Home > Net >  using a for int loop that iterates random numbers until it reaches a certain goal (java)
using a for int loop that iterates random numbers until it reaches a certain goal (java)

Time:11-16

I am trying to find a for int loop that iterates random numbers until it reaches the goal of 10 million.

My assignment states that it needs the total number of contributions needed to meet the goal of 10 million dollars.

I want the for int loop to stop generating random numbers when it reaches the sum of 10 million.

CodePudding user response:

Create an empty list of contributions.

Specify your limit, the ten million.

Start with a sum of zero.

Calculate the delta between the current sum and the limit.

Generate the contribution as a random number between 1 and that delta. ThreadLocalRandom class has handy methods.

Add the contribution to the sum. Record the contribution in the list.

Repeat until the delta is zero. Use a while loop, not for loop.

Those italicized words will be your variables’ names.

CodePudding user response:

This should do the trick
Logic: Generate random number between 1 to range after output reduce the range suppose if sum should be 6
1st iteration range is [1, 6] output is 2
2nd iteration range is [1, 4] output is 3
3rd iteration range is [1, 1] output is 1
exit

  • Related