Home › Forums › kdb+ › Challenge 1 – Triangle Font › Re: Challenge 1 – Triangle Font
-
BaiChens solution uses the Scan form of the Do iterator
rather than the Each iterator
'
I used.Terse q helps us focus on the core of the algorithm. Lets use BaiChens solution as a practice example.
We can rewrite to eliminate the local variable. And, all other things being equal, good q style prefers infix syntax to bracket notation.
q)8{first[x+1]#x+1}1 1 2 2 3 3 3 4 4 4 4 5 5 5 5 5 6 6 6 6 6 6 7 7 7 7 7 7 7 8 8 8 8 8 8 8 8 9 9 9 9 9 9 9 9 9
The addition surely only needs doing once?
q)4{first[b]#b:x+1}1 1 2 2 3 3 3 4 4 4 4 5 5 5 5 5
On each iteration the vector argument lengthens. But we need increment only its first item.
q)4{b#b:1+first x}1 1 2 2 3 3 3 4 4 4 4 5 5 5 5 5
The pattern
N f1
is easily recognisable as: Dof
N times, starting with 1.Tightening up the algorithm saves CPU, but the Each is faster still.
q)ts:10000 {b:first x+1;b#x+1}[100;1] 438 64560 q)ts:10000 100{b#b:1+first x}1 301 63536 q)ts:10000 {x#'x} 1+til 100 174 63616
On the next episode of the Array Cast (just recorded on Tuesday), Michael Higginson talks about how the terse and interactive APL and q REPLs encourage him to compare multiple solutions in a way he would rarely have time to do when writing Java.