Search
 
SCRIPT & CODE EXAMPLE
 

JAVASCRIPT

Towers of Hanoi, Iterative and Recursive

//////// Towers of Hanoi Iterative
function HanoiIterative(n) {
    const trackDiskPosition = Array(n).fill(0);
    for (let stepCount = 0; stepCount < 2 ** n; ++ stepCount) {
        for (let currentDisk = 0; currentDisk < n; ++ currentDisk) {
            const expectedPosition = count(currentDisk, stepCount);
            if (trackDiskPosition[currentDisk] !== expectedPosition) {
                console.log(`Move disk ${currentDisk + 1} from ${trackDiskPosition[currentDisk] + 1} to ${expectedPosition + 1}`);
                trackDiskPosition[currentDisk] = expectedPosition;
                break;
            }
        }
    }
}

function count(disk, step) {
    let temp = Math.ceil(
        (step + (disk % 2 === 1 ? 2 ** (disk + 2) : 0) - 2 ** disk + 1)
        / (2 ** (disk + 1))
    ) % 3;
    return disk % 2 === 1 ? 2 - temp : temp;
}

///////// Towers of Hanoi Recursive
function HanoiRecursive(n, a, b, c) {
  if (n > 0) {
    HanoiRecursive(n-1, a, c, b);
    console.log("Move disk from " + a + " to " + c);
    HanoiRecursive(n-1, b, a, c);
  }
}

console.log("
Iterative = ");
HanoiIterative(3)

console.log("Recursive = ");
HanoiRecursive(3, "1", "2", "3");
Comment

PREVIOUS NEXT
Code Example
Javascript :: chunking array javascript 
Javascript :: how to combine two regular expressions in javascript 
Javascript :: //Splice remove and add new elements in an array in javascript 
Javascript :: faker js uuid example 
Javascript :: how to get keys in an object javascript 
Javascript :: implement queue using stack javascript 
Javascript :: return new Promise(res = { 
Javascript :: array.fill() in javascript 
Javascript :: impress.js cdn 
Javascript :: JSE Data 
Javascript :: react native layout animation android 
Javascript :: Array iteration in ES6 
Javascript :: how to know how many pixels of page be scrolled javascript 
Javascript :: remove element array javascript 
Javascript :: tagged templates 
Javascript :: email valid javascript 
Javascript :: variables in js class 
Javascript :: how to change object property value in javascript 
Javascript :: delay external javascript file load 
Javascript :: default in javascript 
Javascript :: how to upload picture on canvas in react 
Javascript :: chrome.browseraction.getbadgetext 
Javascript :: math.round 
Javascript :: angular indexeddb 
Javascript :: Iterating set object javascript 
Javascript :: how to change string to array in javascript 
Javascript :: how to update mongodb collection with a new field 
Javascript :: react usereducer hook 
Javascript :: add property to object javascript 
Javascript :: mapbox add a leaflet marker with popup 
ADD CONTENT
Topic
Content
Source link
Name
2+6 =