While Dr. Noland was exploring a mysterious forest, he stumbled upon an odd sign. The sign had directions to a "Portal of Magic" written poetically. It read:
Follow the path where the count of forward strides divided by the steps to the right dances into a never-ending rhythm, and a Portal shall appear.
After hours of thinking, Dr. Noland finally decoded it into a more logical message:
Any path where the ratio of the number of forward steps to the number of right steps is a repeating decimal will lead to a Portal.
The goal is to create a function isValidPath(path) that can determine whether or not a specified array of moves (path) is a valid path to one of the Portals of Magic.
Rules for the path:
- There must be at least one forward step and one right step.
- The ratio of the number of steps forward to the number of steps to the right must be a repeating decimal (e.g., 3.333...) in order to lead to a Portal.
- Forward steps are labeled as
F, and right steps are labeled asR. There are no backward or left steps.
Return true if the path leads to a Portal, and false if otherwise.
Examples:
-
[ 'F', 'R', 'R', 'F', 'R', 'R', 'R', 'R' ]:true -
[ 'R', 'F', 'F', 'F', 'F', 'F', 'F', 'F' ]:false -
[ 'F', 'F', 'F', 'F', 'F', 'F' ]:false
function isValidPath(path) {
const fCount = path.filter(x => x === 'F').length;
const rCount = path.filter(x => x === 'R').length;
if (fCount === 0 || rCount === 0) return false;
let denom = rCount;
while (denom % 2 === 0) denom /= 2;
while (denom % 5 === 0) denom /= 5;
return denom !== 1;
}const chai = require("chai");
const assert = chai.assert;
describe("Solution", function() {
it("should test if the array is a valid path", function() {
assert.strictEqual(isValidPath([ 'F', 'R', 'R', 'F', 'R', 'R', 'R', 'R' ]), true);
assert.strictEqual(isValidPath([ 'R', 'F', 'F', 'F', 'F', 'F', 'F', 'F' ]), false);
assert.strictEqual(isValidPath([ 'F', 'F', 'F', 'F', 'F', 'F' ]), false);
assert.strictEqual(isValidPath([ 'R', 'R', 'R', 'R', 'R', 'R' ]), false);
assert.strictEqual(isValidPath([ 'R', 'R', 'F', 'F', 'R', 'F', 'R', 'R', 'R', 'R' ]), true);
assert.strictEqual(isValidPath([ 'F', 'F', 'F', 'F', 'F', 'F', 'R', 'R', 'R', 'R', 'R', 'R', 'R', 'R', 'R', 'R', 'R', 'R', 'R', 'R', 'R', 'R', 'R', 'R' ]), true);
});
});