前回の応用問題の解答例

  1. 点が長方形の内部に含まれるか
    #include <stdio.h>
    
    struct point {
      double x;
      double y;
    };
    
    struct rect {
      struct point ul; /* 左上隅 */
      struct point lr; /* 右下隅 */
    };
    
    /* 点p1の右下に点p2がある時に限り, 真を返す */
    int is_lr(struct point p1, struct point p2){
      int result;
      if((p1.x <= p2.x) &&          /* p2 の方が右にあって */
         (p1.y >= p2.y)){           /* p2 の方が下にあるなら */
        result = 1;                 /* 真 */
      } else {                      /* そうでなければ */
        result = 0;                 /* 偽 */
      }
      return result;
    }
    
    /* 長方形rの内部に点pがあるなら, 真を返す */
    int includes(struct rect r, struct point p){
      int result;
      if(is_lr(r.ul, p) &&          /* 左上隅とpの関係 */
         is_lr(p, r.lr)){           /* pと右下隅の関係 */
        result = 1;                 /* 両方OKなら真 */
      } else {                      /* そうでなければ */
        result = 0;                 /* 偽 */
      }
      return result;
    }
    
    int main(void){
      struct rect r1 = {{1.0, 2.0}, {3.0, 1.0}};
      struct point p1 = {2.0, 1.5};
      struct point p2 = {4.0, 1.5};
    
      printf("for p1: %d\n", includes(r1, p1));
      printf("for p2: %d\n", includes(r1, p2));
    
      return 0;
    }
    
  2. 二つの線分が交点を持つか
    方針だけ, 授業時間に説明します. 数式の導出は以下の通り:


    #include <stdio.h>
    
    struct point {
      double x;
      double y;
    };
    
    struct line {
      struct point p1;
      struct point p2;
    };
    
    /* 二つの線分が交差する時, 真を返す */
    int intersects(struct line l1, struct line l2){
      int result;
      double a, b;
      double p;
      double x, y;
    
      p = (l1.p1.y-l1.p2.y)*(l2.p1.x-l2.p2.x) -
        (l1.p1.x-l1.p2.x)*(l2.p1.y-l2.p2.y);
        
      /* printf("p: %le\n", p); */
      if(p == 0.0){
        result = 0;
      } else {
        a = ((l2.p1.x-l2.p2.x)*(l2.p2.y-l1.p2.y) -
             (l2.p1.y-l2.p2.y)*(l2.p2.x-l1.p2.x)) / p;
        b = ((l1.p1.y-l1.p2.y)*(l1.p2.x-l2.p2.x) -
             (l1.p1.x-l1.p2.x)*(l1.p2.y-l2.p2.y)) / p;
        /* printf("a: %le b: %le\n", a, b); */
        if((0.0 <= a) && (a <= 1.0) &&
           (0.0 <= b) && (b <= 1.0)){
          result = 1;
        } else {
          result = 0;
        }
      }
      /* printf("\n"); */
      return result;
    }
    
    int main(void){
      struct line l1 = {{0.0, 1.0}, {1.0, 0.0}, };
      struct line l2 = {{0.0, 0.0}, {1.0, 1.0}};
      struct line l3 = {{0.0, 2.0}, {1.0, 2.0}};
      struct line l4 = {{0.0, 1.0}, {1.0, 2.0}};
      struct line l5 = {{1.0, 1.0}, {0.0, 1.0}, };
    
      printf("for l1, l2: %d\n", intersects(l1, l2));
      printf("for l1, l3: %d\n", intersects(l1, l3));
      printf("for l2, l4: %d\n", intersects(l2, l4));
      printf("for l2, l5: %d\n", intersects(l2, l5));
    
      return 0;
    }
    
    

[page 2] prev index next