I wrote a Javascript function that seems to successfully generate the unique pairwise combinations of a list:
function pairwise(list) {
var pairs = [];
list
.slice(0, list.length - 1)
.forEach(function (first, n) {
var tail = list.slice(n + 1, list.length);
tail.forEach(function (item) {
pairs.push([first, item])
});
})
return pairs;
}
pairwise('abcd'.split(''))
// [["a","b"],["a","c"],["a","d"],["b","c"],["b","d"],["c","d"]]
I checked it by using the combinatorics formula:
$$ combinations = \frac{n(n-1)}{2} $$
var alpha = [ "a", "b", "c", "d", "e", "f", "h", "i", "j" ];
for(var n=1;n<7;n++){
console.log(
n, // number of items
pairwise(alpha.slice(0,n)).length, // how many pairs from function?
n*(n-1)/2 // double check with formula above
);
}
// 1 0 0
// 2 1 1
// 3 3 3
// 4 6 6
// 5 10 10
// 6 15 15
Which looks right: there are 6 ways to chose pairs from 4 items, and so on.
It works, but I find it hard to read, and I'm not sure how to make it more readable. I'd welcome suggestions.