http://www.perlmonks.org?node_id=1193772


in reply to Minimally changing combinations

That sounds Gray-ish. Except this article deals pretty well with cases where all subsets have the same number of elements, which does not seem to be your case according to your example.

If I'm not wrong, when you have @right, a list where your ordering is respected, and @left, a list of elements you can use the following algorithm:

Take the first element of @left, combine it with all elements of @righ +t Take the second element of @left, combine it with all elements of reve +rse @right Take the third element of @left, combine it with all elements of @righ +t ...
Because you reverse the right part each time you change the left element, you are sure that only one element changes (the left part), because you'll either be using the last or first element of @right twice in a row. This lets you scale up your N-uples recursively. Which in perl gives:
use v5.20; use strict; use warnings; use Data::Dump qw( pp ); sub combine { my ($left, $right) = @_; my @out; my $reverse = 0; for my $el (@$left) { push @out, map { [ $el, ref $_ ? @$_ : $_ ] } ($reverse ? reverse +@$right : @$right); $reverse = !$reverse; } return \@out; } pp combine ['A' .. 'F'], combine ['a'..'d'], [1..8]; pp combine [1..3], combine [1..4], [1..3];

I've just tested those sets and looked if I could find somewhere where the rule was not respected, my advice would be to test it properly though. And haukex's proposed solution might be better, the python page does mention gray coding so that's promising.

Edit: and actually implementing that as a recursive sub is left as an exercise to the reader ;-)