loading...

re: Daily Challenge #17 - Double Trouble VIEW POST

FULL DISCUSSION
 

Some Smalltalk
Defining a subclass of Array that would act like an "infinite collection" (just because it is fun).

Class {
    #name : #DoubleCola,
    #superclass : #Array,
    #type : #variable,
    #category : #''
}

{ #category : #accessing }
DoubleCola >> at: anIndex [
    ^ anIndex <= self size
        ifTrue: [ super at: anIndex ]
        ifFalse: [ self at: anIndex inGroup: 1 ]
]

{ #category : #accessing }
DoubleCola >> at: anIndex inGroup: anIteration [
    ^ anIndex <= (self groupSize: anIteration)
        ifTrue: [ (self group: anIteration) at: anIndex ]
        ifFalse: [ self
                at: anIndex - (self groupSize: anIteration)
                inGroup: anIteration + 1 ]
]

{ #category : #accessing }
DoubleCola >> group: anInteger [
    ^ self
        flatCollect: [ :aPlayer | (1 to: 2 ** anInteger) collect: [ :i | aPlayer ] ]
        as: OrderedCollection
]

{ #category : #accessing }
DoubleCola >> groupSize: anIteration [
    ^ self size * (2 ** (anIteration - 1))
]

To execute:

(DoubleCola withAll: #( Sheldon Leonard Penny Rajesh Howard )) at: 3. "#Penny"
(DoubleCola withAll: #( Sheldon Leonard Penny Rajesh Howard )) at: 7. "#Sheldon"
(DoubleCola withAll: #( Sheldon Leonard Penny Rajesh Howard )) at: 8. "#Leonard"
code of conduct - report abuse