Skip to content

Instantly share code, notes, and snippets.

@only-cliches
Last active December 3, 2019 23:44
Show Gist options
  • Save only-cliches/cd51ce5a1f7aca3e2e75682f11c517d7 to your computer and use it in GitHub Desktop.
Save only-cliches/cd51ce5a1f7aca3e2e75682f11c517d7 to your computer and use it in GitHub Desktop.
Tower of Hanoi Backup
// given a number of intervals and number of backup slots, console log out each backup slots age for every interval
const printBackupIntervals = (intervals, backupSlots) => {
let points = {};
const pad = String(Math.pow(2, backupSlots - 1)).split("").map(c => "0").join("");
for (let i = 1; i < intervals; i++) {
Object.keys(points).forEach(k => points[k]++);
const k = tower(i, backupSlots).charCodeAt(0);
points[k] = 1;
console.log("Day " + i + ": " + Object.keys(points).map(p => {
const str = String(points[p]);
return String.fromCharCode(p) + ": " + pad.substring(0, pad.length - str.length) + str;
}).join(", "));
}
}
// how many days range do we get from each slot?
const backupRange = (slot) => {
if (slot === 1) return [0, 1];
if (slot === 2) return [1, 2];
if (slot === 3) return [2, 3];
const base = Math.pow(2, slot - 2) - 1;
const base2 = Math.pow(2, slot - 1) - 1;
return [base, base2];
}
/*
1: 0 - 1 days
2: 1 - 2 days
3: 2 - 3 days
4: 3 - 7 days
5: 7 - 15 days
6: 15 - 31 days
7: 31 - 63 days
8: 63 - 127 days
9: 127 - 255 days
10: 255 - 511 days
11: 511 - 1,023 days
12: 1,023 - 2,047 days
13: 2,047 - 4,095 days
14: 4,095 - 8,191 days
15: 8,191 - 16,383 days
16: 16,383 - 32,767 days
17: 32,767 - 65,535 days
18: 65,535 - 131,071 days
19: 131,071 - 262,143 days
*/
// given an increment from the first backup and the number of backup slots available,
// provide which backup slot this backup belongs in.
// returns a letter fom "A" on up to denote which backup slot to use.
const tower = (backupNum, backupCount) => {
const max = Math.pow(2, backupCount - 1);
const backupDay = backupNum % max;
if (backupDay === 1) { // begining of cycle
return "A";
} else if (backupDay === 0) { // end of cycle
return String.fromCharCode(64 + backupCount);
}
return tower(backupDay, backupCount - 1);
};
/*
// first backup with 5 slots:
tower(1, 5) => "A"
// 8th backup done with 5 slots:
tower(8, 5) => "D"
// 2,398th backup with 5 slots
tower(2938, 5) => "B"
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment