在 Smalltalk 中检测数组中 x 次相同对象的序列的惯用方法



在 OrderedCollection 或 Array 中检测 x 次相同对象(或具有特定匹配参数的对象)的序列的惯用方法是什么?

例如,数组是否连续包含数字 5 的 10 倍?

我喜欢

Uko 的答案,并希望提供一个不同的解决方案来解决您问题的"匹配参数"部分。在SequenceableCollection中定义:

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

编辑:

当然,我们可以在SequenceableCollection中使用以下方法完成协议:

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

和例子:

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

获取重复对象的序列非常简单:

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

如果要测试是否存在满足特定约束的运行,可以执行以下操作:

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])].

如果要测试对象的某个属性而不是对象相等性,可以通过对此属性执行collect:来轻松创建此属性的RunArray

因此,广义解决方案如下所示:

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
我会

说你必须遵循这样的模式:

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

也许我不知道Pharo中的一些有用的方法,但是如果您定义以下方法:

SequenceableCollection >> indexOfSubCollection: aSubCollection
  ^ aSubCollection indexOfSubCollection: aSubCollection startingAt: 0
SequenceableCollection >> containsSubCollection: aSubCollection
  ^ (aSubCollection indexOfSubCollection: aSubCollection) isZero not
Object >> asArrayOf: aLength
  ^ Array new: aLength withAll: self

然后将定义展平为:

collectionToTest containsSubCollection:
  (desiredObject asArrayOf: numberOfRepetitions)

或者对于您的示例:

anArray containsSubCollection: (5 asArrayOf: 10)

附言我不确定方法名称。也许inArrayOf:可以比asArrayOf:更好,等等。

最新更新