-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy patheggdrop.c
executable file
·68 lines (63 loc) · 1.46 KB
/
eggdrop.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
57
58
59
60
61
62
63
64
65
66
67
68
#include <stdio.h>
#define FLOORS 2000
#define MAXUINT ~0
#define ulli unsigned long long int
int eric(int brkheight)
{
int tries = 0;
int lo = 0;
while (lo < (FLOORS - 1)) {
tries++; //"Trying" the egg drop.
lo += 2;
if (lo >= brkheight) break;
}
tries++; //Once more for checking the floor below.
return tries;
}
int gavin(int brkheight)
{
int tries = 0;
int lo = 0;
int hi = FLOORS - 1;
//Binary search part.
while (1) {
tries++; //"Trying" the egg drop.
int mid = ((lo + hi) / 2) + 1;
if (mid < brkheight) lo = mid;
else {
hi = mid;
break;
}
}
//Linear search part.
while (lo < brkheight) {
tries++;
lo++;
}
return tries;
}
int main()
{
int i;
int ewins = 0; //Eric wins tally.
int gwins = 0; //Gavin wins tally.
int draws = 0; //Number of draws.
ulli etotal = 0;
ulli gtotal = 0;
//Run the experiment.
//It's run once for every floor height the egg could begin breaking at.
for (i = 0; i < FLOORS; i++) {
int etmp = eric(i);
int gtmp = gavin(i);
if (etmp < gtmp) ewins++;
if (etmp > gtmp) gwins++;
if (etmp == gtmp) draws++;
etotal += etmp;
gtotal += gtmp;
if (((MAXUINT - etotal) < (ulli)etmp) || (MAXUINT - gtotal < (ulli)gtmp))
printf("Warning, overflow!\n");
}
printf("Eric won %i times, Gavin won %i times, and there was a draw %i times.\n", ewins, gwins, draws);
printf("For %i floors: Eric's average was %f, Gavin's average was %f.\n", FLOORS, etotal/(float)FLOORS, gtotal/(float)FLOORS);
return 0;
}