d2jsp
Log InRegister
d2jsp Forums > Off-Topic > Computers & IT > Programming & Development > Time Complexity
Add Reply New Topic New Poll
Member
Posts: 6,175
Joined: Sep 4 2009
Gold: Locked
Trader: Scammer
Mar 27 2016 12:20am
Quote
public class TowerOfHanoi {
private static int numOfMoves = 0;

public void move(int numberOfDiscs, char from, char to, char inter) {
if (numberOfDiscs == 1) {
System.out.println("Moving disc 1 from " + from + " to " + to);
numOfMoves++;
} else {
move(numberOfDiscs - 1, from, inter, to);
System.out.println("Moving disc " + numberOfDiscs + " from " + from + " to " + to);
numOfMoves++;
move(numberOfDiscs - 1, inter, to, from);
}
}

public static void main(String[] args) {
TowerOfHanoi toh = new TowerOfHanoi();
toh.move(5, 'A', 'C', 'B');
System.out.println("Number of moves: " + numOfMoves);
}
}


Can anyone explain to me the time complexity of this code? How could I modify it so that it tracks the number of moves
and prints the total number of moves when the program compiles?


Member
Posts: 32,925
Joined: Jul 23 2006
Gold: 3,804.50
Mar 27 2016 12:44am
i saw Tower Of Hanoi and stopped reading. big O of the Tower of Hanoi is 2^n

Quote
How could I modify it so that it tracks the number of moves

you have a move method. increment a counter in it.

Quote
and prints the total number of moves when the program compiles?

i assume you mean when it runs, not when it compiles. just print the incremented counter as you did.
Go Back To Programming & Development Topic List
Add Reply New Topic New Poll