File: math.c

package info (click to toggle)
empire 1.14-2
  • links: PTS, VCS
  • area: main
  • in suites: buster
  • size: 456 kB
  • sloc: ansic: 5,317; xml: 1,010; makefile: 112
file content (95 lines) | stat: -rw-r--r-- 1,953 bytes parent folder | download | duplicates (5)
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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
/*
 *    Copyright (C) 1987, 1988 Chuck Simmons
 * 
 * See the file COPYING, distributed with empire, for restriction
 * and warranty information.
 */

/*
math.c -- various mathematical routines.

This file contains routines used to create random integers.  The
initialization routine 'rndini' should be called at program startup.
The flavors of random integers that can be generated are:

    irand(n) -- returns a random integer in the range 0..n-1
    rndint(a,b) -- returns a random integer in the range a..b

Other routines include:

    dist (a, b) -- returns the straight-line distance between two locations.
*/

#include <stdlib.h>
#include <time.h>
#include "empire.h"
#include "extern.h"

void rndini(void)
{
	srand((unsigned)(time(0) & 0xFFFF));
}

long irand(long high)
{
	if (high < 2) {
		return (0);
	}
	return (rand() % high);
}

#ifdef __UNUSED__
int rndint(int minp, int maxp)
{
	int size;

	size = maxp - minp + 1;
	return ((rand() % size) + minp);
}
#endif

/*
Return the distance between two locations.  This is simply
the max of the absolute differnce between the x and y coordinates.
*/

#define MIN(a,b) ((a)<(b) ? (a) : (b))
#define MAX(a,b) ((a)>(b) ? (a) : (b))
#define ABS(a) ((a) < 0 ? -(a) : (a))

int
dist(loc_t a, loc_t b)
{
	int ax, ay, bx, by;

	ax = loc_row (a);
	ay = loc_col (a);
	bx = loc_row (b);
	by = loc_col (b);

	return (MAX (ABS (ax-bx), ABS (ay-by)));
}

/*
Find the square root of an integer.  We actually return the floor
of the square root using Newton's method.
*/

int isqrt(int n)
{
	int guess;
	
	ASSERT (n >= 0); /* can't take sqrt of negative number */

	if (n <= 1) return (n); /* do easy cases and avoid div by zero */
		
	guess = 2; /* gotta start somewhere */
	guess = (guess + n/guess) / 2;
	guess = (guess + n/guess) / 2;
	guess = (guess + n/guess) / 2;
	guess = (guess + n/guess) / 2;
	guess = (guess + n/guess) / 2;
	
	if (guess * guess > n) guess -= 1; /* take floor */
	return (guess);
}