How do I generate random numbers in an array that add up to a defined total?

后端 未结 4 1642
没有蜡笔的小新
没有蜡笔的小新 2020-12-05 20:16

I need to randomly generate an array with 7 slots in Java. All these slots must have a value of at LEAST 1, but combined, have a total value of another defined number. They

4条回答
  •  一生所求
    2020-12-05 21:06

    The standard way to generate N random numbers that add to a given sum is to think of your sum as a number line, generate N-1 random points on the line, sort them, then use the differences between the points as your final values. To get the minimum 1, start by subtracting N from your sum, run the algorithm given, then add 1 back to 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;
    
            for (int i = 0; i < count-1; ++i) {
                vals[i] = g.nextInt(sum);
            }
            vals[count-1] = sum;
    
            java.util.Arrays.sort(vals);
            for (int i = count-1; i > 0; --i) {
                vals[i] -= vals[i-1];
            }
            for (int i = 0; i < count; ++i) { ++vals[i]; }
    
            for (int i = 0; i < count; ++i) {
                System.out.printf("%4d", vals[i]);
            }
            System.out.printf("\n");
        }
    }
    

提交回复
热议问题