What's the idiomatic way to detect sequences of x times the same object (or an object with a specific matching parameter) in an OrderedCollection or Array?
E.g. does the Array contain 10 times the number 5 in a row?
What's the idiomatic way to detect sequences of x times the same object (or an object with a specific matching parameter) in an OrderedCollection or Array?
E.g. does the Array contain 10 times the number 5 in a row?
I'd say that you have to follow a pattern like this:
Maybe I don't know some of useful methods in Pharo, but if you define the ones like:
then the definition can be flattened into:
or for your example:
P.S. I'm not sure about the method names. Maybe
inArrayOf:
can be better thenasArrayOf:
and so on.I like Uko's answer and would like to provide a different solution which addresses the "matching parameter" part of your question. In
SequenceableCollection
define:Now, for example the two following expressions would evaluate to true
Note: If you want the
startingAt: n
version of this method just initializei := n
instead ofi := 1
just before the main loop.EDIT:
And, of course, we can complete the protocol with the following method in
SequenceableCollection
:And the example:
Getting the sequences of repeating objects is as simple as:
If you want to test if there is a run satisfying specific constraints, you can do something like the following:
If you want to test for a certain property of an object instead of object equality, you can easily create a
RunArray
of this property by doing acollect:
on it.So the generalized solution would look something like this:
And then: