#!/usr/bin/perl -l

sub expected_value {
    my ( $dist, $total ) = (shift, 0);

    while ( ($outcome, $prob) = each %$dist ) {
        $total += $outcome * $prob;
    }

    return $total;
}

sub expected_value_weighted {
    my ( $dist, $total, $total_weight ) = (shift, 0);

    while ( ($outcome, $weight) = each %$dist ) {
        $total += $outcome * $weight;
        $total_weight += $weight;
    }

    return $total/$total_weight;
}

print expected_value( {1=>1/6, 2=>1/6, 3=>1/6, 4=>1/6, 5=>1/6, 6=>1/6} );

print expected_value( {1=>0.1, 2=>0.1, 3=>0.1, 4=>0.1, 5=>0.3, 6=>0.3} );

print expected_value_weighted ( { 1=>1, 4=>2, 6=>3 } );
