Discuss Scratch
- Discussion Forums
- » Help with Scripts
- » Count the number of occurrences of a substring in a list
- RL1123
-
Scratcher
1000+ posts
Count the number of occurrences of a substring in a list
To clarify, lets say I wanted to count how many ABA were in list:
1.A
2.A - start of #1
3.B
4.A
5.A - start of #2
6.B
7.A
Is there any way to count it with larger lists?
1.A
2.A - start of #1
3.B
4.A
5.A - start of #2
6.B
7.A
Is there any way to count it with larger lists?
- AksharPremnath
-
Scratcher
500+ posts
Count the number of occurrences of a substring in a list
I think it doesn't matter how long a list is in Scratch.
- Oumuamua
-
Scratcher
1000+ posts
Count the number of occurrences of a substring in a list
.
Last edited by Oumuamua (Feb. 26, 2021 08:22:01)
- Oumuamua
-
Scratcher
1000+ posts
Count the number of occurrences of a substring in a list
Please, share your attempt.
Thanks.
Thanks.
- deck26
-
Scratcher
1000+ posts
Count the number of occurrences of a substring in a list
Not difficult, assuming each list item is a single character.
If substring length is L1 set index to 1 and repeat a loop until index + L1 > length of list.
In the loop check if item index matches the first letter of the substring. If you find a match run a loop to check each of the next L1 - 1 items against the appropriate list item until you get to the end of the substring or find a mismatch.
If match found increase count of matches.
Change index by 1 and go back to start of main loop.
This also assumes the substring is not just several of the same character - eg AAA. If you allow that you need to decide whether AAAA contains 2 AAA substrings overlapping or only one either starting at item 1 or at item 2.
If substring length is L1 set index to 1 and repeat a loop until index + L1 > length of list.
In the loop check if item index matches the first letter of the substring. If you find a match run a loop to check each of the next L1 - 1 items against the appropriate list item until you get to the end of the substring or find a mismatch.
If match found increase count of matches.
Change index by 1 and go back to start of main loop.
This also assumes the substring is not just several of the same character - eg AAA. If you allow that you need to decide whether AAAA contains 2 AAA substrings overlapping or only one either starting at item 1 or at item 2.
- deck26
-
Scratcher
1000+ posts
Count the number of occurrences of a substring in a list
Depends a little on whether you want a general answer or a one-off method. @Oumuamua's method is concise if you know what the substring is in advance and it is short enough. I was approaching it from a more general angle where you could input the substring at run-time and the length wouldn't matter.
Both totally valid so it's a case of what you need.
Both totally valid so it's a case of what you need.
- Discussion Forums
- » Help with Scripts
-
» Count the number of occurrences of a substring in a list




