2014年7月18日金曜日

開発環境

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>

#include "sample328.h"

int compare_scores_desc(const void* score_a, const void* score_b)
{
  return compare_scores(score_b, score_a);
}

int compare_areas(const void* a, const void* b)
{
  rectangle *ra = (rectangle*)a;
  rectangle *rb = (rectangle*)b;

  return ra->width * ra->height - rb->width * rb->height;
}

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[], int n)
{
  int i;

  for (i = 0; i < n; ++i)
    printf("%i ", scores[i]);
  puts("");
}

void p_rectangles(rectangle r[], int n)
{
  int i;
  
  for (i = 0; i < n; ++i) {
    printf("%ix%i ", r[i].width,  r[i].height);
  }
  puts("");
}

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

int main(int argc, char *argv[])
{
  rectangle r[] = {{1, 5}, {1, 1}, {1, 4}, {1, 2}, {1, 3}};
  char* names[] = {"abcd", "Dabc", "bcda", "Cdab", "Bcda", "Abcd", "cdab",
                   "dabc"};

  p_scores(scores, 7);
  p_rectangles(r, 5);
  p_names(names, 8);

  puts("昇順");
  qsort(scores, 7, sizeof(int), compare_scores);
  qsort(r, 5, sizeof(rectangle), compare_areas);
  qsort(names, 8, sizeof(char*), compare_names);

  p_scores(scores, 7);
  p_rectangles(r, 5);
  p_names(names, 8);

  puts("降順");
  qsort(scores, 7, sizeof(int), compare_scores_desc);
  qsort(r, 5, sizeof(rectangle), compare_areas_desc);
  qsort(names, 8, sizeof(char*), compare_names_desc);

  p_scores(scores, 7);
  p_rectangles(r, 5);
  p_names(names, 8);

  return (0);
}

Makefile

CC=cc
CFLAGS=-g -Wall
SRC=sample328.c
OBJ=sample328.o

all: sample328

sample328: sample328.o
 $(CC) $(CFLAGS) $(OBJ) -o sample328

sample328.o: sample328.h sample328.c
 $(CC) $(CFLAGS) -c sample328.c -o sample328.o

clear:
 rm -rf sample328 $(OBJ)

入出力結果(Terminal)

$ make && ./sample328
cc -g -Wall -c sample328.c -o sample328.o
cc -g -Wall sample328.o -o sample328
543 323 32 554 11 3 112 
1x5 1x1 1x4 1x2 1x3 
abcd Dabc bcda Cdab Bcda Abcd cdab dabc 
昇順
3 11 32 112 323 543 554 
1x1 1x2 1x3 1x4 1x5 
Abcd Bcda Cdab Dabc abcd bcda cdab dabc 
降順
554 543 323 112 32 11 3 
1x5 1x4 1x3 1x2 1x1 
dabc cdab bcda abcd Dabc Cdab Bcda Abcd 
$

0 コメント:

コメントを投稿