[ create a new paste ] login | about

Link: http://codepad.org/6xdG8O9n    [ raw code | output | fork ]

C, pasted on Mar 24:
#include <stdio.h>
#include <math.h>

typedef struct Position
{
  double x, y, z;
} Position;

typedef struct Triangle
{
  Position p1, p2, p3;
} Triangle;

double dist(Position* p1, Position* p2)
{
  return sqrt((p1->x - p2->x) * (p1->x - p2->x) + (p1->y - p2->y) * (p1->y - p2->y) + (p1->z - p2->z) * (p1->z - p2->z));
}

Position GetNearestPosition(Triangle* tri, Position* tgt)
{
  double ds1, ds2, ds3, nearest;

  ds1 = dist(&tri->p1, tgt);
  ds2 = dist(&tri->p2, tgt);
  ds3 = dist(&tri->p3, tgt);
  
  nearest = (ds1 < ds2) ? ds1 : ds2;
  nearest = (nearest < ds3) ? nearest : ds3;
  
  return (ds1 == nearest) ? tri->p1 : (ds2 == nearest) ? tri->p2 : tri->p3;
}

int main(void)
{
  Triangle tr = {{0.0, 1.0, 1.0}, {2.0, 3.0, 4.0}, {4.0, 1.5, 3.0}};
  Position ps = {0.2, 0.3, 0.4};

  Position nearest = GetNearestPosition(&tr, &ps);

  printf("(%f, %f, %f)に最も近い座標は(%f, %f, %f)\n", ps.x, ps.y, ps.z, nearest.x, nearest.y, nearest.z);
  
  return 0;
}


Output:
1
(0.200000, 0.300000, 0.400000)に最も近い座標は(0.000000, 1.000000, 1.000000)


Create a new paste based on this one


Comments: