Beefy Boxes and Bandwidth Generously Provided by pair Networks
go ahead... be a heretic
 
PerlMonks  

Re: Minimally changing combinations

by Eily (Prior)
on Jun 28, 2017 at 09:06 UTC ( #1193772=note: print w/replies, xml ) Need Help??


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 ;-)

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1193772]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others perusing the Monastery: (3)
As of 2019-05-26 11:23 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    Do you enjoy 3D movies?



    Results (153 votes). Check out past polls.

    Notices?
    • (Sep 10, 2018 at 22:53 UTC) Welcome new users!