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

后端 未结 4 1650
没有蜡笔的小新
没有蜡笔的小新 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 20:55

    Adding on to what @Kon said, you could use two random numbers rather than one for more randomness. That is:

    Fill every element in the array with the value 1
    valuesToDistribute = a - array.length-1
    randomIndex = Roll a number between 0 and array.length-1
    randomValue = Roll a number between 1 and valuesToDistribute
    Add to randomIndex the value randomValue
    Subtract randomValue from valuesToDistribute
    Repeat until valuesToDistribute = 0
    

提交回复
热议问题