cresjoy - 1 year ago 67
Java Question

# Filling an ArrayLists with n elements to a specific sum

Currently I'm working through some exercises in my book where I'm solving a problem on bulgarian solitaire ( The chapter is on arrays and arraylists).

The basic idea is to start with a list of numbers (randomly sized) as long as they sum to 45 say

`20, 5, 1, 9, and 10`
you give one and make another stack like the following

``````20, 5, 1, 9, and 10 -> 19, 4, 8, 10, and 5.
``````

Eventually if you keep doing this you will get a stack like

``````1, 2, 3, 4, 5, 6, 7, 8, and 9
``````

I'm having trouble with the first start of the problem where I fill the arraylist with a specific amount of items, as long as they sum to 45. The following is my code

``````class organizeCards
{
private int sum;
private Random randNum;
private boolean flag;
private ArrayList<Integer> nums;
public organizeCards()
{
sum = 0;
randNum = new Random();
flag = true;
nums = new ArrayList<Integer>();
}

public void fillArrList()
{
int nextNum = 0;
while(flag)
{
int thisRandNum = randNum.nextInt(45 - nextNum) + 1;
System.out.println(thisRandNum);
sum+=thisRandNum;
nextNum = thisRandNum;
if(sum == 45)
{
flag = false;
}
}
}

}
``````

Heres my Issue ( I know my problem, just not really sure how to fix it)

My code is doing the following.

First get a random number from
`1-45`
, say
`30`

Now
`45-30 = 15`
, so the next random number can be from
`1-15`

Now Say
`8`

Now our rand number is from
`1-7`
This process will keep repeating, but won't eventually If I keep adding these my sum reach
`45`
?

What am I missing in my logic?

EDIT(Oops I put sum > 45 in my own code)

Currently, my program sometimes ends and gives me an arraylist that is proper size. But often times never terminates.

``````while(flag)
{
int thisRandNum = randNum.nextInt(45 - nextNum) + 1;
System.out.println(thisRandNum);
sum+=thisRandNum;
nextNum = thisRandNum;
if(sum == 45)
{
flag = false;
}
}
``````

Here, you are subtracting `nextNum` from `45` to get the maximum number achieved. However, what you wish to do is subtract the sum of all the previous numbers generated from the `random()` function.

Changed code:

``````while(flag)
{
int thisRandNum = randNum.nextInt(45 - nextNum) + 1;
System.out.println(thisRandNum);