Skip to content

Instantly share code, notes, and snippets.

@jremmen
Last active August 29, 2015 14:03
Show Gist options
  • Save jremmen/4f88797486a65e0b4ddf to your computer and use it in GitHub Desktop.
Save jremmen/4f88797486a65e0b4ddf to your computer and use it in GitHub Desktop.
js: n Queens solver
Queens = function(num) {
function range(n) {
return Array.apply(null, new Array(n)).map(function(_, i) { return i; });
};
function is_safe(q, qs) {
if(qs.length == 0) return true;
return qs.filter(function(x, i) {
return Math.abs(q - x) != Math.abs(qs.length - (qs.length - (i + 1)));
}).length == qs.length;
};
function permutate(list) {
if(list.length == 1) return [list];
var collect = [];
permutate(list.slice(1)).map(function(p, j, a) {
range(p.length + 1).map(function(b, i) {
collect.push(p.slice(0, i).concat([list[0]]).concat(p.slice(i)));
});
});
return collect;
};
return {
solutions: (function(n) {
var queens = permutate(range(n));
return queens.filter(function(s) {
return s.filter(function(q, i, a) { return is_safe(q, a.slice(i + 1)); }).length == s.length;
});
})(num),
show: function(x) {
var solution = this.solutions[x];
return "\n" + solution.map(function(s) {
return range(solution.length).map(function(p, i) {
return s == i ? ' ' + s + ' ' : ' . ';
}).join('');
}).join("\n") + "\n";
},
showAll: function() {
var self = this;
return range(this.solutions.length).map(function(x) { return self.show(x); }).join("\n");
}
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment