Created
June 16, 2016 17:03
-
-
Save danielrw7/5f968939ffbe72bbf7b0c94084ba47b4 to your computer and use it in GitHub Desktop.
Encoding data into an order of a fixed number of array indexes
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
function getOptions(len) { | |
return Array(len).join().split(",").map(function(c, i) { | |
return i; | |
}); | |
} | |
function getStep(i, len) { | |
return factorial(len) / len * i; | |
} | |
function to(order) { | |
var remainingOptions = getOptions(order.length); | |
var res = 0; | |
order.forEach(function(n, i) { | |
res += getStep(remainingOptions.indexOf(n), remainingOptions.length) | |
remainingOptions.splice(remainingOptions.indexOf(n),1) | |
}); | |
return res; | |
} | |
function from(res, len) { | |
var remainingOptions = getOptions(len); | |
var arr = []; | |
for(var i = 0; i < len; i++) { | |
var step = getStep(1, remainingOptions.length); | |
var n = Math.floor(res/step); | |
arr.push(remainingOptions[n]); | |
remainingOptions.splice(remainingOptions.indexOf(remainingOptions[n]),1) | |
res -= n*step; | |
} | |
return arr; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment