Skip to content

Instantly share code, notes, and snippets.

@ancms2600
Created May 13, 2018 18:35
Show Gist options
  • Save ancms2600/dddcc1bf1d1a5f4e7ec9aa30ad4393a5 to your computer and use it in GitHub Desktop.
Save ancms2600/dddcc1bf1d1a5f4e7ec9aa30ad4393a5 to your computer and use it in GitHub Desktop.
CROSS JOIN implementation in Javascript
var crossJoin = (...args) => {
const m = args.reduce((acc,a)=>{
acc.push(0 === acc.length ?
a.length :
(acc[acc.length-1] * a.length));
return acc;
},[]);
const o = [];
for (const [i,letters] of args.entries()) {
const slots = m[m.length-1];
const cmult = m[i];
const letterlen = letters.length;
const loccur = slots / cmult;
const poccur = slots / (letterlen * loccur);
for (let poi = 0; poi<poccur; poi++) {
for (const [li, letter] of letters.entries()) {
for (let loi = 0; loi<loccur; loi++) {
const ipr = slots / poccur;
const y = ((poi * ipr)) + (li * loccur) + loi, x = i;
if (null == o[y]) o[y] = [];
o[y][x] = letter;
}
}
}
}
return o;
};
crossJoin([1,2], [3,4], [5,6], [7]); // 4 x 8
@ancms2600
Copy link
Author

notes:

                 4    cols
   2    4    8   8    cmult = cumulative multiplier
  12 x 34 x 56 x 7    
   8    8    8   8    slots = rows = len
   2    2    2   1    ll = letter len
   4    2    1   1    loccur = letter occur = alternate at = len / cmult
   1    2    4   8    poccur = pattern occur = (len / (ll * loccur))
   8    4    2   1    ipr = inverse of poccur (1-indexed) = len / poccur

0 1    3    5    7
1 1    3     6   7
2 1     4   5    7
3 1     4    6   7
4  2   3    5    7
5  2   3     6   7
6  2    4   5    7
7  2    4    6   7

  ((poi * ipr)) + (li * loccur) + loi = y

round 1
all 0
0 * 8

round 2
0 * 4
0 * 4
0 * 4
0 * 4
1 * 4
1 * 4
1 * 4
1 * 4

round 3
0 = 0 * 2
0 = 0 * 2
2 = 1 * 2
2 = 1 * 2
4 = 2 * 2
4 = 2 * 2
6 = 3 * 2
6 = 3 * 2

round 4
0 * 1
1 * 1 
2 * 1
3 * 1
4 * 1
5 * 1
6 * 1
7 * 1

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment