java - How do I generate random numbers in an array that add up to a defined total? -
i need randomly generate array 7 slots in java. these slots must have value of @ least 1, combined, have total value of defined number. need int value, no 1.5 or 0.9816465684646 numbers. example:
int a=10; int[] ar = new int[7] ar[0] = 1 ar[1] = 1 ar[2] = 2 ar[3] = 2 ar[4] = 1 ar[5] = 2 ar[6] = 1
i want generate that, if int a=15, numbers total 15 in order
the standard way generate n random numbers add given sum think of sum number line, generate n-1 random points on line, sort them, use differences between points final values. minimum 1, start subtracting n sum, run algorithm given, add 1 each segment.
public class rand { public static void main(string[] args) { int count = 8; int sum = 100; java.util.random g = new java.util.random(); int vals[] = new int[count]; sum -= count; (int = 0; < count-1; ++i) { vals[i] = g.nextint(sum); } vals[count-1] = sum; java.util.arrays.sort(vals); (int = count-1; > 0; --i) { vals[i] -= vals[i-1]; } (int = 0; < count; ++i) { ++vals[i]; } (int = 0; < count; ++i) { system.out.printf("%4d", vals[i]); } system.out.printf("\n"); } }
Comments
Post a Comment