Count the number of identical instances in an array

How do I find the number of identical values in an array?

I have an array populated with X positions and I would like to count the number of instances an X position occurs.

i.e.
416, 417, 416, 417

I can loop through the array but I can’t figure out how the comparison works to basically check if a value equals an existing x value

Edit: I just realized you want to find the number of identical values my mistake. Let me think about it

Have you tried the array tools extension?
(edit: IDK if this would help here but it is a good tool)
https://wiki.gdevelop.io/gdevelop5/extensions/array-tools/#array-tools

To do it with your current technique, it would need a variable to go through the indexes.

Updated
Set Counter to 0
Set matches = 0

While event
Counter < number of children in the array

Sub event of the while event
arrayX[Counter] = X value you’re looking for
Set matches plus 1

Sub event of the while event
Counter plus 1

This would loop through and add 1 to matches if a match was found. If the original number was in the array as well then it would be more the number of ocourances since that number would also be counted.

Alternatively, you could use a for each child with the same technique minus the counter and you wouldn’t compare the variable[index] you would compare the value of the variable in the for each child event(the default variable name is child)

IDK which technique is faster. Also, you. Could use a repeat number of children times.

thanks Keith,

I’ve tried to code it up, however it seems to be stuck in an infinite loop? Is there something I’m missing?

There are at least 2 methods. Using a while event, you would only need 1 while event. The current events were only increasing the counter when there was a match. So, it got stuck in an endless loop.

Since you’re counting all of the value in the array, you could use for each child

Variables used
image

fantastic thanks so much Keith!!

1 Like