/** ex8-2.c 交差点のソート * キーボード入力した座標から近い順にデータを並び変えて画面に出力するプログラム) */ #include #include #include #define CROSSING_SIZE 100 /* 交差点数=100 */ #define MAX_NAME_SIZE 50 /* 最大文字数50文字(半角) */ typedef struct { double x, y; /* 位置 x, y */ } Position; /* 位置を表す構造体 */ typedef struct { int id; /* 交差点番号 */ Position pos; /* 位置を表す構造体 */ double wait; /* 平均待ち時間 */ char jname[MAX_NAME_SIZE]; /* 交差点名 */ char ename[MAX_NAME_SIZE]; /* 交差点名 */ int points; /* 交差道路数 */ int next[5]; /* 隣接する交差点番号 */ } Crossing; Crossing cross[CROSSING_SIZE]; int map_read(char *filename) { /* サーチで作ったものを参考にして下さい */ FILE *fp; int i, j; int crossing_number; /* 交差点数 */ fp = fopen(filename, "r"); if (fp == NULL) { printf("File %s is not created\n", filename); return -1; } /* はじめに交差点数を読み込む */ fscanf(fp, "%d", &crossing_number); if ((crossing_number < 1) || (crossing_number >= CROSSING_SIZE)) { printf("Illegal data number (%d)\n", crossing_number); return 0; } for (i = 0; i < crossing_number; i++) { fscanf(fp, "%d,%lf,%lf,%lf,%[^,],%[^,],%d", &(cross[i].id), &(cross[i].pos.x), &(cross[i].pos.y), &(cross[i].wait), cross[i].jname, cross[i].ename, &(cross[i].points)); for (j = 0; j < cross[i].points; j++) fscanf(fp, ",%d", &(cross[i].next[j])); } fclose(fp); /* ファイルから読み込んだ交差点数を返す */ return crossing_number; } void print_cross(int i) { /* サーチで作ったものを参考にして下さい */ int j; printf("交差点番号:%2d, 座標(%5.2lf,%5.2lf), 名前: %s ( %s ),", cross[i].id, cross[i].pos.x, cross[i].pos.y, cross[i].jname,cross[i].ename); printf("\n 待ち時間:%5.1lf, 隣接交差点 :%d個 ( ", cross[i].wait, cross[i].points); /* 交差道路数だけ繰り返し */ for (j = 0; j < cross[i].points; j++) printf("%d ", cross[i].next[j]); printf(")\n\n"); } /* ここら辺から入力してください */ /* num個表示 = 表示数制限可能 */ void print_cross_list(int num) { int i; for (i = 0; i < num; i++) print_cross(i); } /* バブルソートのプログラムを入力して下さい:元気がある人は他のも試してみましょう */ void bubble_sort(int num, double x0, double y0) { int i, j, lo, up; double d1, d2; /* 距離を計算します */ Crossing temp; /* 入れ替えのために使ってください */ lo = 0; up = num - 1; while (up > lo) { j = lo; for (i = lo; i < up; i++) { d1=hypot(cross[i].pos.x - x0, cross[i].pos.y - y0); d2=hypot(cross[i+1].pos.x - x0, cross[i+1].pos.y - y0); if (d1>d2) { /* 逆順なので i と i+1 を入れ替えましょう */ /* temp を使ってください */ temp = cross[i]; /* 入れ替え第1手順 */ cross[i] = cross[i+1]; /* 入れ替え第2手順 */ cross[i+1]=temp; /* 入れ替え第3手順 */ j = i; } } up = j; } } int main(void) { int crossing_number; /* 交差点数 */ double x, y; /* ファイルの読み込み */ crossing_number = map_read("map2.dat"); printf("loaded %d crossings\n", crossing_number); /* fprintf(stderr,... にすると、| more , | less などの影響を */ /* 受けなくなります */ fprintf(stderr, "基準座標を入力してください (%%lf %%lf 形式):\n"); scanf("%lf %lf", &x, &y); bubble_sort(crossing_number, x, y); print_cross_list(10); return 0; }