Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generating random numbers, each of a minimum size

Not sure if this exact question's been asked before, though a similar question has been asked here. Essentially, what I'm trying to is generate random integers of a minimum size that still sum up to a certain value (an invariant is that the sum / (number of randoms you want) is greater than the minimum value. Here's a sad attempt I coded up:

import java.util.Arrays;
import java.util.Random;

public class ScratchWork {

    private static Random rand = new Random();


    public static void main(String[] args) {
            int[] randoms = genRandoms(1000, 10, 30);
            for (int i = 0; i<randoms.length; i++) sop("Random Number "+ (i+1) + ": " + randoms[i]);
            sop("Sum: " + sum(randoms));
    }

    public static int sum(int[] array) { int sum = 0; for (int i : array) sum+=i; return sum; }

    public static int[] genRandoms(int n, int numberOfRandoms, int min) {
        if (min > n/numberOfRandoms) throw new UnsupportedOperationException();
        int[] intRandArray = {0};
        while (sum(intRandArray) != n) {
            ////////////////////////
            // See https://stackoverflow.com/questions/2640053/getting-n-random-numbers-that-the-sum-is-m
            Double[] randArray = new Double[numberOfRandoms];
            double workerSum = 0;
            for (int i = 0; i<numberOfRandoms; i++) {
                randArray[i] = ((double)rand.nextInt(n-1)+1);
                workerSum += randArray[i];
            }

            for (int i = 0; i<randArray.length; i++) {
                randArray[i] = n*(randArray[i]/(workerSum));
            }
            /////////////////////////

            while (existsSmallerNumThanMin(randArray, min)) 
                randArray = continueToFix(randArray, min);

            //Convert doubles to ints
            intRandArray = new int [randArray.length];
            for (int i = 0; i < intRandArray.length; i++) 
                intRandArray[i] = (int)Math.round(randArray[i]);
        }
        return intRandArray;
    }

    public static boolean existsSmallerNumThanMin(Double[] randArray, int min) {
        for (double i : randArray) if (i < (double)min) return true;
        return false;
    }

    public static Double[] continueToFix(Double[]randArray, int min) {
        Double[] tempArray = Arrays.copyOf(randArray, randArray.length);
        Arrays.sort(tempArray);
        int smallest = Arrays.asList(randArray).indexOf(tempArray[0]);
        int largest = Arrays.asList(randArray).indexOf(tempArray[tempArray.length-1]);

        double randomDelta = rand.nextInt(min);

        randArray[smallest]+=randomDelta;
        randArray[largest]-=randomDelta;
        return randArray;
    }

    public static void sop(Object s) { System.out.println(s); }

}

This is neither an elegant nor high-performing way to do this... It also doesn't seem to work well (if at all) when passed in, say, (100,10,10), which only allows for the number 10 in the array. The distribution of the random numbers is also pretty bad.

Is there an elegant approach to this??

Also, my end goal is to implement this in Objective-C, though I'm still just learning the ropes of that language, so any tips for doing this in that language would be greatly appreciated.

like image 947
benjammin Avatar asked Jan 13 '12 07:01

benjammin


1 Answers

I did some more testing, and my Java implementation is broken. I think my algorithm is bad.

How about something like getting N random numbers in [0,1] and normalize the results based on their sums (different than the desired sum). Then multiply these values against the desired number sum.

This assumes the minimum size is 0. Generalizing this to maintain a minimum for each result is simple. Just feed in sum - min * n for sum. Add min to all the results.

To avoid potential floating point issues, you can do something similar with using a range of integer values that are logically on the scale [0,M] (M arbitarily large) instead of [0,1]. The idea is the same in that you "normalize" your random results. So lets say you get a random sum of N (want N to have to be a multiple of sum+1... see REMARK). Divy N up by sum+1 parts. The first part is 0, second is 1, ..., last is sum. Each random value looks up its value by seeing what part of N it belongs to.

REMARK: If you are okay with an arbitrarily small amount of bias, make each die roll a magnitude larger than sum (might want BigInteger for this). Let N be the sum. Then N = k*sum + rem where rem < sum. If N is large, then rem / k -> 0, which is good. N is probabilistically large if M is large.

Algorithm psuedo code:

F(S, N):
    let R[] = list of 0's of size N
    if S = 0: return R[]
    for 0 <= i < N
        R[i] = random integer in [0, M] -- inclusive and (M >= S). M should be an order larger than S. A good pick might be M = 1000*S*N. Not sure though. M should probably be based on both S and N though or simply an outragously large number.
    let Z = sum R[]
    for 0 <= i < N
        R[i] = (Z mod R[i]) mod (S+1)
    return R[]

Java implementation:

import java.math.BigInteger;
import java.util.Arrays;
import java.util.Map;
import java.util.Random;
import java.util.TreeMap;


public class Rand {
    private final Random rand;
    
    public Rand () {
        this(new Random());
    }
    
    public Rand (Random rand) {
        this.rand = rand;
    }
    
    public int[] randNums (int total, int minVal, int numRands) {
        if (minVal * numRands > total) {
            throw new IllegalArgumentException();
        }
        int[] results = randNums(total - minVal * numRands, numRands);
        for (int i = 0; i < numRands; ++i) {
            results[i] += minVal;
        }
        return results;
    }

    private int[] randNums (int total, int n) {
        final int[] results = new int[n];
        if (total == 0) {
            Arrays.fill(results, 0);
            return results;
        }
        final BigInteger[] rs = new BigInteger[n];
        final BigInteger totalPlus1 = BigInteger.valueOf(total + 1L);
        while (true) {
            for (int i = 0; i < n; ++i) {
                rs[i] = new BigInteger(256, rand);
            }
            BigInteger sum = BigInteger.ZERO;
            for (BigInteger r : rs) {
                sum = sum.add(r);
            }
            if (sum.compareTo(BigInteger.ZERO) == 0) {
                continue;
            }
            for (int i = 0; i < n; ++i) {
                results[i] = sum.mod(rs[i]).mod(totalPlus1).intValue();
            }
            return results;
        }
    }
    
    public static void main (String[] args) {
        Rand rand = new Rand();
        Map<Integer, Integer> distribution = new TreeMap<Integer, Integer>();
        final int total = 107;
        final int minVal = 3;
        final int n = 23;
        for (int i = total - (n-1) * minVal; i >= minVal; --i) {
            distribution.put(i, 0);
        }
        for (int i = 0; i < 100000; ++i) {
            int[] rs = rand.randNums(total, minVal, n);
            for (int r : rs) {
                int count = distribution.get(r);
                distribution.put(r, count + 1);
            }
        }
        System.out.print(distribution);
    }
    
}
like image 178
15 revs Avatar answered Oct 05 '22 13:10

15 revs