#!/usr/bin/perl

# $selection = rand_dist_perfect( $dist )
#    Select an element from a distribution.
sub rand_dist_perfect {
    my $dist = shift;
    my $key;

    # Get a random floating-point value between 0 and 1.
    my $rand = rand;

    # Use it to determine a key.
    foreach $key ( keys %$dist ) {
        return $key if ($rand -= $dist->{$key}) < 0;
    }
}

%a = (1 => 0.1, 2 => 0.1, 3 => 0.1, 4 => 0.1, 5 => 0.3, 6 => 0.3);

for (1..100) { print rand_dist_perfect(\%a) }
