Beefy Boxes and Bandwidth Generously Provided by pair Networks
Think about Loose Coupling
 
PerlMonks  

Re: combinations of multiple variables which can assume multiple values

by choroba (Cardinal)
on Mar 16, 2018 at 16:21 UTC ( [id://1211059]=note: print w/replies, xml ) Need Help??


in reply to combinations of multiple variables which can assume multiple values

It's not clear what output you expect. Are you missing the following?
[ [1,"a"], [2,"b"], [3,"b"] ], [ [1,"b"], [2,"a"], [3,"b"] ]

If so, the following should work:

#!/usr/bin/perl use warnings; use strict; my @a = (1, 2, 3); my @b = qw( a b ); my @expected = ( [ [1, "a"], [2, "a"], [3, "a"] ], [ [1, "a"], [2, "a"], [3, "b"] ], [ [1, "a"], [2, "b"], [3, "a"] ], [ [1, "b"], [2, "a"], [3, "a"] ], [ [1, "b"], [2, "b"], [3, "a"] ], [ [1, "b"], [2, "b"], [3, "b"] ], # [ [1, "a"], [2, "b"], [3, "b"] ], # [ [1, "b"], [2, "a"], [3, "b"] ], ); my %reverse_b; @reverse_b{@b} = 0 .. $#b; my @c = [ map [ $_, $b[0] ], @a ]; while (1) { my @indexes = map $reverse_b{ $_->[1] }, @{ $c[-1] }; my $r = $#indexes; while ($r >= 0) { if (++$indexes[$r] > $#b) { $indexes[$r--] = 0; } else { last } } last if $r < 0; push @c, [ map [ $a[$_], $b[ $indexes[$_] ]], 0 .. $#a ]; } use Test::More; use Test::Deep; cmp_deeply \@c, bag @expected; done_testing();

Update: I forgot to mention: It works for any size of both the arrays.

($q=q:Sq=~/;[c](.)(.)/;chr(-||-|5+lengthSq)`"S|oS2"`map{chr |+ord }map{substrSq`S_+|`|}3E|-|`7**2-3:)=~y+S|`+$1,++print+eval$q,q,a,

Replies are listed 'Best First'.
Re^2: combinations of multiple variables which can assume multiple values
by jgraeve (Novice) on Mar 16, 2018 at 16:47 UTC
    This is exactly what I needed. Thank you so much.

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others making s'mores by the fire in the courtyard of the Monastery: (3)
As of 2024-04-26 02:16 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found