Minecraft command to remove duplicate entities

minecraft-commandsminecraft-java-edition

I am making a wireworld cellular automata, and everything is going well except for one thing: placing "wire" cells on both sides of an "empty" cell and filling the gap afterwards causes TWO "WireCell" entities instead of one because of the flood-fill method that I am using. How can I remove all but one entity from each block?

Best Answer

you said you found out how to do it, but I'll just give this answer to show other people how to do it,

I did it in three command blocks (five if you include the two command blocks I used to make it loop, could make it loop with only one extra though)

first you'll need a scoreboard objective

/scoreboard objectives add near dummy

first set all of the sheep's scores to zero

/scoreboard players set @e[type=Sheep] near 0

this command makes each sheep in a stack add one to one other sheep in the stack, basically it counts how many is in each stack

/execute @e[type=Sheep,r=50] ~ ~ ~ /execute @e[r=0,type=Sheep,c=1] ~ ~ ~ /scoreboard players add @e[r=1,type=Sheep] near 1

then you kill one sheep that has a score that is more then two

/execute @e[type=Sheep,c=1,score_near_min=2] ~ ~ ~ /kill @e[r=0,c=1,type=Sheep]

loop the above three commands, until all sheep have a score of 1

note: I used the scoreboard objective "near" but you can use what ever you want, as long as you change the name in each command

same with the entity type, just make sure you get every time it says type=Sheep, I counted six occurrences