[ create a new paste ] login | about

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

C, pasted on Apr 5:
#include <math.h>
#include <stdio.h>
#include <stdlib.h>

#define square(x) ((x) * (x))

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

double CalcDistance(Coordinate *A, Coordinate *B){
	return square(A->x - B->x) + square(A->y - B->y) + square(A->z - B->z);
}

int main(void){
	int n = 5;
	int i, j;
	Coordinate *Position;

	Position = (Coordinate *)malloc(sizeof(Coordinate) * n);
	if(Position == NULL){
		printf("メモリが確保できません\n");
		return 1;
	}

	srand((unsigned int)(time(NULL)));
	printf("[Coordinate]\n");
	for(i = 0; i < n; ++i){
		Position[i].x = (double)(rand()) / RAND_MAX;
		Position[i].y = (double)(rand()) / RAND_MAX;
		Position[i].z = (double)(rand()) / RAND_MAX;
		printf("%d (%f %f %f)\n", i + 1, Position[i].x, Position[i].y, Position[i].z);
	}

	printf("\n[Distance]\n");
	for(i = 0; i < n - 1; ++i){
		for(j = i + 1; j < n; ++j){
			printf("%d<->%d %f\n", i + 1, j + 1, CalcDistance(&Position[i], &Position[j]));
		}
	}

	return 0;
}


Output:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
[Coordinate]
1 (0.777498 0.957247 0.279725)
2 (0.177398 0.140311 0.027895)
3 (0.522958 0.741187 0.561143)
4 (0.658372 0.718426 0.803936)
5 (0.311698 0.589567 0.597151)

[Distance]
1<->2 1.090921
1<->3 0.190668
1<->4 0.346023
1<->5 0.452917
2<->3 0.764817
2<->4 1.167793
2<->5 0.543919
3<->4 0.077803
3<->5 0.068916
4<->5 0.179548


Create a new paste based on this one


Comments: