javascriptalgorithmtestingtowers-of-hanoi

I'm having a problem with the Tower of Hanoi using JavaScript


I'm trying to write a piece of code to create a method that prints a string with the correct steps to solve the puzzle of the Towers of Hanoi but I'm having a small problem. The output is correct but at the end, it displays an additional value of "undefined".I tried that same code with ruby and it works perfectly.

 hanoi_steps = (numberOfDiscs) => {
    move(numberOfDiscs, 1, 2 , 3);
}

move =  ( numberOfDiscs,start, intermediate, goal) => {
  if (numberOfDiscs <= 0) {
      return;
  }

  move(numberOfDiscs - 1, start, goal, intermediate)
  console.log(`${start}->${goal}`)
  move(numberOfDiscs - 1, intermediate, start, goal)
}



console.log(hanoi_steps(2));

Output:

1->2
1->3
2->3
undefined

Solution

  • Actually The problem has been resolved just by removing the console.log call at the last line (Thanks to the comments)

     hanoi_steps = (numberOfDiscs) => {
        move(numberOfDiscs, 1, 2 , 3);
    }
    
    move =  ( numberOfDiscs,start, intermediate, goal) => {
      if (numberOfDiscs <= 0) {
          return;
      }
    
      move(numberOfDiscs - 1, start, goal, intermediate)
      console.log(`${start}->${goal}`)
      move(numberOfDiscs - 1, intermediate, start, goal)
    }
    
    
    hanoi_steps(2);
    

    Output

    1->2
    1->3
    2->3