in reply to Re^5: an algorithm to randomly pick items that are present at different frequencies
in thread an algorithm to randomly pick items that are present at different frequencies
Hi BrowserUk,
I'm still running into trouble. Here is my code:
#!/usr/bin/perl -w use strict; use Data::Dump qw[ pp ]; open my $fh, '<', 'numbs.dat' or die $!; my $pick = genPicker( $fh ); ## Reads the file and generates a picker sub genPicker { my $fh = shift; my( @vals, @odds ); ( $vals[ @vals ], $odds[ @odds ] ) = split( ' +' ) for <$fh>; ## Sort if not sorted my @order = sort{ $odds[ $a ] <=> $odds[ $b ] } 0 .. $#odds; @odds = @odds[ @order ]; @vals = @vals[ @order ]; ## Calculate and accumulate break points my $t = 0; $t += $_ for @odds; $_ /= $t for @odds; $odds[ $_ + 1 ] += $odds[ $_ ] for 0 .. $#odds - 1; ## Generate a subroutine to do the picking return sub { my $r = rand(); $r < $odds[ $_ ] and return $vals[ $_ ] for 0 .. $#odds; }; } close $fh;
Here is my numbs.dat file (I changed the numbers to simplify things):
A 0.0001 B 0.0004 C 0.0008
For what it's worth, there is a new line after each row except the last, and each letter is separated from the corresponding number by a single space. I think something is going wrong with my split, because if I pause the script and look into the variables, my @odds array has three slots, each of which is undefined, whereas my @vals array has three slots, each of which contains a letter, a space, a number and then for the first two slots a new line character.
Do you see what's wrong?
Best wishes,
Eric
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^7: an algorithm to randomly pick items that are present at different frequencies
by BrowserUk (Patriarch) on May 27, 2015 at 22:33 UTC | |
by efoss (Acolyte) on May 28, 2015 at 04:54 UTC | |
by efoss (Acolyte) on Jun 04, 2015 at 20:30 UTC | |
by BrowserUk (Patriarch) on Jun 04, 2015 at 20:41 UTC | |
by efoss (Acolyte) on Jun 04, 2015 at 21:34 UTC | |
by BrowserUk (Patriarch) on Jun 04, 2015 at 22:35 UTC | |
|