in reply to random pairs

Without retries
use strict; use warnings; my %pairs; my @left = (0,1,2,5,7,8,10); #put your own predetermined numbers foreach my $val1 (@left){ my @right = (); foreach my $val2 (0..99){ push(@right, $val2) if $val1 != $val2 && (!exists $pairs{$val2} || + $pairs{$val2} != $val1); } $pairs{$val1} = $right[int(rand($#right+1))]; } foreach(@left){ print $_, ',', $pairs{$_}, ' '; }
Update: modified condition so that it works correctly when there's a zero in the predetermined numbers. Also clean under 'use warnings;' now.

Replies are listed 'Best First'.
Re^2: random pairs
by CountZero (Bishop) on Jul 14, 2012 at 12:01 UTC
    This will breakdown when your list of predetermined numbers contains duplicates.

    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