Skip to content

Instantly share code, notes, and snippets.

@loretoparisi
Created September 5, 2016 12:42
Show Gist options
  • Save loretoparisi/a6ddb8e0422cae072d9a26b9ad7d2993 to your computer and use it in GitHub Desktop.
Save loretoparisi/a6ddb8e0422cae072d9a26b9ad7d2993 to your computer and use it in GitHub Desktop.
Round robin scheduler in JavaScript - https://www.npmjs.com/package/roundrobin
function(n, ps) {
const DUMMY = -1;
var rs = []; // rs = round array
if (!ps) {
ps = [];
for (var k = 1; k <= n; k += 1) {
ps.push(k);
}
} else {
ps = ps.slice();
}
if (n % 2 === 1) {
ps.push(DUMMY); // so we can match algorithm for even numbers
n += 1;
}
for (var j = 0; j < n - 1; j += 1) {
rs[j] = []; // create inner match array for round j
for (var i = 0; i < n / 2; i += 1) {
if (ps[i] !== DUMMY && ps[n - 1 - i] !== DUMMY) {
rs[j].push([ps[i], ps[n - 1 - i]]); // insert pair as a match
}
}
ps.splice(1, 0, ps.pop()); // permutate for next round
}
return rs;
}
@loretoparisi
Copy link
Author

roundRobin(6)
[ [ [ 1, 6 ], [ 2, 5 ], [ 3, 4 ] ],
  [ [ 1, 5 ], [ 6, 4 ], [ 2, 3 ] ],
  [ [ 1, 4 ], [ 5, 3 ], [ 6, 2 ] ],
  [ [ 1, 3 ], [ 4, 2 ], [ 5, 6 ] ],
  [ [ 1, 2 ], [ 3, 6 ], [ 4, 5 ] ] ]

and

roundRobin(3,['a','b','c'])
[ [ [ 'b', 'c' ] ],
  [ [ 'a', 'c' ] ],
  [ [ 'a', 'b' ] ] ]

Adapted from this node module on npm.

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