Created
October 28, 2015 05:26
-
-
Save bobpace/329515cd1a9773d9b34a to your computer and use it in GitHub Desktop.
n queens in ramda
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
describe("n queens", function() { | |
var isSafe = R.curry((col, placedQueens) => { | |
var row = R.length(placedQueens); | |
var notThreatened = ([r, c]) => col !== c && Math.abs(col - c) !== row - r; | |
var rowsWithQueen = R.zip(R.reverse(R.range(0, row)), placedQueens); | |
return R.all(notThreatened, rowsWithQueen); | |
}); | |
var queens = (n) => { | |
var columns = R.range(0, n); | |
var placeQueens = (k) => { | |
if (k === 0) { | |
return R.of([]); | |
} | |
var findSafePlacements = (placedQueens) => { | |
var safePlacementsFor = R.pipe( | |
R.filter(isSafe(R.__, placedQueens)), | |
R.map(R.prepend(R.__, placedQueens)) | |
); | |
return safePlacementsFor(columns); | |
}; | |
return R.chain(findSafePlacements, placeQueens(k - 1)); | |
}; | |
return placeQueens(n); | |
}; | |
it("no solutions for 2x2 or 3x3", function() { | |
queens(2).should.eql([]); | |
queens(3).should.eql([]); | |
}); | |
it("two solutions for 4x4", function() { | |
queens(4).should.eql([ | |
[2, 0, 3, 1], | |
[1, 3, 0, 2] | |
]); | |
}); | |
it("ten solutions for 5x5", function() { | |
queens(5).should.eql([ | |
[3, 1, 4, 2, 0], | |
[2, 4, 1, 3, 0], | |
[4, 2, 0, 3, 1], | |
[3, 0, 2, 4, 1], | |
[4, 1, 3, 0, 2], | |
[0, 3, 1, 4, 2], | |
[1, 4, 2, 0, 3], | |
[0, 2, 4, 1, 3], | |
[2, 0, 3, 1, 4], | |
[1, 3, 0, 2, 4] | |
]); | |
}); | |
it("four solutions for 6x6", function() { | |
queens(6).should.eql([ | |
[4, 2, 0, 5, 3, 1], | |
[3, 0, 4, 1, 5, 2], | |
[2, 5, 1, 4, 0, 3], | |
[1, 3, 5, 0, 2, 4] | |
]); | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment