Skip to content

Instantly share code, notes, and snippets.

@forsvunnet
Created June 12, 2018 14:30
Show Gist options
  • Save forsvunnet/27a8c05de35f346fbe86ecec1c2a503f to your computer and use it in GitHub Desktop.
Save forsvunnet/27a8c05de35f346fbe86ecec1c2a503f to your computer and use it in GitHub Desktop.
Get all cell combinations from a 2d array
/**
* Recursive mapping
* @param array collection Any 2d array
* @param integer index The starting index (used for recursion)
* @return array Array with all possible combination of items
*/
var generate_combinations = function( collection, index ) {
// Sanity check
if ( ! collection[ index ] ) {
// This will never happen unless an invalid index is used
return [];
}
// Get the row for the current recursion
var row = collection[index];
// Special handling of the last row
// Last index means there is no next collection
if ( collection.length - 1 == index ) {
// Create a element with the same structure
var other_rows = [];
// Divide each cell into seperate rows
for (var i = 0; i < row.length; i++) {
var cell = row[i];
other_rows.push( [ cell ] );
}
// Return the last row
return other_rows;
}
// Begin the main recursion logic and start building the result
var result = [];
// Recursion! Build the next row before this one.
// Note that because recursive mapping is called here then it will
// start at the deepest level and then bubble back to the beginning
var other_rows = generate_combinations( collection, index + 1 );
// Loop through this level
for ( var i = 0; i < row.length; i++ ) {
// Get the current cell
var cell = row[i];
// Uncomment this line to debug the recursion:
// console.log( 'Depth:' + index + ' @Itteration:' + i +', cell: '+ cell );
// Loop through the other rows
for ( var j = 0; j < other_rows.length; j++ ) {
var other_row = other_rows[j];
// Create a new record begining with the current cell
var combination_cell = [ cell ];
// Combine the new record with all the other combinations
// from the other rows
for ( var v = 0; v < other_row.length; v++ ) {
var other_cell = other_row[v];
combination_cell.push( other_cell );
}
// Finally add the combined cell to the result
result.push( combination_cell );
}
}
return result;
}
// A test array
var testing = [
['B1','B2'],
['A1','A2','A3'],
['C1','C2'],
];
console.log(
generate_combinations( testing, 0 )
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment