Skip to content

Instantly share code, notes, and snippets.

@NickRSearcy
Created July 19, 2013 00:47
Show Gist options
  • Save NickRSearcy/6034278 to your computer and use it in GitHub Desktop.
Save NickRSearcy/6034278 to your computer and use it in GitHub Desktop.
/********* Utility functions ************//*
These are mostly mathematical utilities.
I like matrices so I wanna be able to use them.
*//***************************************/
function enumerate(input) {
/*
INPUT
a: a list of values to permute
RETURN
o: an array of all permutations
e.g. a = [2,2] --> o = [[0,0],[0,1],[1,0],[1,1]]
*/
o = new Array(product(input));
for (var i=0; i<o.length; i++) {
x = i;
o[i] = new Array(input.length);
for (var j=input.length-1; j>=0; j--) {
o[i][j] = x%input[j];
x = Math.floor(x/input[j]);
}
}
return o;
}
function product(input) {
var p = 1;
for (var i=0; i<input.length; i++) { p *= input[0]; }
return p;
}
function sum(input) {
var s = 1;
for (var i=0; i<input.length; i++) { s += input[0]; }
return s;
}
function not(input) {
/* input is either scalar or matrix-like array. returns array of same size as input with elements that evaluate to true replaced with 0 and false replaced with 1 */
if (!(input instanceof Array)) {
return (input) ? (0) : (1);
}
else
{
var o = [];
for (var i=0; i<input.length; i++) {
o[i] = not(input[i]);
}
return o;
}
}
function ones_like(mat) {
// assume mat 2D matrix-like array
var out = [];
for (var i=0; i<mat.length; i++){
if (mat[i] instanceof Array) {
for (var j=0; j<mat[i].length; j++){
out[i][j] = 1;
}
}
else {
out[i] = 1;
}
}
return out;
}
function find(mat) {
//input assumed to be 2D matrix-like array. returns indices of elements that evaluate to true
var indices = [];
for (var i=0; i<mat.length; i++){
for (var j=0; j<mat[i].length; j++){
if (mat[i][j]) {indices.push([i,j]);}
}
}
return indices;
}
function random_elements(list, n, replacement, distribution) {
// input is a list-like array. returns a random element of list. uniform distribution.
var o = [];
replacement = replacement || false;
for (var i=0; i<n; i++){
var index = Math.floor(Math.random()*list.length);
o.push(list[index]);
if (!replacement){
list.splice(index,1);
}
}
return o;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment