#05
// dswaptest.c --- demonstration of dswap.
#include <stdio.h>
#include <stdlib.h>
void dswap(double *x, double *y) {
double z = *x; *x = *y; *y = z;
}
int main(int argc, char *argv[]) {
double a = atof(argv[1]), b = atof(argv[2]);
printf("a = %g, b = %g\n", a, b);
dswap(&a, &b);
printf("a = %g, b = %g\n", a, b);
return 0;
}
// test_dswap.c --- unit test for dswap.
#include <math.h>
#include <stdio.h>
void dswap(double *x, double *y) {
double z = *x; *x = *y; *y = z;
}
void expect_double(double a, double b, double d, char *msg) {
printf("%s %.10g:%.10g %s\n", (fabs(a-b)<d)?"OK":"NG" , a, b, msg);
}
int main(void) {
double a = 3.14, b = 2.71; dswap(&a, &b);
expect_double(a, 2.71, 1e-10, "a should be 2.71");
expect_double(b, 3.14, 1e-10, "b should be 3.14");
}
int gcd(int x, int y) {
if(x == y) {
return x;
} else if(x > y) {
return gcd(x-y, y);
} else {
return gcd(x, y-x);
}
}
// hanoi.c --- tower of hanoi
#include <stdio.h>
#include <stdlib.h>
void hanoi(int k, int x, int y, int z) {
if(k == 1) {
printf("move disc %d from %c to %c.\n", k, x, y);
} else {
hanoi(k-1, x, z, y);
printf("move disc %d from %c to %c.\n", k, x, y);
hanoi(k-1, z, y, x);
}
}
int main(int argc, char *argv[]) {
hanoi(atoi(argv[1]), 'A', 'B', 'C'); return 0;
}
// railmap2.h -- a railroad map (fields added)
#include <stdbool.h>
struct node { char *name; int num, edge[5], prev; bool visit; };
struct node map[] = {
{ "yokohama", 3, { 1, 3, 4 }, -1, false }, // 0
{ "kawasaki", 3, { 0, 2, 5 }, -1, false }, // 1
{ "shinagawa", 3, { 1, 3, 9 }, -1, false }, // 2
{ "osaki", 3, { 0, 2, 6 }, -1, false }, // 3
{ "hachiouji", 2, { 0, 5 }, -1, false }, // 4
{ "tachikawa", 3, { 1, 4, 6 }, -1, false }, // 5
{ "shinjuku", 4, { 3, 5, 8, 7 }, -1, false }, // 6
{ "ikebukuro", 3, { 6, 11, 12 }, -1, false }, // 7
{ "ochanomizu", 3, { 6, 9, 10 }, -1, false }, // 8
{ "tokyo", 3, { 2, 8, 10 } , -1, false }, // 9
{ "akihabara", 3, { 8, 9, 11 }, -1, false }, // 10
{ "tabata", 3, { 7, 10, 12 }, -1, false }, // 11
{ "akabane", 2, { 7, 11 }, -1, false }, // 12
};
// searchrec.c --- search path with recursion
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include "railmap2.h"
void search(int cur, int goal, int len) {
if(map[cur].visit) { return; }
if(cur == goal) { printf("len = %d\n", len); return; }
map[cur].visit = true;
for(int i = 0; i < map[cur].num; ++i) {
int k = map[cur].edge[i], p = map[k].prev;
map[k].prev = cur; search(k, goal, len+1); map[k].prev = p;
}
map[cur].visit = false;
}
int main(int argc, char *argv[]) {
int from = atoi(argv[1]), to = atoi(argv[2]);
search(from, to, 0); return 0;
}