Skip to content

Instantly share code, notes, and snippets.

@primaryobjects
Last active September 4, 2016 20:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save primaryobjects/4f9ca16cdc4a8ae0246a950de6fbc943 to your computer and use it in GitHub Desktop.
Save primaryobjects/4f9ca16cdc4a8ae0246a950de6fbc943 to your computer and use it in GitHub Desktop.
[2016-08-31] Challenge #281 [Intermediate] Dank usernames
//
// [2016-08-31] Challenge #281 [Intermediate] Dank usernames
// https://www.reddit.com/r/dailyprogrammer/comments/50hbtp/20160831_challenge_281_intermediate_dank_usernames/
// Demo: http://primaryobjects.github.io/dank/
// Kory Becker http://primaryobjects.com
//
// Load a word list and return an array of words, split upon the separator character(s).
function initialize(wordsFilePath, separator, callback) {
$.get(wordsFilePath, function(data) {
if (callback) {
callback(data.split(separator));
}
});
}
// Returns a list of words from the dictionary array, that contain matching consectutive letters in name.
function dankNames(name, dictionary, isVerbose) {
var results = [];
var count = 0;
var total = dictionary.length;
name = name.toLowerCase();
// Go through each word in the dictionary and check if each letter exists in the name (in order). If so, it's a match.
dictionary.forEach(function(word) {
if (++count % 10000 == 0 && isVerbose) {
console.log(count + '/' + total + ' ' + (Math.round(count / total * 100) / 100) + '% (' + word + ')');
}
var index = -1;
var isMatch = word.toLowerCase().split('').every(function(char) {
index = name.indexOf(char, index + 1);
return (index != -1);
});
if (isMatch) {
results.push(word);
}
});
return results;
}
// Returns the longest name(s) from an array.
function longestNames(names) {
var result = [];
var max = 0;
if (names.length) {
// Find the longest name.
var longest = names.reduce(function (a, b) { return a.length > b.length ? a : b; });
result = names.filter(function(name) {
return (name.length == longest.length);
});
}
return result;
}
initialize('words.txt', '\r\n', function(words) {
var input = ['Donald Knuth', 'Alan Turing', 'Claude Shannon', 'Kory Becker'];
input.forEach(function(name) {
console.log(name);
var names = dankNames(name, words);
console.log(longestNames(names));
});
});
<script src='https://code.jquery.com/jquery-3.1.0.min.js'></script>
<script src='dank.js'></script>
Source: http://norvig.com/ngrams/enable1.txt
Note: Running the code requires a web server (such as https://www.npmjs.com/package/http-server) due to reading a local file.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment