Advertisement
NikolaDimitroff

Generating ntuples

Nov 12th, 2013
150
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. var boundingVector = [5, 3, 3];
  2.  
  3. // A generic function to copy the tuple
  4. function copy(array) {
  5.     var newArray = [];
  6.     for (var i = 0; i < array.length; i++) {
  7.         newArray[i] = array[i];
  8.     }
  9.     return newArray;
  10. }
  11.  
  12. // A function that computes the successor of a given tuple
  13. function getNextTuple(lastGeneratedTuple) {
  14.     var newTuple = copy(lastGeneratedTuple)
  15.     for (i = boundingVector.length - 1; i >= 0; i--) {
  16.         // Increment the last coordinate. If it overflows,
  17.               // continue incrementing the next coordinate, else we are done
  18.         newTuple[i]++;
  19.         if (newTuple[i] > boundingVector[i] - 1) {
  20.             newTuple[i] = 0;
  21.         }
  22.         else {
  23.             break;
  24.         }
  25.     }
  26.     return newTuple;
  27. }
  28.  
  29. // A function that enumerates all possible tuples
  30. function enumerateAllTuples() {
  31.  
  32. // The number of tuples is the product of all segments
  33.     var numberOfTuples = 1;
  34.     for (i = 0; i < boundingVector.length; i++) {
  35.         numberOfTuples *= boundingVector[i];
  36.     }
  37.     var allTuples = [],
  38.         zeroTuple = [];
  39.     for (var i = 0; i < boundingVector.length; i++) {
  40.         zeroTuple[i] = 0;
  41.     }
  42.     allTuples[0] = zeroTuple;
  43.     for (i = 1; i < numberOfTuples; i++) {
  44.         allTuples[i] = getNextTuple(allTuples[i - 1]);
  45.     }
  46.     return allTuples;
  47. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement