Skip to content

Instantly share code, notes, and snippets.

@tatsuyax25
Created May 2, 2025 19:56
Show Gist options
  • Save tatsuyax25/9d4a130535ce48649d62f36d2bafa450 to your computer and use it in GitHub Desktop.
Save tatsuyax25/9d4a130535ce48649d62f36d2bafa450 to your computer and use it in GitHub Desktop.
There are n dominoes in a line, and we place each domino vertically upright. In the beginning, we simultaneously push some of the dominoes either to the left or to the right. After each second, each domino that is falling to the left pushes the adja
/**
* Simulates the domino effect by computing the final state of a row of dominoes.
*
* @param {string} dominoes - A string representing dominoes. 'L' falls left, 'R' falls right, '.' stays upright.
* @return {string} - The final state of the dominoes after all forces are resolved.
*/
var pushDominoes = function(dominoes) {
const n = dominoes.length;
const forces = new Array(n).fill(0);
// Calculate rightward forces (R).
let force = 0;
for (let i = 0; i < n; i++) {
if (dominoes[i] === 'R') {
force = n; // Strong force pushing right.
} else if (dominoes[i] === 'L') {
force = 0; // Leftward force cancels rightward force.
} else {
force = Math.max(force - 1, 0); // Gradual force reduction.
}
forces[i] += force;
}
// Calculate leftward forces (L).
force = 0;
for (let i = n - 1; i >= 0; i--) {
if (dominoes[i] === 'L') {
force = n; // Strong force pushing left.
} else if (dominoes[i] === 'R') {
force = 0; // Rightward force cancels leftward force.
} else {
force = Math.max(force - 1, 0); // Gradual force reduction.
}
forces[i] -= force; // Subtracting leftward forces from rightward forces.
}
// Construct the final state of the dominoes.
return forces.map(f => (f > 0 ? 'R' : f < 0 ? 'L' : '.')).join('');
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment