Here's what I came up with:
#!/usr/bin/env perl use strict; use warnings; for my $X (3 .. 7) { for my $Y (2 .. 8) { my @orig = ((map {"X$_"} 0 .. $X),(map {"Y$_"} 0 .. $Y)); my @wanted = ((map {"Y$_"} 0 .. $Y),(map {"X$_"} 0 .. $X)); print "@orig\n"; swap($X+1, \@orig, \@wanted); my $fl = 'Y'; for (0 .. $#wanted) { if ($orig[$_] ne $wanted[$_]) { $fl='N'; $orig[$_]=lc($orig[$_]); } } print "@orig ($fl)\n\n"; } } sub swap { my ($ofs, $list) = @_; my ($cnt, $src, $dst, $cmp, $tmp); $cnt = @$list; $dst = $cmp = 0; $tmp = $list->[$dst]; while ($cnt--) { $src = ($dst+$ofs) % @$list; if ($src == $cmp) { # Loop detected, finish it and start next one $list->[$dst] = $tmp; $dst = ++$cmp; $tmp = $list->[$dst]; } else { $list->[$dst] = $list->[$src]; $dst = $src; } } }
The two tricks are: (1) You never have to subtract from your pointers, and (2) you have to detect loops when your pointers have a smaller loop size than the buffer size.
Update: It took me a bit of time to get back to this, and I posted it before reviewing the thread. It turns out that graf already described the algorithm, as did hdb.
...roboticus
When your only tool is a hammer, all problems look like your thumb.
In reply to Re: [OT] Swapping buffers in place.
by roboticus
in thread [OT] Swapping buffers in place.
by BrowserUk
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |