Created
November 13, 2018 17:04
-
-
Save runandrerun/c3d6e3a1ff568b8e7769c277314e7215 to your computer and use it in GitHub Desktop.
This file contains 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
combinationLock = (initialState, code) => { | |
// declare a variable to account for total turns | |
let totalTurns = 0; | |
// iterate over the initialState array | |
// this what the lock looks like when it's first handed to you | |
initialState.forEach((i, index) => { | |
// i is the value | |
// index is the current index of that value | |
// we need to calculate the difference between the initial state | |
// and the final position (code) in relation to the same index | |
let turns = Math.abs(i - code[index]); | |
// without Math.abs() | |
// 0 - 3 = -3 | |
// 0 - 1 = -1 | |
// 0 - 8 = -8 | |
// with Math.abs() | |
// Math.abs(0 - 3) = 3 | |
// Math.abs(0 - 1) = 1 | |
// Math.abs(0 - 8) = 8 | |
// if the return value of Math.abs(i - code[index]) is <= 5 | |
// this signifies a forward rotation | |
// increment totalTurns with the value of turns | |
// Math.abs(0 - 3) = 3 | |
// is 3 <= 5 ? | |
// yes! | |
// return (totalTurns += 3) | |
// totalTurns = 3 | |
// Math.abs(0 - 1) = 1 | |
// is 1 <= 5 ? | |
// yes! | |
// return (totalTurns += 1) | |
// totalTurns = 4 | |
// Math.abs(0 - 8) = 8 | |
// is 8 <= 5 ? | |
// no! | |
// 10 - 8 = 2 | |
// return (totalTurns += 2) | |
// totalTurns = 6 | |
if (turns <= 5) { | |
return (totalTurns += turns); | |
} else { | |
// else if it's larger than 5 then that makes it a backward rotation | |
// subtract the value of turns from 10 | |
// the reason we choose 10 is because the combination lock is only 0-9 | |
// in regards to indices 0-9 is 10, and we need to count backwards | |
const newTurns = 10 - turns; | |
return (totalTurns += newTurns); | |
} | |
}); | |
return totalTurns; | |
}; | |
combinationLock([0, 0, 0], [3, 1, 8]) | |
combinationLock([2, 3, 4, 5], [5, 4, 3, 2]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment