Count adjacent occurrences of a string in an array

0 favourites
  • 4 posts
From the Asset Store
Supports 1D, 2D, 3D arrays. Import and export arrays in JSON format
  • 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.

  • Try Construct 3

    Develop games in your browser. Powerful, performant & highly capable.

    Try Now Construct 3 users don't see these ads
  • 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

  • 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.

  • 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.

Jump to:
Active Users
There are 1 visitors browsing this topic (0 users and 1 guests)