Last active
September 17, 2020 06:56
-
-
Save hassan-maavan/2c06fdcfe57ca87b292615fdaf5b9e0e to your computer and use it in GitHub Desktop.
Recover a secret string from random triplets
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
var recoverSecret = function(triplets) { | |
let duplets = []; | |
let res = ''; | |
triplets.forEach(trip => { | |
duplets.push(trip.slice(0,2).join('')); | |
duplets.push(trip.slice(1, 3).join('')); | |
}) | |
duplets = duplets.filter((value, index, array) => array.indexOf(value) === index) | |
let word = getWord(duplets); | |
while(word) { | |
res += word; | |
duplets = duplets.filter(d => d.indexOf(word) === -1) | |
word = getWord(duplets); | |
} | |
return res; | |
} | |
const getWord = function(duplets) { | |
let word = duplets.find(duplet => duplets.every(dup => dup[1] !== duplet[0])) | |
return duplets.length > 1 ? word[0] : duplets[0] | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment