--- Begin Message ---
Well my main run method looks like this:
run
        | op | 
        ram := self input.
        in := ReadStream on: ram.
        [ (op := in next) = 99 ] whileFalse: [ self processOpcode: op ].
        ^self at: 0.

ram is the array of integers.
in is a ReadStream on them which lets me process them in order.
They are both instance variables.

self input provides a clean copy of the program memory (the integer array).  I 
just used an array literal.  No file IO.

The main dispatch method is

processOpcode: op 

        op = 1 ifTrue: [ ^self processAdd ].
        op = 2 ifTrue: [ ^self processMultiply ].

and for illustration 

processAdd
        | a b c |
        a := self at: in next.
        b := self at: in next.
        self at: in next put: a+b

There are custom versions of at: and at:put: that compensate for zero based vs 
one based array indexing.

at: idx
        ^ram at: idx + 1

I hope this helps you out.

> On Dec 17, 2019, at 6:59 AM, Roelof Wobben via Pharo-users 
> <pharo-users@lists.pharo.org> wrote:
> 
> 
> From: Roelof Wobben <r.wob...@home.nl>
> Subject: how can I this refractor this so its more smalltalk
> Date: December 17, 2019 at 6:59:28 AM PST
> To: Any question about pharo is welcome <pharo-users@lists.pharo.org>
> 
> 
> Hello,
> 
> My solution to day2 part1 is right this :
> 
> processData: instructions
>     | opcode index firstNumber secondNumber placeToPut firstNumberIndex 
> secondNumberIndex |
>     index := 1.
>     opcode := instructions at: index.
>     [ opcode ~= 99 ]
>         whileTrue: [ firstNumberIndex := instructions at: index + 1.
>             secondNumberIndex := instructions at: index + 2.
>             firstNumber := instructions at: firstNumberIndex + 1.
>             secondNumber := instructions at: secondNumberIndex + 1.
>             placeToPut := (instructions at: index + 3) + 1.
>             opcode == 1
>                 ifTrue: [ instructions at: placeToPut put: firstNumber + 
> secondNumber ].
>             opcode == 2
>                 ifTrue: [ instructions at: placeToPut put: firstNumber * 
> secondNumber ].
>             index := index + 4.
>             opcode := instructions at: index ].
>     ^ instructions at: 1
> 
> so its ugly code
> 
> is there a way  I can this more the smalltalk way by using streams or 
> something else.
> if so, is there someone who can tell me or can let me see how to make this 
> cleaner code
> 
> Roelof
> 
> 
> 
> 


--- End Message ---

Reply via email to