An idiomatic way to detect sequences x times of the same object in an array in Smalltalk?

What is the idiomatic way to detect sequences x times the same object (or an object with a specific matching parameter) in an ordered set or array?

eg. Does the array 10 times contain the number 5 in a row?

+4
source share
3 answers

Getting sequences of repeating objects is as simple as:

({ 1. 1. 2. 2. 2. 5. 5. 3. 9. 9. 9. 9. } as: RunArray) runs 
=> #(2 3 2 1 4)

If you want to check if there is an execution that satisfies certain restrictions, you can do something like the following:

meetsConstraint := false.
({ 1. 1. 2. 2. 2. 5. 5. 3. 9. 9. 9. 9. } as: RunArray) runsAndValuesDo: [:run :value | 
    meetsConstraint := (value = 9 and: [run > 3])].

, RunArray , collect: .

, :

SequenceableCollection >> containsRunOf: anElement withAtLeast: nElements
    (self as: RunArray) runsAndValuesDo: [:run :value | 
        (value = anElement and: [run >= nElements]) ifTrue: [^ true]].
    ^ false

:

({ 'aa'. 'bb'. 'c'. 'ddd'. } collect: [:each | each size])
    containsRunOf: 2 withAtLeast: 3
=> false
+3

Uko , " " . SequenceableCollection define:

contains: m consecutiveElementsSatisfying: block
    | n i |
    self isEmpty ifTrue: [^m = 0].
    n := self size - m + 1.
    i := 1.
    [i <= n] whileTrue: [| j |
        (block value: (self at: i)) ifTrue: [
            j := 2.
            [j <= m and: [block value: (self at: i + j - 1)]]
                whileTrue: [j := j + 1].
            j > m ifTrue: [^true]].
        i := i + 1].
    ^false

, , true

#(2 1 1 1 2) contains: 3 consecutiveElementsSatisfying: [:e | e = 1]
#(2 1 0 1 2) contains: 3 consecutiveElementsSatisfying: [:e | e squared = e]

. , startingAt: n i := n i := 1 .

EDIT:

, , SequenceableCollection:

contains: m consecutiveTimes: anObject
    ^self contains: m consecutiveElementsSatisfying: [:e | e = anObject]

:

#(2 1 1 1 2) contains: 3 consecutiveTimes: 1
+4

I would say that you should follow a pattern like this:

(collectionToTest
  indexOfSubCollection: (
    Array
      new:     numberOfRepetitions
      withAll: desiredObject)
    startingAt: 1
) isZero not

Maybe I don’t know some useful methods in Pharo, but if you define such as:

SequenceableCollection >> indexOfSubCollection: aSubCollection
  ^ aSubCollection indexOfSubCollection: aSubCollection startingAt: 0

SequenceableCollection >> containsSubCollection: aSubCollection
  ^ (aSubCollection indexOfSubCollection: aSubCollection) isZero not

Object >> asArrayOf: aLength
  ^ Array new: aLength withAll: self

then the definition can be smoothed to:

collectionToTest containsSubCollection:
  (desiredObject asArrayOf: numberOfRepetitions)

or for your example:

anArray containsSubCollection: (5 asArrayOf: 10)

PS I'm not sure about method names. Maybe, inArrayOf:maybe better asArrayOf:, etc.

+3
source

All Articles