Created
July 5, 2013 08:19
-
-
Save auser/5932901 to your computer and use it in GitHub Desktop.
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
<!doctype html> | |
<html ng-app> | |
<head> | |
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js"></script> | |
</head> | |
<body> | |
<div ng-controller="nQueensController"> | |
<label>Number:</label> | |
<input type="number" ng-model="n" placeholder="Enter a number"> | |
<ul> | |
<li ng-repeat="s in solutions"> | |
Solutions for: {{ s.n }} queens: {{ s.count }} | |
</li> | |
</ul> | |
</div> | |
</body> | |
</html> | |
<script type="text/javascript"> | |
function nQueensController($scope) { | |
$scope.n = 2; | |
$scope.solutions = []; | |
var solve = function() { | |
$scope.solutions = []; | |
var n = $scope.n; | |
for (i = 0; i < n; i++) { | |
var obj = {n: i, count: 0}, | |
mask = (1 << i) - 1; | |
var solveF = function(columns, leftDiag, rightDiag) { | |
var poss = ~(columns|leftDiag|rightDiag) & mask; | |
while (poss > 0) { | |
var bit = -poss & poss; // valid position | |
c = columns | bit; | |
poss = poss ^ bit; | |
ol = (leftDiag | bit) << 1; | |
or = (rightDiag | bit) >> 1; | |
solveF(c,ol,or); | |
} | |
if (columns === mask){ | |
obj.count += 1; | |
} | |
} | |
solveF(0,0,0); | |
$scope.solutions.push(obj); | |
} | |
} | |
$scope.$watch('n', solve); | |
} | |
</script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment