This is not homework, I do not have money to study, so I teach myself while working, moving around the dining room on the highway (long nights with a small number of customers).
I am trying to implement a simple Hanoi Towers Java solution. I use stacks and a recursive function without consulting external sources to get an opportunity to think.
I started with an array of arrays ( int[][] pegs ), but got stuck in the implementation of the "move" step, in particular, how to find out at what "height" I need to "select" from the array of the original position and at which "height" I would flush the disk to the destination position array. Of course, with Stack<Integer> this is a data structure that does this for me, and I don't need to track anything. I encoded this version, but felt negatively lazy about surrender; I am intrigued by stretching my brain and understanding how all this can be done with arrays.
Is it possible to implement this code with int[][] pegs ? How? (Enough hint, I just get stuck on the approach, I can do my work on my own after determining the right path).
BTW, is this the code I wrote "passable" Java, or am I using things incorrectly? (I'm still not sure whether to focus on Java or C ++. I have e-books for both).
package exercises; import java.util.ArrayList; import java.util.List; import java.util.Stack; public class HanoiTowers { private static final int N_DISCS = 6; private static final int N_PEGS = 3; private static int nMoves = 0; private static final int POSITION_END_PEG = N_PEGS - 1; private static final int POSITION_START_PEG = 0; public static void main(String[] args) { List<Stack<Integer>> pegs = new ArrayList<Stack<Integer>>(N_PEGS); for (int i = 0; i < N_PEGS; i++) { pegs.add(new Stack<Integer>()); } for (int i = 0; i < N_DISCS; i++) { pegs.get(POSITION_START_PEG).push(N_DISCS - i); } printPegs(pegs); moveTowers(pegs, POSITION_START_PEG, POSITION_END_PEG, N_DISCS); System.out.println(String.format("# moves: %d", nMoves)); } private static void moveTowers(List<Stack<Integer>> pegs, int fromPeg, int toPeg, int ofHeight) { if (ofHeight <= 0) { return; } int throughPeg = N_PEGS - fromPeg - toPeg;
source share