Skip to content

Instantly share code, notes, and snippets.

@benshimmin
Last active August 29, 2015 14:10
Show Gist options
  • Save benshimmin/31b5191466699cd31fb4 to your computer and use it in GitHub Desktop.
Save benshimmin/31b5191466699cd31fb4 to your computer and use it in GitHub Desktop.
How to solve The Times 2 "Polygon" puzzle
#!/usr/bin/env node
// This should solve the "Polygon" puzzle in The Times 2 "MindGames".
// Assumes a *nix system with the usual dictionary of words in the usual
// place.
// A few of the rules for what words count are a bit complicated... you could
// probably extend this with a Porter Stemmer, if you cared enough.
var fs = require("fs"),
readline = require("readline"),
_ = require("underscore"),
WORDS = fs.readFileSync("/usr/share/dict/words").toString().split("\n");
var Solver = function() {
var inputs = [],
centre,
num;
(function trimWords() {
WORDS = _.chain(WORDS)
// excluding capitalised words
.reject(function(word) {
return /[A-Z]/.test(word[0]);
})
// plurals - TODO
// conjugated words - TODO
// adverbs ending in LY
.reject(function(word) {
return /ly$/.test(word);
})
// comparatives and superlatives - TODO
.value();
})();
var solve = function() {
var last = _.last(inputs, 2);
centre = last[0];
num = parseInt(last[1], 10);
console.log("Letters:\n", _.first(inputs, inputs.length - 1).join(","));
console.log("Must contain:\n", centre);
WORDS = _.chain(WORDS)
// must contain the centre
.reject(function(word) {
return word.indexOf(centre) < 0;
})
// must not be longer than the words in the polygon
.reject(function(word) {
return word.length > inputs.length;
})
// and must not be less than `num` letters
.reject(function(word) {
return word.length < num;
})
.value();
WORDS = _.select(WORDS, function(word) {
var len = word.length,
_inputs = inputs,
match = 0,
i = 0,
l,
idx;
for (; i < len; ++i) {
l = word[i];
if ((idx = _inputs.indexOf(l)) > -1) {
++match;
var arr = _inputs;
_inputs = (arr.slice(0, idx) + arr.slice(idx + 1));
} else {
break;
}
}
return match === len;
});
var result = WORDS.sort(function(a,b) {
return b.length - a.length;
});
console.log("\nLongest:\n", result.shift());
console.log("\nThe rest:\n", result.sort().join(", "));
};
return {
add : function(line) {
inputs.push(line[0]);
},
solve : solve
}
};
console.log("Enter the letters, pressing return after each one.");
console.log("Enter the letter in the middle of the polygon last.");
console.log("Finish with the *minimum length* of word required (usually three or four).");
var solver = new Solver();
var rl = readline.createInterface({
input : process.stdin,
output : process.stdout,
terminal : false
})
.on("line", function(line) {
!line.length ? rl.close() : solver.add(line);
})
.on("close", solver.solve);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment