Skip to content

Instantly share code, notes, and snippets.

@Jiert
Last active January 12, 2017 15:54
Show Gist options
  • Save Jiert/35099c91da243fa275deeb3ad94fb726 to your computer and use it in GitHub Desktop.
Save Jiert/35099c91da243fa275deeb3ad94fb726 to your computer and use it in GitHub Desktop.
Alien Dictionary
var words = [
"wrt",
"wrf",
"er",
"ett",
"rftt"
]
var alphabet = []
var hash = {};
function insert(value) {
if (alphabet.indexOf(value) == -1) {
alphabet.splice(0, 0, value)
}
}
function findKey(keys) {
if (keys.length) {
keys.map(function(key) {
var values = hash[key]
if (values && values.length) {
values.map(function(value) {
if (keys.indexOf(value) == -1) {
insert(value)
values.pop(value)
}
})
delete hash[key]
findKey(Object.keys(hash))
} else {
insert(key)
}
})
}
}
function decoder(words) {
words.map(function(word, index, array) {
var currentWord = word
var nextWord = array[index + 1]
if (!nextWord) { return }
for (var i = 0; i < currentWord.length; i++) {
var currentChar = currentWord.charAt(i)
var comparisonChar = nextWord.charAt(i)
if (currentChar !== comparisonChar) {
if (hash[currentChar] && hash[currentChar].indexOf(comparisonChar) !== -1) {
hash[currentChar].push(comparisonChar);
} else {
hash[currentChar] = [comparisonChar];
}
return;
}
}
})
findKey(Object.keys(hash))
console.log(alphabet)
}
decoder(words)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment