2014年11月1日土曜日

開発環境

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

その他参考書籍

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

コード(BBEdit, Emacs)

sample328.c

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

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)
{
  int a = *(int*)score_a;
  int b = *(int*)score_b;

  return b - a;
}

typedef struct {
  int width;
  int height;
} rectangle;

int compare_areas(const void* a, const void* b)
{
  rectangle *r_a = (rectangle*)a;
  rectangle *r_b = (rectangle*)b;
  int area_a = r_a->width * r_a->height;
  int area_b = r_b->width * r_b->height;
  
  return area_a - area_b;
}

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);
}

void p_scores(int scores[], size_t length)
{
  int i;

  for (i = 0; i < length; i++)
    printf("%d ", scores[i]);
  putchar('\n');
}

void p_areas(rectangle rectangles[], size_t length)
{
  int i;
  
  for (i = 0; i < length; i++)
    printf("%d ", rectangles[i].width * rectangles[i].height);
  putchar('\n');
}

void p_names(char *names[], size_t length)
{
  int i;
  for(i = 0; i < length; i++)
    printf("%s ", names[i]);
  putchar('\n');
}

int main(int argc, char *argv[])
{
  int scores[] = {543, 323, 32, 554, 11, 3, 112};
  rectangle rectangles[] = {{5, 1}, {1, 1}, {4, 1}, {2, 1}, {3, 1}};
  char* names[] = {"ae", "aa", "ad", "ab", "ac", "Ae", "Aa", "Ad", "Ab", "Ac"};

  printf("%d: ", rectangles[1].width);

  qsort(scores, 7, sizeof(int), compare_scores);
  p_scores(scores, 7);
  qsort(scores, 7, sizeof(int), compare_scores_desc);
  p_scores(scores, 7);
  qsort(rectangles, 5, sizeof(rectangle), compare_areas);
  p_areas(rectangles, 5);
  qsort(rectangles, 5, sizeof(rectangle), compare_areas_desc);
  p_areas(rectangles, 5);
  qsort(names, 10, sizeof(char*), compare_names);
  p_names(names, 10);
  qsort(names, 10, sizeof(char*), compare_names_desc);
  p_names(names, 10);

  return 0;
}

Makefile

P=
CC=cc
CFLAGS=-g -Wall # -O3
SRC=
OBJ=
LDLIBS=

$(P): $(OBJ)
 $(CC) $(CFLAGS) $(LDLIBS) $(OBJ) -o $@

入出力結果(Terminal)

$ make sample328
cc -g -Wall     sample328.c   -o sample328
$ ./sample328
1: 3 11 32 112 323 543 554 
554 543 323 112 32 11 3 
1 2 3 4 5 
5 4 3 2 1 
Aa Ab Ac Ad Ae aa ab ac ad ae 
ae ad ac ab aa Ae Ad Ac Ab Aa 
$

0 コメント:

コメントを投稿