Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl: the Markov chain saw
 
PerlMonks  

Re: random pairs

by BillKSmith (Monsignor)
on Jul 13, 2012 at 20:10 UTC ( [id://981713]=note: print w/replies, xml ) Need Help??


in reply to random pairs

The second numbers of each pair must be the numbers 0 through 99 in random order. Code this directly.

use List::Util qw( shuffle ); my $n = 0; my @pairs = map { [$n++, $_] } shuffle( 0..99 );

Update: Sorry guys, I misread the spec.

Replies are listed 'Best First'.
Re^2: random pairs
by CountZero (Bishop) on Jul 13, 2012 at 20:31 UTC
    I understood that the second element of each pair was to be a random number between 0 and 99. I did not read in the specs that there should be no repeats.

    Also it is very well possible that your method yields a combination, the reverse of which is also in the set. Suppose your shuffle yields the list 99 to 0. In that case, every result's reverse is in the set.

    CountZero

    A program should be light and agile, its subroutines connected like a string of pearls. The spirit and intent of the program should be retained throughout. There should be neither too little or too much, neither needless loops nor useless variables, neither lack of structure nor overwhelming rigidity." - The Tao of Programming, 4.1 - Geoffrey James

    My blog: Imperial Deltronics
Re^2: random pairs
by Perlbotics (Archbishop) on Jul 13, 2012 at 20:26 UTC

    Unfortunately, that algorithm does not avoid unwanted pairs like [1,23] and [23,1].

    Here is a naive try until it works approach:

    use strict; use warnings; use List::Util qw(shuffle); my (%keys, @rnds, @pairs); do { %keys = (); @rnds = shuffle (0..99); @pairs = map{ my $r = $rnds[$_]; $keys{"$_,$r"}++; $keys{"$r,$_"}++; [ $_, $r ] } (0..99); } while ( scalar keys %keys != 200 ); # no symmetry means 200 distinct + pairs # @pairs = shuffle( @pairs ); # uncomment if wanted printf( "%3d %3d\n", @{$pairs[$_]}) for (0..99);

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others having an uproarious good time at the Monastery: (4)
As of 2024-04-19 22:30 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found