I know there are already some very smart solutions
for 'all combinations of length k taken from a set
of length n' f.e. comb1 and combM cooked by R.E. Boss.
I'm just curious. Is the double recursive method
being considered to be a dead end for J or was it just
a starting point to attack the problem with all the
powerful possibilities of J?
Anyway, here's my formulation of combinations, considering
values of x outside the range of (x>0)*.x<:#y as nonsense:
kCn=: 4 : 0
if. x>:#y do. y
else. if. x>1 do. (({.y),.(x-1)kCn}.y),x kCn}.y
else. ,.y end.
end.
)
I avoided the use of elseif. (ending in a useless test)
and a temp var. for }.y
By limiting x on the low side to a minimum of 1
gives me also a considerable speed advantage:
I mean instead of doing:
else. if. x>0 do. (({.y),.(x-1)kCn}.y),x kCn}.y
else. 1 0$0 end.
)
2 kCn 'abcd'
ab
ac
ad
bc
bd
cd
But
r=: i.16
ts '6 comb1 r'
0.00161 604224
compared to
ts '6 kCn r'
0.105149 593152
Is there further improvement possible?
without the use of helper functions :-)
=@@i
+/3&u: 'J.SOFT 6.02'
----------------------------------------------------------------------
For information about J forums see http://www.jsoftware.com/forums.htm