package com.mindprod.example;
import org.jetbrains.annotations.NotNull;
import java.util.Random;
import static java.lang.System.*;
/**
* random choices with int weights.
*
* @author Roedy Green, Canadian Mind Products
* @version 1.0 2014-07-28 initial version
* @see com.mindprod.example.RandomWithFloatWeights
* @since 2014-07-28
*/
public final class RandomWithIntWeights
{
/**
* build the translator table for generated weighted random numbers
*
* @param weights array of weights
*
* @return translator table
*/
@NotNull
private static int[] buildTranslator( @NotNull final int[] weights )
{
int totalWeights = 0;
for ( int weight : weights )
{
totalWeights += weight;
}
final int[] translator = new int[ totalWeights ];
int k = 0;
for ( int i = 0; i < weights.length; i++ )
{
final int weight = weights[ i ];
for ( int j = 0; j < weight; j++ )
{
translator[ k++ ] = i;
}
}
return translator;
}
/**
* Print out 30 ice cream flavours, but weighting toward choclate strawberry and orange.
*
* @param args not used
*/
public static void main( String[] args )
{
final String[] flavours = { "chocolate", "strawberry", "vanilla", "orange", "lime", "Cherry Garcia", "bubble gum" };
final int[] weights = { 15, 20, 1, 18, 10, 2, 1 };
final int[] translator = buildTranslator( weights );
final Random wheel = new Random();
for ( int i = 0; i < 30; i++ )
{
final int rawChoice = wheel.nextInt( translator.length );
final int weightedChoice = translator[ rawChoice ];
out.println( flavours[ weightedChoice ] );
}
}
}