第8週 ポインタの応用
前回の復習
練習問題の解答
code: pointer_practice.c
typedef struct {
double x;
double y;
} Point;
typedef struct {
Point a;
Point b;
Point c;
} Triple;
typedef enum {Red, Orange, Yellow, Blue, Cyan, Green, Brown, Gray} Color;
typedef struct {
Triple tri;
Color color;
} Triangle;
// 前回実装した関数
double distance(Point, Point);
int is_triangle(Triple);
double calc_area(Triple);
Point make_point();
Triple make_triangle();
void print_triangle(Triple);
Triangle generate();
// 今回実装する関数
void centering_triangle(Triangle *);
Triangle *generate_triangle_array(int);
int compare_triangle(const void *, const void *);
void sort_triangle_array(Triangle *, int);
int main() {
srand(time(NULL));
Triangle *triangles = generate_triangle_array(15);
for (int i = 0; i < 15; i++) {
centering_triangle(triangles + i);
}
sort_triangle_array(triangles, 15);
for (int i = 0; i < 15; i++) {
printf("Triangle %d:\n", i);
print_triangle(trianglesi.tri); printf("Area: %lf\n", calc_area(trianglesi.tri)); puts("");
}
}
double distance(Point a, Point b) {
double dx = a.x - b.x, dy = a.y - b.y;
return sqrt(dx * dx + dy * dy);
}
int is_triangle(Triple t) {
double a, b, c;
a = distance(t.b, t.c);
b = distance(t.c, t.a);
c = distance(t.a, t.b);
return (a+b>c)&&(b+c>a)&&(c+a>b);
}
double calc_area(Triple d) {
if(!is_triangle(d)) {
return -1;
}
Point a = d.a, b = d.b , c = d.c;
double res = (a.x - c.x) * (b.y - c.y) - (b.x - c.x) * (a.y - c.y);
return fabs(res / 2.);
}
Point make_point() {
Point res;
res.x = rand() % 100;
res.y = rand() % 100;
return res;
}
Triple make_triangle() {
Triple tri;
double area = calc_area(tri);
while(area <= 0 || 100 < area) {
tri.a = make_point();
tri.b = make_point();
tri.c = make_point();
area = calc_area(tri);
}
return tri;
}
void print_triangle(Triple tri) {
if(!is_triangle(tri)) {
puts("tri is not a triangle");
return;
}
printf("(x1, y1): (%lf, %lf)\n", tri.a.x, tri.a.y);
printf("(x2, y2): (%lf, %lf)\n", tri.b.x, tri.b.y);
printf("(x3, y3): (%lf, %lf)\n", tri.c.x, tri.c.y);
}
Triangle generate() {
static int color;
Triple tri = make_triangle();
Triangle res = {tri, (Color)color};
color++;
if(color > 7) color = 0;
return res;
}
// ここから新しく追加する関数
void centering_triangle(Triangle *t) {
Point offset;
Triple *tri = &(t->tri);
offset.x = (tri->a.x + tri->b.x + tri->c.x) / 3;
offset.y = (tri->a.y + tri->b.y + tri->c.y) / 3;
tri->a.x -= offset.x;
tri->b.x -= offset.x;
tri->c.x -= offset.x;
tri->a.y -= offset.y;
tri->b.y -= offset.y;
tri->c.y -= offset.y;
}
Triangle *generate_triangle_array(int size) {
return (Triangle *)malloc(sizeof(Triangle) * size);
}
int compare_triangle(const void *l, const void *r) {
return (int)(calc_area(((Triangle *)r)->tri) - calc_area(((Triangle *)l)->tri));
}
void sort_triangle_array(Triangle *ts, int size) {
qsort(ts, size, sizeof(Triangle), compare_triangle);
}
今回の内容
線形リストの構築
スタック・キューの構築
このディレクトリにある資料を4から順に読み、実装してください。
なお、これはSNコースのプログラミング演習2の資料です、一切の外部公開を禁止します。