in reply to Random Couple Script

He he! But is it fair?

#! perl -slw use strict; local $, = ' '; my @array; splice @array, rand( @array ), 0, $_ for map{ /^..(.*$)/ } <DATA>; my %partners = @array; print %partners; __DATA__ 1.bobby 2.jane 3.charleen 4.markus 5.gabriel 6.Alex

Examine what is said, not who speaks.
"Efficiency is intelligent laziness." -David Dunham
"Think for yourself!" - Abigail
"Memory, processor, disk in that order on the hardware side. Algorithm, algorithm, algorithm on the code side." - tachyon

Replies are listed 'Best First'.
Re^2: Random Couple Script
by thospel (Hermit) on Nov 09, 2004 at 12:02 UTC
    Heh, this code is the most interesting of the lot since it *seems* wrong.

    If the splice line had been

    splice @array, rand(1+@array ), 0, $_ for map{ /^..(.*$)/ } <DATA>;
    it would obviously have been fair. Now it seems to have a slight preference for left, so that makes you worry that e.g. maybe the last two elements don't get paired often enough. But that impression is wrong. The bias only causes the order inside one pair to be lopsided. The element inserted first becomes the last element in @array, and will remain last during the loop. The other n-1 elements will get a fair shuffle. So after pairing the result is fair, but the first element inserted will always be last in its pair.
Re^2: Random Couple Script
by Roy Johnson (Monsignor) on Nov 09, 2004 at 15:05 UTC
    Using splice to deconstruct the list, instead of to construct it:
    # Read names, chop off numbers my @names = map /\.(.*)/, <DATA>; # Pair them up randomly for (1..@names/2) { printf "Group $_: %s and %s are partners\n", splice(@names, rand(@na +mes), 1) , splice(@names, rand(@names), 1); }
    Update: using Thospel's idea, one of the splices could be replaced with a simple shift:
    printf "Group $_: %s and %s are partners\n", shift(@names), splice(@ +names, rand(@names), 1);

    Caution: Contents may have been coded under pressure.