Last active
March 31, 2022 14:14
-
-
Save anthonyhastings/945dbb8b2ab6966d6901ca040f7874c5 to your computer and use it in GitHub Desktop.
Slide Code Challenge
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // Write a function, that checks whether the bomb explodes if the wires are cut in a given order. | |
| // | |
| // It should take an array of strings (colors of wires) as input and return a single boolean value | |
| // as output (true if bomb explodes, false otherwise). | |
| // | |
| // Example of an input: | |
| // ['red', 'green', 'blue', 'yellow', 'white', 'black'] | |
| // | |
| // Rules | |
| // - After cutting the red wire, you can't cut the yellow one next. | |
| // - After cutting the black wire, you can only cut the blue or green one. | |
| // - When cutting the white wire, you have to cut yellow, blue, black or red wire next. | |
| // - If you cut the blue wire, you have to cut the red one next. | |
| // - After cutting the yellow wire, you can't cut the black or white one. | |
| const wireCombinations = { | |
| red: { | |
| nextMustBe: [], | |
| nextCannotBe: ['yellow'] | |
| }, | |
| black: { | |
| nextMustBe: ['blue', 'green'], | |
| nextCannotBe: [] | |
| }, | |
| white: { | |
| nextMustBe: ['yellow', 'blue', 'black', 'red'], | |
| nextCannotBe: [] | |
| }, | |
| blue: { | |
| nextMustBe: ['red'], | |
| nextCannotBe: [] | |
| }, | |
| yellow: { | |
| nextMustBe: [], | |
| nextCannotBe: ['black', 'white'], | |
| } | |
| }; | |
| (wires) => { | |
| let hasExploded = false; | |
| for (var i = 0; i < wires.length; i++) { | |
| const wireColor = wires[i]; | |
| const wireColorData = wireCombinations[wireColor]; | |
| // If color has no dedicated rules then skip. | |
| if (wireColorData === undefined) continue; | |
| // If there is no further wire then skip. | |
| const nextWireColor = wires[i + 1]; | |
| if (nextWireColor === undefined) continue; | |
| // If next wire is in the deny list, break early. | |
| if (wireColorData.nextCannotBe.includes(nextWireColor)) { | |
| hasExploded = true; | |
| break; | |
| } | |
| // If there is a required color to be next, and the next wire isn't there, break early. | |
| if (wireColorData.nextMustBe.length > 0 && wireColorData.nextMustBe.includes(nextWireColor) === false) { | |
| hasExploded = true; | |
| break; | |
| } | |
| } | |
| return hasExploded; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment