Sorting Problem
HTML
<div id="output"></div>
JavaScript
////////////////
// EDIT THESE //
////////////////
// These are the rules to follow
// [1, 4] means that a one should not touch a 4
var rules = [
[1, 4],
[1, 2],
[3, 1],
[4, 3],
[3, 2],
[4, 2]
];
// This is the list of numbers to find the best answer for
var toSort = "1423";
/////////////////
// DO NOT EDIT //
/////////////////
var possibilities = [];
// http://codereview.stackexchange.com/questions/59615/recursive-function-that-generates-the-permutations-of-a-string
function doPerm(str, arr) {
if (typeof (str) == 'string') str = str.split('');
if (str.length == 0) possibilities.push(arr.join(''));
for (var i = 0; i < str.length; i++) {
var x = str.splice(i, 1);
arr.push(x);
doPerm(str, arr);
arr.pop();
str.splice(i, 0, x);
}
}
doPerm(toSort, []);
function scoreOf(m) {
var newScore = 0;
for (n = 0; n < rules.length; n++) {
if (rules[n][0] == parseInt(m[0])) {
if (rules[n][1] == parseInt(m[1])) {
newScore++;
}
if (rules[n][1] == parseInt(m[2])) {
newScore++;
}
}
}
return newScore;
}
var scores = possibilities.map(
function (s) {
var score = 0;
for (i = 0; i < s.length; i++) {
score += scoreOf([s.charAt(i), s.charAt(i - 1), s.charAt(i + 1)]);
}
return score;
});
console.log(possibilities);
console.log(scores);
function getBest() {
var tmp_best = [];
var tmp_bScore = scores[0] + 1;
for (i = 0; i < scores.length; i++) {
if (scores[i] < tmp_bScore) {
tmp_best = [possibilities[i]];
tmp_bScore = scores[i];
} else if (scores[i] == tmp_bScore) {
tmp_best.push(possibilities[i]);
}
}
return tmp_best;
}
var bestOptions = getBest();
var elem = document.getElementById("output");
elem.innerHTML = "";
for (i = 0; i < bestOptions.length; i++) {
elem.innerHTML +=...