in reply to Pairing the pairs
I think this does the same thing as your code, but is a bit simpler.
#! perl -slw use strict; use warnings; my @array = sort map{ 1+ int rand(8) } 1..36; print "@array"; print '=' x 30; my %X; $X{$_}++ for @array; my @keys = sort { $a <=> $b } keys %X; my %hash; my @pairs; foreach my $x ( @keys ){ foreach my $y ( @keys ){ next if not ( $X{$x} and $X{$y} ) or $x eq $y or defined $hash{$x}{$y}; push @pairs, [$x,$y]; print scalar @pairs, " = $x $y"; $hash{$x}{$y} = $hash{$y}{$x} = 1; $X{$x} -= 1; $X{$y} -= 1; } } print 'Count: ', scalar @pairs;
Why do you use references to anonymous hashes instead of a straight hash? All it does it complicate the syntax for no benefit.
To extend your solution to more than two elements per row, you might be able to use tye's Algorithm::Loops.
I say "might" because your description of the problem is somewhat confusing. You say "A Pair is a set of 2 numbers", "A Row is a set of 'P' such pairs", & "P is a fixed number : Let's take it as 2", which by my reading should mean that each Row (line) in your sample output would consist of P pairs, ie. 2 sets of 2 numbers, but your output only shows one pair?
Overall, I found your description of the problem completely confusing.
What I think you are trying to do is:
Generate the maximum number of unique sets of N unique numbers from a given array of numbers, using each of the (possibly duplicated) numbers in the input array exactly as many times as it appears in the input array.
Does that sum up your intent?
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Re: Pairing the pairs
by artist (Parson) on Jun 13, 2003 at 02:36 UTC |