Imagine you're generating the Fibonacci numbers using the obvious, brute-force algorithm. If I know the number of Fibonaccis I want to generate in advance, I can do something like this using the power conjunction ^:
:
(, [: +/ _2&{.)^:20 i.2
How can I instead stop when the Fibonaccis reach some limit, say 1e6
? (I know how to do this inside a function using while.
, but that's no fun.)
I want to stress that this is a general question about J, not a specific question about Fibonacci. Don't get too distracted by Fibonacci numbers. The heart of the question is how to keep appending to a list until some condition is met.
Power has also a verb form u^:v^:n
where the second verb can be used as a check. Eg: double (+:
) while (n
is _
) less than 100 (100&>
):
+:^:(100&>)^:_ ] 1
128
+:^:(100&>)^:_ ] 3
192
As usual, to append to the result of power, you box the noun:
+:^:(100&>)^:(<_) ] 3
3 6 12 24 48 96 192
I think the best answer to this is in Henry Rich's book J for C programmers. Specifically, it using the Power Conjunction ^:
. You can also use it to converge until there is no change, so that the limit would not need to be defined. Henry uses the example that:
2 *^:(100&>@:])^:_"0 (1 3 5 7 9 11)
128 192 160 112 144 176
The ^:_
Power Conjunction repeats until there is no change and the ^:(100&>@:])
tests for the result being less than 100. If it is then ^:
is applied to 1
and the loop 2*
is done again, if it is not less than 100 then ^:
would be applied to 0
and that results in it doing nothing and nothing changes and the loop exits. The fact that it use "0
as the rank means that it can apply the doubling function 2*
to each of 1 3 5 7 9 11
individually.
Henry really does explain the process better than I, so here is the reference for further reading. http://www.jsoftware.com/help/jforc/loopless_code_iv_irregular_o.htm#_Toc191734389
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With