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

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

    My java is horrible, so I'm not providing the actual code here, as it would probably be wrong. I've done this exact thing in SQL before though, so I know it works...

    1. Let Y be the Total value you want the elements to add up to
    2. Begin a loop with variable Z going from 1 to X where X is the number elements in your array (here called AR)
    3. In the loop, set AR(Z) to a random number between 1 and Y-X+Z
    4. Subtract the new value from Y, so Y = Y - AR(Z)
    5. End loop : back to step 2, advancing Z by 1

提交回复
热议问题