Last active
February 24, 2019 01:27
-
-
Save 4skinSkywalker/a252d17621499dbb03c9d6da48d1074a to your computer and use it in GitHub Desktop.
The fourth hardest challenge listed in the “easy” section of Coderbyte.
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
function isValid(string) { | |
let v = 0 | |
let h = 0 | |
for (let char of string) { | |
if (char === 'd') v++ | |
if (char === 'u') v-- | |
if (char === 'r') h++ | |
if (char === 'l') h-- | |
} | |
for (let i = 1; i < string.length; i++) { | |
if (string[i - 1] + string[i] in {du: 1, ud: 1, rl: 1, lr: 1}) return false | |
} | |
return v === h && v === 4 | |
} | |
function combination(length, symbols) { | |
let combinations = []; | |
(function recursion(s = '') { | |
if (s.length === length) return combinations.push(s) | |
for (let symbol of symbols) recursion(s + symbol) | |
})() | |
return combinations | |
} | |
function correctPath(string) { | |
let countMarks = string.replace(/[^?]/g, '').length | |
let combinations = combination(countMarks, 'durl') | |
let startsWithMark = string.indexOf('?') === 0 | |
for (let combination of combinations) { | |
combination = [...combination] | |
let temp = string | |
if (startsWithMark && combination[0] in {u: 1, l: 1}) continue | |
while (temp.indexOf('?') > -1) { | |
temp = temp.replace('?', v => { | |
return combination.pop() | |
}) | |
} | |
if (isValid(temp)) return temp | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment