Last active
December 28, 2015 11:43
-
-
Save MrTrick/be21f07013bc080ccd67 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
function ncmp(a, b) { return a - b; } | |
function format(set) { return JSON.stringify(set).replace(/\],\[/g,') (').replace('[[','[(').replace(']]','])'); } | |
function generate_combinations(dims) { | |
"use strict"; | |
function next(el) { for(var i=dims.length-1;i>=0;i--) { if (++el[i]<dims[i]) return true; else el[i]=0; } return false; } | |
function first() { return Array.apply(null, Array(dims.length)).map(function() { return 0; }); } | |
function upperlimit() { var _ds = dims.slice().sort(ncmp); return _ds[0]*_ds[1]; } | |
function valid(set,n) { for(var i=0;i<n;i++) { for(var c=0,di=0;di<set[n].length;di++) if (set[n][di]===set[i][di]) if (++c>1) return false; } return true; } | |
var limit = upperlimit(); | |
var set = []; | |
var n; | |
var winner=[]; | |
var iteration=0; | |
set[0] = first(); //set[0] is fixed at the first value | |
set[1] = set[0].slice(); | |
do { next(set[1]) } while(!valid(set,1)) //set[1] is fixed at the next valid value | |
set[2] = set[1].slice(); n=2; //PUSH | |
while(n>1) { | |
if (!next(set[n])){n--; continue;} //POP | |
if (!valid(set,n)) continue; //NEXT | |
if(!(++iteration%10000)) console.log(iteration, winner.length, format(set.slice(0,n))); | |
//Valid! | |
if (n>=winner.length) { | |
winner = set.slice(0).map(function(s){return s.slice();}); | |
//console.log("new", winner.length, format(winner)); | |
if (winner.length == limit) return winner; //DONE. | |
} | |
//Descend | |
set[n+1] = set[n].slice(); n++; //PUSH | |
} | |
return winner; | |
} | |
//START node.js code - gets the dimensions from the command-line | |
if (process.argv.length<3) { console.error("Need dimensions"); process.exit(1); } | |
var dims = []; | |
for(i=2;i<process.argv.length;i++) { | |
n = parseInt(process.argv[i]); | |
if (!n) { console.error("Each dim must be numeric and >0"); process.exit(2); } | |
dims.push(n); | |
} | |
//END node.js code - could substitute with eg var dims = [4,5,7,7]; | |
dims.sort(ncmp); | |
for(i=2;i<=dims.length;i++) { | |
_dims = dims.slice(0,i); | |
solution = generate_combinations(_dims); | |
console.log("N="+_dims.length+" C("+_dims.join(',')+") = "+solution.length+" values: "+format(solution)); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment