[Jprogramming] J-like approach for merging numbers in a list
Ric Sherlock
tikkanz at gmail.com
Tue Jun 7 21:15:14 UTC 2016
I'm looking for a J-like approach to a verb for merging adjacent numbers in
a row where the numbers are the same. For example
mergerow 4 4 4 4
8 8
mergerow 8 8
16
mergerow 16
16
mergerow 4 4 4
8 4
mergerow 8 4
8 4
mergerow 4 8 8 4
4 16 4
My version below which I've used as part of the answer to a RosettaCode task
<http://rosettacode.org/wiki/2048#J> is very non J-like:
mergerow=: verb define
len=. <:@# y
row=. i. i=. 0
while. (i <: len) *. len >: 0 do.
if. =/ (i , i+1) { y,_9 do.
row=. row, +: i { y
i=. i + 2
else.
row=. row, i { y
i=. i + 1
end.
end.
row
)
I thought I had a good solution with:
mergerow=: rplc (2&# ; +:)&>@~.
But this seemed to cause unpredictable behaviour when used as part of the
whole solution.
More information about the Programming
mailing list