Appending a counter is the easiest. Since we never reverse more elements than there are in the list, we don't even have to bother with removing the counter. Here's my code.
topswap =: [: {: [: (>:@{: _1} ((|.@{. , }.)~ {.))^:(1~:{.)^:_ ,&0 topswap 2 4 1 3 4 The part inside the while loop is (>:@{: _1} ((|.@{. , }.)~ {.)). You'll recognize the right half of the fork as topswap from your message, and the rest simply replaces the last element with its successor. Then we only have to maximize this over all permutations. To generate all permutations of (>:i.y), we have allperms =: i.@! A. >:@i. So one solution to the problem is topswaps =: [: >./ topswap"1@:allperms Of course this is rather inefficient. For an efficient solution I advise copying the C algorithm. Marshall On Mon, Nov 26, 2012 at 09:19:37PM -0500, David Ward Lambert wrote: > Reference: http://rosettacode.org/wiki/Topswops > What are good ways to count iterations? > > While=: 2 : 'u^:v^:_' > > topswop=: (|.@:{. , }.)~ {. > > topswop While (1 ~: {.) 2 4 1 3 > 1 2 3 4 > > These ideas seem like structural nightmares: > * separate data and counter with boxes; > * append a counter to the data; > * explicit code with a global noun; > * +/@:(0 = (0,~topswop)While(1 ~: {.)) NB. <laughs>. > > The boxes or explicit code seem most general. > > Thank you, Dave. > > Bonus: find a definition topswop using C. > > ---------------------------------------------------------------------- > For information about J forums see http://www.jsoftware.com/forums.htm ---------------------------------------------------------------------- For information about J forums see http://www.jsoftware.com/forums.htm