Created
March 19, 2011 05:53
-
-
Save meric/877263 to your computer and use it in GitHub Desktop.
demo of sample size and vector types.
This file contains 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
#include "stdio.h" | |
/* a size type */ | |
typedef struct | |
{ | |
int width; | |
int height; | |
} size; | |
/* create a new size */ | |
size new_size(int width, int height) | |
{ | |
size s; | |
s.width = width; | |
s.height = height; | |
return s; | |
} | |
/* a coordinate vector type */ | |
typedef struct | |
{ | |
int x; | |
int y; | |
} vector; | |
/* create a new vector */ | |
vector new_vector(int x, int y) | |
{ | |
vector v; | |
v.x = x; | |
v.y = y; | |
return v; | |
} | |
/* convert vector to index, given size of grid */ | |
int vector_to_index(size s, vector v) | |
{ | |
return v.y * s.width + v.x; | |
} | |
/* convert index to vector, given size of grid */ | |
vector index_to_vector(size s, int index) | |
{ | |
return new_vector(index % s.width, index / s.width); | |
} | |
int main(void) | |
{ | |
/* size with width 15, height 15 */ | |
size s = new_size(10, 10); | |
printf("created size with width %d, height %d\n", s.width, s.height); | |
/* convert index 15 to vector */ | |
vector xy_at_15 = index_to_vector(s, 15); | |
printf("index 15 is coordinate %d, %d\n", xy_at_15.x, xy_at_15.y); | |
/* convert vector to index */ | |
int index_at_xy = vector_to_index(s, xy_at_15); | |
printf("index of coordinate %d, %d is %d\n", xy_at_15.x, xy_at_15.y, | |
index_at_xy); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment