Forum

How to count repeated elements?

Hi!
I am trying to count repeated elements of a spread. The example used in the patch is:

Given String: aabcccdeee
desired Result:
a:2
b:1
c:3
d:1
e:3

I have tried some approaches - without success.

count repeated elements.vl (19.2 KB)
In the attached patch I have tried to compare a splice with the following slice of the given spread - but from there I have no idea on how to proceed.

I also googled the problem (adding “c#”, thanks for the hint, @sebl!), but I don’t know what to do with the result:
One answer has been:
“It seems the array is sorted (According to the example). If so you just have to pick the first element and iterate through the array until a distinct value is found. Within this process you can have a counter within loop to count the occurences.
Then pick the found distinct value instead of first element and repeat the process.” https://stackoverflow.com/questions/851716/count-repeated-elements-in-an-array

I’m not even sure if that can be implemented in VL - let alone, how to do it! :-)

So, any help is much appreciated!
Thanks a lot in advance!

08

1 Like

with linq:

i have to admit one has to become comfortable with this linq stuff…

count repeated elements Linq.vl (15.2 KB)

e:
notice how easy this could be extended if you want to count the distincts of more complex objects.

2 Likes

this is a nice example on how to generalize such things.

image

count repeated elements Linq.vl (52.0 KB)

2 Likes

Thank you both very much!
Linq (being completely new to me) looks very interesting!
I feel like I have to get my head around the new datatypes in gamma ( char, sequence, hashset, list etc.) and how to transform them to other datatypes; also when to use what. But your patches are great starting points for that, and I definetely see how powerful things can get!
Thanks a lot!