Lab1 - 4 Slides Per Page
Lab1 - 4 Slides Per Page
Lab1 - 4 Slides Per Page
Programming Techniques
Lab 1
Note on invariants
Star proximity
Profiling
Debugging
Invariants
#define assert(ignore)((void) 0)
Problem Statement
#of:
Red:
Blue:
#of:
Red: 5
Blue: 5
Red found!
Swap!
Red found!
Swap!
Red found!
Swap!
Method comparison
Method comparison
-O3 optimizations
30
25
20
Time (ms)
Time (ms)
15
10
5
0
4096
1024
65536
16384
1048576
16777216
262144
4194304
4096
1024
65536
16384
1048576
16777216
262144
4194304
Input Size
Input size
Same experiment run with optimization disabled (left) and with optimization (-O3
flag) enabled (right). The red blue is represented by 0 and 1, respectively, in an
array of integers.
Method Comparison
-O3 optimization
60
60
50
50
40
40
Time (ms)
Time (ms)
30
20
10
30
20
10
0
2048
2048
1024
8192
4096
32768
16384
131072
524288
65536
262144
1024
8192
4096
32768
131072
524288
16384
65536
262144
Input Size
Input Size
Same experiment run with optimization disabled (left) and with optimization (-O3
flag) enabled (right). The red blue is represented by a struct of 808 bytes.
Problem invariants:
All the cells to the left of red marker are red!
All the cells to the right of blue marker are blue!
Star proximity
Task: Find all the pairs of
points that are closer than
a given distance d, (d<1 ).
d i , j = ( x i x j )2 +( y i y j )2
But, we will end up with a vast
amount of comparisons! Since
we have N dots and we compare
each one of them with the
remaining N-1 dots, we end up
with
N*(N-1)/2
~
O(N 2)
calculations.
This
problem
becomes infeasible for large N.
xi < xj
or
xi = xj and yi < yj
4.0
2.1
4.0
5.7
4.3
0.1
4.4
1.6
5.3
3.2
5.5
3.1
5.5
3.3
5.5
9.1
5.5
13.3
7.0
4.0
4.0
2.1
4.0
5.7
4.3
0.1
4.4
5.3
1.6
3.2
6.0
3.1
6.0
3.3
6.0
9.1
6.0
13.3
7.0
4.0
Since d<1
We could divide
the big grid into a
linked list of
smaller grids
Each sub-grid
covers an area of
d2
All the points in
one grid will look
only for the points
in adjacent grids
We managed to decrease
the complexity to O(d 2N2)
(Since d<1
d 2N2< N2 )
Star proximity
int main(int argc, char *argv[])
{ int i, j, N = atoi(argv[1]);
d = atof(argv[2]);
G = 1/d;
grid = malloc2d(G+2, G+2);
for (i = 0; i < G+2; i++)
for (j = 0; j < G+2; j++)
grid[i][j] = NULL;
for (i = 0; i < N; i++)
gridinsert(randFloat(), randFloat());
printf("%d edges shorter than %f\n", cnt, d);
return 0;
}
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include "Point.h"
typedef struct node* link;
struct node { point p; link next; };
link **grid; int G; float d; int cnt = 0;
gridinsert(float x, float y)
{ int i, j; link s;
int X = x*G +1;
int Y = y*G+1;
link t = malloc(sizeof *t);
t->p.x = x;
t->p.y = y;
for (i = X-1; i <= X+1; i++)
for (j = Y-1; j <= Y+1; j++)
for (s = grid[i][j]; s != NULL; s = s->next)
if (distance(s->p, t->p) < d) cnt++;
t->next = grid[X][Y]; grid[X][Y] = t;
}