challenge データの整列

(x, y) の座標情報を以下の2種類の方法で整列する機能を実現してください。

  • (x, y) の辞書順(まず x で昇順に整列して、x が同じデータに対して y で昇順に整列する)
  • (0, 0) からの距離の昇順

データの表現方法はタプルなり構造体/オブジェクトなり各自で適当に選んで下さい。

Posted feedbacks - C

シンプルにクイックソートで。
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
#include <stdio.h>
#include <stdlib.h>

typedef struct {
    int x;
    int y;
} point;

int compare_val(const point *a, const point *b){
    if (a->x==b->x){
        return a->y-b->y;
    }else{
        return a->x-b->x;
    }
}

int compare_dist(const point *a, const point *b){
    long dist_a,dist_b;
    dist_a=a->x*a->x+a->y*a->y;
    dist_b=b->x*b->x+b->y*b->y;

    if(dist_a==dist_b){
        return compare_val(a,b);
    }else{
        return dist_a-dist_b;
    }
}

int main(){
    point data1[]={
        {0,0},
        {1,0},
        {2,0},
        {0,1},
        {1,1},
        {2,1},
        {0,2},
        {1,2},
        {2,2},
    };
    point data2[]={
        {0,0},
        {1,0},
        {2,0},
        {0,1},
        {1,1},
        {2,1},
        {0,2},
        {1,2},
        {2,2},
    };
    qsort(data1, sizeof(data1)/sizeof(point), sizeof(point), (int (*)(const void*, const void*))compare_val);
    qsort(data2, sizeof(data2)/sizeof(point), sizeof(point), (int (*)(const void*, const void*))compare_dist);

    return 0;
}

Index

Feed

Other

Link

Pathtraq

loading...