Skip to content

Instantly share code, notes, and snippets.

@justinmarsan
Last active December 19, 2015 07:09
Show Gist options
  • Save justinmarsan/5916407 to your computer and use it in GitHub Desktop.
Save justinmarsan/5916407 to your computer and use it in GitHub Desktop.
// possible words
var words = ["lazy", "crackers", "hello", "cruel", "world", "bears", "need", "not", "apply"];
// characters
var puzzle = " \
r b f x w \
h e l l o \
o a h c r \
c r u e l \
v s u f d \
";
var solve = function solve(puzzle, words) {
var puzzle_lines_array = [],
puzzle_lines = [],
puzzle_array = [],
found_words = [],
row = 0,
column = -1,
line = '',
f_find_letter = _.memoize(function(letter) {
var coords = false;
_.each(puzzle_lines_array, function(e, y) {
_.each(e, function(f, x) {
if(!coords) {
coords = [];
}
if(letter == f) {
coords.push({'x': x, 'y': y});
}
});
});
return coords;
}),
f_letter_at = function(x, y) {
return puzzle_lines_array[y][x];
};
//Split the string in lines
_.each(puzzle, function(e) {
if(e != " ") {
if(column == 4) {
puzzle_lines.push(line);
line = e;
column = 0;
row++;
}
else if(column == 3 && row == 4) {
puzzle_lines.push(line + e);
}
else {
line = line + e;
column++;
}
}
});
// console.log(puzzle_lines);
//Split the lines in arrays
_.each(puzzle_lines, function(e, i) {
puzzle_lines_array.push(e.split(''));
});
// console.log(puzzle_lines_array);
//Loop through possible words
_.each(words, function(e) {
var word = e,
first = _.first(e),
last = _.last(e),
first_coords = f_find_letter(first);
//Get positions of first letter
_.each(first_coords, function(f) {
if(f.x + word.length <= 5) {
//Enough space for word horizontally
//Loop through word letter to see if match
for(var _i = 0, _len = word.length; _i < _len; _i++) {
var _x = _i + f.x,
_y = f.y;
if(f_letter_at(_x, _y) != word[_i]) {
break;
}
else if(_i + 1 == _len) { // last word
found_words.push(word);
}
}
}
if(f.y + word.length <= 5) {
//Enough space for word vertically
//Loop through word letter to see if match
for(var _i = 0, _len = word.length; _i < _len; _i++) {
var _x = f.x,
_y = _i + f.y;
if(f_letter_at(_x, _y) != word[_i]) {
break;
}
else if(_i + 1 == _len) { // last word
found_words.push(word);
}
}
}
});
});
return found_words;
};
solve(puzzle, words);
//=> ["hello", "cruel", "world", "bears"]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment