public class TowerOfHanoi { public static int Tower(int numOfDisks) { return numOfDisks < 1 ? 0 : tailRecursiveHanoi(numOfDisks); static int tailRecursiveHanoi( in int target, in int iteration = 1, in int lastRoundValue = 0 ) => iteration > target ? lastRoundValue : tailRecursiveHanoi( target, iteration + 1, lastRoundValue: lastRoundValue * 2 + 1); } }
using System.Collections.Generic;using System.Diagnostics;- public class TowerOfHanoi
- {
- public static int Tower(int numOfDisks)
- {
//only numOfDisks is given, fill in the other gaps, call the other method that moves disks, and return the return statement from the other methodreturn Tower(numOfDisks, new Dictionary<int, int>());}- return
- numOfDisks < 1 ? 0
- : tailRecursiveHanoi(numOfDisks);
private static int Tower(int n, Dictionary<int, int> cache){//dictionary has keys and values.if (n > 0) // if one or more disks{if (cache.ContainsKey(n)) //check if dictionary contains an element with the specified key{return cache[n];}//variable declared at method scope//outcome will be the number of moves in testvar outcome = Tower(n - 1, cache); //move disk from rod to rod using recursionoutcome += Tower(n - 1, cache);outcome += 1;cache.Add(n, outcome);return outcome;}else { //if no disks given, no moves possiblereturn 0;}- static int tailRecursiveHanoi(
- in int target,
- in int iteration = 1,
- in int lastRoundValue = 0
- ) =>
- iteration > target ?
- lastRoundValue
- : tailRecursiveHanoi(
- target,
- iteration + 1,
- lastRoundValue: lastRoundValue * 2 + 1);
- }
}//mathematical way to calculate moves//using System;//static int moves = 0;//method body// return moves = (int) Math.Pow(2,numOfDisks)-1;- }