Created
March 14, 2023 15:08
-
-
Save martian17/3781037b6f87164d38d83e78c20d2f75 to your computer and use it in GitHub Desktop.
Solves tower of hanoi
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const range = function(n){ | |
const arr = []; | |
for(let i = 0; i < n; i++){ | |
arr.push(i); | |
} | |
return arr; | |
}; | |
const peek = function(arr){ | |
return arr[arr.length-1]; | |
}; | |
const vacancyMap = [0,2,1,0]; | |
const move = function(n,from,to){ | |
const vacant = vacancyMap[from+to]; | |
if(n === 1){ | |
return [[from,to]]; | |
}else{ | |
const moves = move(n-1,from,vacant); | |
moves.push([from,to]); | |
const moves2 = move(n-1,vacant,to); | |
for(let move of moves2){ | |
moves.push(move); | |
} | |
return moves; | |
} | |
}; | |
const solveHanoi = function(n){ | |
return move(n,0,2); | |
}; | |
//makes sure the output obeys the rule | |
const verifyHanoi = function(moves,n){ | |
console.log("verifying"); | |
console.log(moves.length); | |
const stack = [range(n).reverse(),[],[]]; | |
for(let i = 0; i < moves.length; i++){ | |
//console.log(stack); | |
const [from,to] = moves[i]; | |
if(from < 0 || to < 0 || from > 2 || to > 2){ | |
console.log(`move ${i} contains illegal values: ${from}:${to}`); | |
} | |
//verify | |
if(stack[from].length === 0){ | |
console.log(`source ${from} is empty at move ${i}`); | |
return false; | |
} | |
const val = stack[from].pop(); | |
if(stack[to].length !== 0 && peek(stack[to]) < val){ | |
console.log(`destination ${to} has larger value than source at move ${i}`); | |
return false; | |
} | |
stack[to].push(val); | |
} | |
//console.log(stack); | |
const s3 = stack[2]; | |
if(s3.length !== n){ | |
console.log(`third stack is not full`); | |
return false; | |
} | |
s3.reverse(); | |
for(let i = 0; i < n; i++){ | |
if(s3[i] !== i){ | |
console.log("third stack not in order"); | |
return false; | |
} | |
} | |
console.log("verification success"); | |
return true; | |
}; | |
verifyHanoi(solveHanoi(20),20); | |
/* | |
verifyHanoi([ | |
[0,1], | |
[0,2], | |
[1,0], | |
[2,1], | |
[0,1], | |
[0,2], | |
[1,0], | |
[1,2], | |
[0,2] | |
],3); | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment