Skip to content

Instantly share code, notes, and snippets.

@radiofreejohn
Created April 26, 2011 04:18
Show Gist options
  • Save radiofreejohn/941786 to your computer and use it in GitHub Desktop.
Save radiofreejohn/941786 to your computer and use it in GitHub Desktop.
a routine I am working on to process sets of numbers
#include <stdlib.h>
#include <stdio.h>
#include "numbers.h" // https://gist.github.com/911872
struct Pair
{
int left;
int right;
};
struct Pairs
{
struct Pair *pairs;
int size;
};
/* makePairs
input: struct numbers
output: struct Pairs
Inputs a numbers structure {size, values} and constructs all possible
pairs of the numbers.
For any sequence of unique numbers of size N, there are Sum([N, N-1, N-2, ...) - N.size possible unique pairs.
This does not take into account permutations on the pairs
So for example, given a list of numbers [1, 2, 3, 4]
There are 1 + 2 + 3 + 4 - 4 = 6 total pairs
[1, 2] [1, 3] [1, 4]
[2, 3] [2, 4]
[3, 4]
There would be twice as many pairs if you consider swapped order, which I should
like to do later when I construct combined pairs after filtering these pairs.
*/
struct Pairs makePairs(struct numbers myList)
{
int i, j, k = 0;
struct Pairs myPairs;
myPairs.size = sumRange(&myList)-myList.size;
myPairs.pairs = malloc((sizeof(struct Pair)) * myPairs.size-myList.size);
for (i = 0; i < myList.size; i++)
{
for (j = i+1; j < myList.size; j++)
{
myPairs.pairs[k].left = myList.values[i];
myPairs.pairs[k].right = myList.values[j];
k++;
}
}
return myPairs;
}
void printPairs(struct Pairs *myPairs)
{
int i;
for (i = 0; i < myPairs->size; i++)
{
printf("[%03d, %03d] ",myPairs->pairs[i].left, myPairs->pairs[i].right);
}
printf("\n");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment