2018年6月22日金曜日

開発環境

Head First C ―頭とからだで覚えるCの基本 (David Griffiths (著)、Dawn Griffiths (著)、中田 秀基 (監修)、木下 哲也 (翻訳)、オライリージャパン)の7章(高度な関数 - 関数を最大限に活用する)、長いエクササイズ(p. 328)を取り組んでみる。

長いエクササイズ(p. 328)

Makefile

CC = cc

all: sample run

sample: sample.c
 $(CC) sample.c -o sample

run: sample
 ./sample

コード

#include <stdio.h>
#include <stdlib.h> // qsort
#include <string.h> // strcmp

int compare_scores(const void *score_a, const void *score_b) {
  int a = *(int *)score_a;
  int b = *(int *)score_b;
  return a - b;
}
int compare_scores_desc(const void *score_a, const void *score_b) {
  return compare_scores(score_b, score_a);
}
typedef struct {
  int width;
  int height;
} Rectangle;
int compare_areas(const void *a, const void *b) {
  Rectangle *ra_ptr = (Rectangle *)a;
  Rectangle *rb_ptr = (Rectangle *)b;
  int ra_area = ra_ptr->width * ra_ptr->height;
  int rb_area = rb_ptr->width * rb_ptr->height;

  return ra_area - rb_area;
}
int compare_names(const void *a, const void *b) {
  char *name_a = *(char **)a;
  char *name_b = *(char **)b;
  return strcmp(name_a, name_b);
}

int compare_areas_desc(const void *a, const void *b) {
  return compare_areas(b, a);
}
int compare_names_desc(const void *a, const void *b) {
  return compare_names(b, a);
}

int scores_n = 5;
int scores[] = {5, 1, 4, 2, 3};
void display_scores() {
  for (size_t i = 0; i < scores_n; i++) {
    printf("%i ", scores[i]);
  }
  puts("");
}
int rects_n = 5;
Rectangle rects[] = {{1, 5}, {1, 1}, {1, 4}, {1, 2}, {1, 3}};
void display_rects() {
  for (size_t i = 0; i < rects_n; i++) {
    Rectangle r = rects[i];
    printf("%ix%i ", r.width, r.height);
  }
  puts("");
}
int names_n = 5;
char *names[] = {"ab", "CD", "cd", "AB", "z"};
void display_names() {
  for (size_t i = 0; i < names_n; i++) {
    printf("%s ", names[i]);
  }
  puts("");
}
int main() {
  display_scores();
  qsort(scores, scores_n, sizeof(int), compare_scores);
  display_scores();
  qsort(scores, scores_n, sizeof(int), compare_scores_desc);
  display_scores();
  qsort(rects, rects_n, sizeof(Rectangle), compare_areas);
  display_rects();
  qsort(rects, rects_n, sizeof(Rectangle), compare_areas_desc);
  display_rects();
  display_names();
  qsort(names, names_n, sizeof(char *), compare_names);
  display_names();
  qsort(names, names_n, sizeof(char *), compare_names_desc);
  display_names();
}

入出力結果(Terminal)

$ make
cc sample.c -o sample
./sample
5 1 4 2 3 
1 2 3 4 5 
5 4 3 2 1 
1x1 1x2 1x3 1x4 1x5 
1x5 1x4 1x3 1x2 1x1 
ab CD cd AB z 
AB CD ab cd z 
z cd ab CD AB 
$

0 コメント:

コメントを投稿