Skip to content

Instantly share code, notes, and snippets.

@dbrady
Created June 26, 2011 04:47
Show Gist options
  • Save dbrady/1047254 to your computer and use it in GitHub Desktop.
Save dbrady/1047254 to your computer and use it in GitHub Desktop.
Process every pair in a set only once
// How to do this algorithm in Smalltalk? Call a function on each pair of elements
// in a set once. Do not call func(b,a) if func(a,b) has already been called.
var i,j,ray,func;
ray = [3,2,11,7,5];
func = function(a,b) {
console.log(a + "x" + b + " -> " + a*b);
};
// For first item, iterate over every item but the last one.
for(i=0; i<ray.length-2; ++i) {
// For the second item, iterate over every item from i+1 to the end.
for(j=i+1; j<ray.length-1; ++j) {
func(ray[i], ray[j]);
}
}
// Output:
// 3x2 -> 6
// 3x11 -> 33
// 3x7 -> 21
// 2x11 -> 22
// 2x7 -> 14
// 11x7 -> 77
@dbrady
Copy link
Author

dbrady commented Jun 26, 2011

ALso ,not commented, but the code does this, too: don't call func(a,a). (If you want to allow calling func(a,a), change the second loop to start with i=j)

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