in reply to Randomly generating histograms

narse,

Well, there may be other things that bound you (this example just uses integers and can have dupes) but a simplistic brute force approach would be:

#!/usr/bin/perl -wd use strict; my $tot = 0; my $i = 0; my $x = 0; my @array; while( $tot < 100 ) { my $x = int rand( 100 ); $x = ( $tot + $x > 100 ) ? 100 - $tot : $x; $array[$i] = $x; $i++; $tot += $x; } $tot = 0; foreach( @array ) { print $_, "\n"; $tot += $_; } print "Total is ", $tot, "\n";

But I'm sure there are prettier approaches. But start with rand and perlfaq4 for ideas.

<code> -derby

Replies are listed 'Best First'.
Re: Re: Randomly generating histograms
by narse (Pilgrim) on Mar 25, 2002 at 16:13 UTC
    This is similar to the method I am using at the moment for testing. The problem I have is the first entries in the array always have the largest numbers, while the last ones are nearly always 0. I mixed this up some by randomizing which array index each value goes into but I'm hoping to find something thats a little more random. Thanks tho.
      This is completely hackish but loop for x number of times (12, 100?) before using the values of rand:

      $x = int rand( 100 ) for ( 1 .. 12 ); $x = 0;

      update: Or better yet. After you have the array filled, shuffle it as described in perlfaq4. -derby

Re: Re: Randomly generating histograms
by narse (Pilgrim) on Mar 26, 2002 at 22:12 UTC
    I probably didn't express what I was hoping to do well enough so not many people hit on what I was asking. Thanks for the responses none the less. I found a method elsewhere that does what I want very well and is easier to impliment than the others that I saw. Here it is:
    #!/usr/bin/perl -w use strict; my @arr; map { $arr[rand 10]++ } 0..99; print join(' ', @arr), "\n";