Skip to content

Instantly share code, notes, and snippets.

@superwills
Last active December 28, 2015 14:59
Show Gist options
  • Save superwills/7518618 to your computer and use it in GitHub Desktop.
Save superwills/7518618 to your computer and use it in GitHub Desktop.
Chancer redistributes the uniform distribution of randFloat(0,1) to any distribution you'd like.
#include <stdio.h>
#include <stdlib.h>
#include <vector>
using namespace std ;
float randFloat()
{
return (float)rand() / RAND_MAX ;
}
float randFloat( float min, float max )
{
return min+(max-min)*rand() / RAND_MAX ;
}
int chance1( vector<float>& chances )
{
float r = randFloat() ;
for( int i = 0 ; i < chances.size() ; i++ )
if( r <= chances[i] )
return i ;
return (int)chances.size()-1; // if the last entry is 1.0, and randFloat() is [0,1]
// then we won't get to this last line, but this is a failsafe
}
int chance2( vector<float>& chances )
{
float r = randFloat() ; // by far the most expensive thing here.
float total=0.f;
for( int i = 0 ; i < chances.size() ; i++ )
{
total += chances[i] ;
if( r <= total )
return i ;
}
// You get OOB the chances array if none of your choices were selected
return (int)chances.size() ;
}
void testChances1()
{
// 20% 0, 20% 1, 50% 2, 10% 3
vector<float> chances = { .2, .4, .9, 1. } ;
vector<int> res = {0,0,0,0};
int runs=10000;
for( int i = 0 ; i < runs ; i++ )
res[ chance1( chances ) ] ++ ;
for( int i = 0 ; i < res.size() ; i++ )
printf( "%d: %.2f%%\n", i, 100.*res[i]/runs ) ;
}
void testChances2()
{
// 20% 0, 20% 1, 50% 2, 10% 3 (classified as "other")
vector<float> chances = { .2, .2, .5 } ;
vector<int> res = {0,0,0,0};
int runs=10000;
for( int i = 0 ; i < runs ; i++ )
res[ chance2( chances ) ] ++ ;
for( int i = 0 ; i < res.size() ; i++ )
printf( "%d: %.2f%%\n", i, 100.*res[i]/runs ) ;
}
int main(int argc, const char * argv[])
{
//testChances1() ;
testChances2() ;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment