Count adjacent occurrences of a string in an array

Just started using Construct 2? Post your questions here

Post » Sun Mar 01, 2015 7:49 pm

In my game I am populating an array with one of several strings based on player input. I would like to count the number of occurrences of the string in the array, but only if those occurrences are next to each other in the array. E.g. if I'm counting the number of occurrences of "cat" in my array the following should be returned:

("cat", "dog", "cat", "dog") - should only return a count of 1 as the two occurrences of "cat" are separated by dog

("cat", "cat", "dog", "cat") - should return a count of 2

("cat", "cat", "cat", "dog") - should return a count of 3

Any suggestions/pointers appreciated.
B
5
Posts: 7
Reputation: 239

Post » Sun Mar 01, 2015 8:46 pm

One way would be to use RegexSearch(String, Regex, Flags) but that would require that you convert the array row content to a string first.

If you did something like... RegexSearch(YourArrayAs.String, "dog", "gi")
on this row ("cat", "dog", "cat", "dog"), converted into a string that looks like this "catdogcatdog" would return the index 4.
You then know that there are only 1 "cat" before you found a "dog", because the word "cat" is build from 3 letters, and there are 3 letters before you found the stop.

This would be complicated if you dont know all the words in the array. But if you know the lenght of the words you are looking for then it would be doable.
"catcatcatdog" would return the index 10, so 10 would equal 3
Frosty Elk AB
www.frostyelk.se
Have no fear, We come in peace!
B
13
S
3
G
1
Posts: 106
Reputation: 1,169

Post » Sun Mar 01, 2015 10:09 pm

I know all the words in the array (there are only four) but the count I'm performing won' be on any specific word, it will be on all of them. I.e. I want to pick out the word that appears most frequently (as long as it's next to other appearances of the word) each time I check the array.

To make things easier I could have all the words be a fixed number of characters or Instead of words/strings, I could place numbers in the array. E.g. cat = 0, dog = 1, fish = 2, rat = 3. Would you suggest something different in this case?

Not sure what the third parameter ("gi") represents in your example.
B
5
Posts: 7
Reputation: 239

Post » Sun Mar 01, 2015 10:11 pm

Just keep a counter variable with initial value 1, and loop through the array keeping track of the 'current' and 'previous' array values. If current=previous, add 1 to the counter otherwise stop the loop. You should have your count.

BTW your descriptions are a little ambiguous but I'm going with what I think you're asking for.
B
24
S
9
G
4
Posts: 1,646
Reputation: 6,596


Return to Beginner's Questions

Who is online

Users browsing this forum: No registered users and 1 guest