Created
June 26, 2011 04:47
-
-
Save dbrady/1047254 to your computer and use it in GitHub Desktop.
Process every pair in a set only once
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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)