JSFiddle - React, Tailwind, and code Playground
towers of hanoi
by kkdaily
JavaScript
/*
You are given three towers (stacks) and N disks, each of different size. You can move the disks according to three constraints:
1. only one disk can be moved at a time
2. when moving a disk, you can only use pop (remove the top element) and push (add to the top of a stack)
3. no disk can be placed on top of a disk that is smaller than it
The disks begin on tower#1. Write a function that will move the disks from tower#1 to tower#3 in such a way that none of the constraints are violated
*/
// ex: tower 1 contains [2, 1], [1, 2], [1, 3, 2]
// create Stack data structure and initialize 3 stacks for towers 1, 2, and 3
// tower1 stack should contain initial values for disks
// if there are no disks on tower 2
// check for position of largest value in tower1 stack
// if the largest value is at the top of the stack
// pop tower1 and push that disk into tower3
// else
// pop tower1 and push that disk into tower2
// while there are disks on tower 2 and disks on tower 1 then
// find the largest value between tower 1 and tower 2
// if the largest value is in tower 1
// if it is at the top of the stack
// pop and push this value to tower 3
// else
// pop and push this value to tower 2
// else if the largest value is in tower 2
// if it is at the top of the stack
// pop and push this value to tower 3
// else
// pop andn push this value to tower 1
function Stack(values) {
if (!Array.isArray(values)) {
return console.log('values must be an array');
}
this._storage = values;
};
Stack.prototype.push = function(val) {
this._storage.push(val);
};
Stack.prototype.pop = function() {
return this._storage.pop();
};
Stack.prototype.max = function() {
var max = this._storage[0];
for (var i = 0; i < this._storage.length; i++) {
if (this._storage[i] > max) {
max = this._storage[i];
}
}
return...