# Arraylist of stacks

• 10-07-2013, 07:39 PM
boss
Arraylist of stacks
I'm trying to solve the "Hanoi Moves" challenge.
I'm using an Arraylist of stacks to implement it, but for some reason it's not building the stacks as it should. Instead, it's placing all the discs in all the stacks, so they all end up [6,5,4,3,2,1].
Here's the portion of the code that builds the stacks (or should):

for (int i=inicio.size()-1;i>=0;i--) { // i = disc radius, <inicio> contains the initial pegs to which discs belong.
peg = (Integer)inicio.get(i); // peg = stack to which the disc belongs
(stacks.get(peg)).push(i+1); // it pushes all the disks onto all the stacks, instead of only <peg>
System.out.println(peg);
System.out.println(stacks.get(peg));

What's wrong?
• 10-07-2013, 07:58 PM
JosAH
Re: Arraylist of stacks
I don't understand your code: according to that code snippet 'peg' is an Integer or an int but in your comment you say 'peg' is supposed to be a stack ... show us a bit more code please.
(b.t.w. I think that you only have one stack stored multiple times in your ArrayList).

kind regards,

Jos
• 10-07-2013, 08:24 PM
boss
Re: Arraylist of stacks
No, peg represents the stack to be pushed with the disc i. The stacks are stored in<stacks>.
Here goes the code...

ArrayList<Stack> stacks = new ArrayList<Stack>();
ArrayList inicio = new ArrayList(8);

int peg;
Stack s0 = new Stack();
for (int i=0;i<=K;i++) stacks.add(s0); // creates K empty stacks
System.out.println(stacks); // OK

for (int i=inicio.size()-1;i>=0;i--) { // i = disc radius, <inicio> contains the initial pegs to which discs belong
peg = (Integer)inicio.get(i); // peg ids stack to push with disc i
(stacks.get(peg)).push(i+1);
System.out.println(peg); // OK

System.out.println(stacks.get(peg));
}

// K and <inicio> are inputs.
• 10-07-2013, 08:41 PM
JosAH
Re: Arraylist of stacks
As I wrote: you're adding the single stack s0 to the ArrayList multiple times. Change that line to:

Code:

`for (int i=0;i<=K;i++) stacks.add(new Stack());`
kind regards,

Jos
• 10-07-2013, 08:45 PM
boss
Re: Arraylist of stacks
Input for 6 discs and 4 pegs:
6 4
2 3 1 4 2 3 // stored in <inicio>

Here's the output I get...

[[], [], [], [], []] // empty stacks
3 // last peg in <inicio>
[6]
2 // peg
[6, 5]
4 // peg
[6, 5, 4]
1 // peg
[6, 5, 4, 3]
3 // peg
[6, 5, 4, 3, 2]
2 // 1st peg in <inicio>
[6, 5, 4, 3, 2, 1]
[[6, 5, 4, 3, 2, 1], [6, 5, 4, 3, 2, 1], [6, 5, 4, 3, 2, 1], [6, 5, 4, 3, 2, 1], [6, 5, 4, 3, 2, 1]] // all the discs go in all the stacks

it should end like this:
stack 1: disc [3]
stack 2: discs [5 1]
stack 3: discs [6 2]
stack 4: disc [4]
• 10-07-2013, 08:51 PM
boss
Re: Arraylist of stacks
And that affects the push's lateron?
• 10-07-2013, 08:55 PM
boss
Re: Arraylist of stacks
It worked. Thanx...