sub mixedgray_iterator { my @domains = @_; my @sizes = map { scalar @$_ } @domains; die "all items must have at least two positions" if grep {$_<2} @sizes; my @cur_indices = (0) x @domains; my @pos_to_loop_next = 0 .. @domains; my @dir = (1) x @domains; my $done; return sub { return undef if $done; my $rv = [map {$domains[$_][$cur_indices[$_]]} 0..$#domains]; if ($pos_to_loop_next[0]==@domains) { $done=1; return $rv } (my $domain,$pos_to_loop_next[0]) = ($pos_to_loop_next[0], 0); $cur_indices[$domain] += $dir[$domain]; if ($cur_indices[$domain]==0 || $cur_indices[$domain]==$sizes[ +$domain]-1) { $dir[$domain] = -$dir[$domain]; $pos_to_loop_next[$domain] = $pos_to_loop_next[$domain+1]; $pos_to_loop_next[$domain+1] = $domain+1; } return $rv; } }
thanos1983's references include Algorithm::Loops, its NestedLoots could be wrangled into producing what I'm looking for.
Thanks Eily "Gray code" was the term I'd forgotten (and "Hamming Distance" too) and nice compact code there!
Turns out my post was an "XY" problem. Like the authors of some combination modules, I'm running tests with all combinations of options. In these tests, each time an option changes, there's expensive setup to run first. My thought was to take the Gray-code-like sequence, and then compare each iteration with the values from the previous to see which setup code to run.
Or in other words, I want a sequence of "change option K to value V". Working on it!
In reply to Re: Minimally changing combinations
by Yary
in thread Minimally changing combinations
by Yary
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |