Loops/Wrong ranges: Difference between revisions

Content added Content deleted
(→‎{{header|J}}: another approach)
Line 1,224: Line 1,224:


</pre>
</pre>

===Another approach===

<syntaxhighlight lang=J>genrange=: {{
'start stop increment'=. y
start+increment*i.1+<.(stop-start)%increment
}}</syntaxhighlight>

Here, we generate n values (where n is defined based on the difference between the start and stop values, scaled by the increment), and scale them according to the increment and adjust the origin to match the start value.

That said, since J treats a negative n as a reversed sequence, what we get here is a truncated projection backwards from the start value when the increment would never reach the stop value:

<syntaxhighlight lang=J> genrange 9 2 _2 NB. valid
9 7 5 3
genrange _2 2 1 NB. valid
_2 _1 0 1 2
genrange _2 2 0 NB. invalid: requires at least an infinity of values
|domain error: genrange
genrange _2 2 _1 NB. projects backwards from _2
_4 _3 _2
genrange _2 2 10 NB. valid
_2
genrange 2 _2 1 NB. projects backwards from 2
4 3 2
genrange 2 2 1 NB. valid (increment is irrelevant)
2
genrange 2 2 _1 NB. valid (increment is irrelevant)
2
genrange 2 2 0 NB. valid (increment is irrelevant)
2
genrange 0 0 0 NB. valid (increment is irrelevant)
0</syntaxhighlight>

As an aside, J's range generation function <code>i.</code> generates indices starting from 0 and not reaching the absolute value of its argument. This corresponds to integers in the [[wp:Interval_(mathematics)|interval]] [0,n). So we add 1 to n so that our range includes the end of the interval. However, when n is negative, adding 1 to n shortens the interval rather than extending it. So, when we "project backwards" we're 2 elements short of the number we would have expected if the sign of the interval had been reversed.


=={{header|Java}}==
=={{header|Java}}==