Skip to content

Instantly share code, notes, and snippets.

@zianwar
Created June 25, 2023 00:04
Show Gist options
  • Save zianwar/2b7d6a832e3e64727b2f1eda22b3d8af to your computer and use it in GitHub Desktop.
Save zianwar/2b7d6a832e3e64727b2f1eda22b3d8af to your computer and use it in GitHub Desktop.
Backtracking - diceRoll, diceSum - https://www.youtube.com/watch?v=tC1rgphJtO4
/**
* Prints all possible combinations of values that could appear after rolling the dice.
*/
function diceRoll(dice: number, chosen: number[]) {
if (dice == 0) {
// Base case, print.
console.log(chosen);
} else {
for (let i = 1; i <= 6; i++) {
// Chose
chosen.push(i);
// Explore
diceRoll(dice - 1, chosen);
// Un-choose
chosen.pop();
}
}
}
/**
* Prints all possible combinations of dice values that sum up to targetSum.
*/
function diceSum(dice: number, targetSum: number, sum: number, chosen: number[]) {
if (dice == 0) {
// Base case: if we eliminated unnecessary calls,
// we should end up with chosen values that give us the desired sum by default.
console.log(chosen);
} else {
for (let i = 1; i <= 6; i++) {
// Explore only solution that might give us a sum <= targetSum:
// Given i, what's smallest and biggest possible values we can get
// by rolling the current die + all remaining dice?
const smallestSum = sum + i + 1 * (dice - 1); // Get a 1 on all remaining dice.
const biggestSum = sum + i + 6 * (dice - 1); // Get a 6 on all remaining dice.
if (smallestSum <= targetSum && biggestSum >= targetSum) {
chosen.push(i);
diceSum(dice - 1, targetSum, sum + i, chosen);
chosen.pop();
}
}
}
}
diceRoll(2, [])
// [ 1, 1 ]
// [ 1, 2 ]
// [ 1, 3 ]
// [ 1, 4 ]
// [ 1, 5 ]
// [ 1, 6 ]
// [ 2, 1 ]
// [ 2, 2 ]
// [ 2, 3 ]
// [ 2, 4 ]
// [ 2, 5 ]
// [ 2, 6 ]
// [ 3, 1 ]
// [ 3, 2 ]
// [ 3, 3 ]
// [ 3, 4 ]
// [ 3, 5 ]
// [ 3, 6 ]
// [ 4, 1 ]
// [ 4, 2 ]
// [ 4, 3 ]
// [ 4, 4 ]
// [ 4, 5 ]
// [ 4, 6 ]
// [ 5, 1 ]
// [ 5, 2 ]
// [ 5, 3 ]
// [ 5, 4 ]
// [ 5, 5 ]
// [ 5, 6 ]
// [ 6, 1 ]
// [ 6, 2 ]
// [ 6, 3 ]
// [ 6, 4 ]
// [ 6, 5 ]
// [ 6, 6 ]
diceSum(2, 7, 0, []);
// [ 1, 6 ]
// [ 2, 5 ]
// [ 3, 4 ]
// [ 4, 3 ]
// [ 5, 2 ]
// [ 6, 1 ]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment