strange behavior in workspace

Previous Topic Next Topic
 
classic Classic list List threaded Threaded
2 messages Options
Reply | Threaded
Open this post in threaded view
|

strange behavior in workspace

larrry
I'm messing about with Project Euler problems and have noticed some behavior that I don't understand.  This one happens to be very self-contained so I though I'd as for assistance.

This code (which doesn't solve the problem, btw) is buggy, but I can't see the bug and I'm beginning to suspect something in the VM or the class libraries. When I execute it, two odd things happen:

First, in spite of the block test [sum < 100] whileTrue:[...]  it continues to run when sum > 100 (or a million for that matter).  

Second, the block in the line:
(sum isPrime) ifTrue: [ (seq size > bestSeq size) ifTrue: [ bestSeq := seq copy.]]
executes even when sum is not a prime number.

Any help is appreciated. 
-------------------------------
"Create a list of primes smaller than a million"
primes := OrderedCollection new.
2 to: 999999 do: [ :n | n isPrime ifTrue: [ primes add: n]].

bestSeq := OrderedCollection new.
seq := OrderedCollection new.
sum := 0.
[sum < 100] whileTrue: [
primes do: [:prime | 
seq add: prime.
sum := seq sum.
(sum isPrime) ifTrue: [ (seq size > bestSeq size) ifTrue: [ bestSeq := seq copy.]]
]
].
Reply | Threaded
Open this post in threaded view
|

Re: strange behavior in workspace

larrry
Ok. figured it out. whileTrue: only evaluates at the end of each block so it didn't evaluate.
I guess ignorance is not bliss, after all. 

On Sun, Jan 8, 2012 at 10:05 AM, Larry White <[hidden email]> wrote:
I'm messing about with Project Euler problems and have noticed some behavior that I don't understand.  This one happens to be very self-contained so I though I'd as for assistance.

This code (which doesn't solve the problem, btw) is buggy, but I can't see the bug and I'm beginning to suspect something in the VM or the class libraries. When I execute it, two odd things happen:

First, in spite of the block test [sum < 100] whileTrue:[...]  it continues to run when sum > 100 (or a million for that matter).  

Second, the block in the line:
(sum isPrime) ifTrue: [ (seq size > bestSeq size) ifTrue: [ bestSeq := seq copy.]]
executes even when sum is not a prime number.

Any help is appreciated. 
-------------------------------
"Create a list of primes smaller than a million"
primes := OrderedCollection new.
2 to: 999999 do: [ :n | n isPrime ifTrue: [ primes add: n]].

bestSeq := OrderedCollection new.
seq := OrderedCollection new.
sum := 0.
[sum < 100] whileTrue: [
primes do: [:prime | 
seq add: prime.
sum := seq sum.
(sum isPrime) ifTrue: [ (seq size > bestSeq size) ifTrue: [ bestSeq := seq copy.]]
]
].