#include #include #include #define kRows 16 #define kCols 16 #define kOffset 127U #define kFactor 31U #define kMax 255U // Value grid (e.g. image) to find matches for. bestMatch is index of closest // grid match thus far, and bestDifference is how different that match is. typedef struct { long long vals[kRows][kCols]; int bestMatch; int bestDifference; } Grid; // Create |len| made-up grids, putting them into array |grids| int MockupGrids(Grid *grids, int len) { int val, g, r, c; for (g = 0; g < len; g++) { val = g; for (r = 0; r < kRows; r++) { for (c = 0; c < kCols; c++) { val = (val + kOffset) * kFactor % INT_MAX; grids[g].vals[r][c] = val % kMax; } } grids[g].bestMatch = -1; grids[g].bestDifference = INT_MAX; } } inline int sqr(int x) {return x*x;} // Given an other Grid's id as |other|, and the |bestDifference| between // Grid |*g| and |other|, update |*g|s info accordingly. inline void UpdateGrid(Grid *g, int other, int difference) { if (difference < g->bestDifference) { g->bestMatch = other; g->bestDifference = difference; } } int main(int argc, char **argv) { unsigned checkSum = 0; int difference, numGrids, g1, g2, row, col; Grid *grids, *grid1, *grid2; if (argc != 2) { printf("Usage: GridMatcher \n"); exit(1); } numGrids = atoi(argv[1]); grids = (Grid *)calloc(sizeof(Grid), numGrids); MockupGrids(grids, numGrids); for (g1 = 0; g1 < numGrids; g1++) { grid1 = grids + g1; for (g2 = g1+1; g2 < numGrids; g2++) { grid2 = grids + g2; difference = 0; for (row = 0; row < kRows; row++) { for (col = 0; col < kCols; col += 4) difference += sqr(grid1->vals[row][col] - grid2->vals[row][col]); } UpdateGrid(grid1, g2, difference); UpdateGrid(grid2, g1, difference); } checkSum += grid1->bestDifference; } printf("Last grid matches %d with %d\n", grid1->bestMatch, grid1->bestDifference); printf("Checksum is %0u\n", checkSum); }