Loops/With multiple ranges: Difference between revisions

→‎{{header|Smalltalk}}: an alternative (better ?)
(→‎{{header|Smalltalk}}: an alternative (better ?))
Line 1,763:
Transcript show:' sum = '; showCR:sum.
Transcript show:'prod = '; showCR:prod</lang>
 
As an alternative to the first solution above, we could loop over the ranges. This avoids the concatenations and possible generation of the intermediate big collection - which does not make a difference here, but would, if each collection consisted of millions of objects):
<lang smalltalk>...
{
(three negated to: 3**3 by: three ) .
(seven negated to: seven by: x ) .
(555 to: 550-y ) .
(22 to: -28 by: three negated) .
(1927 to: 1939 ) .
(x to: y by:z ) .
(11**x to: 11**x + one ) .
} do:[:eachRange |
eachRange
select:[:j | ((prod abs < (2**27)) and:[ j ~= 0 ]) ]
thenDo:[:j | prod := prod*j ].
]
].
...</lang>
Notice: this also shows an alternative element selection scheme, which may be more readable.
{{out}}
<pre> sum = 348173
Anonymous user