forked from remzi-arpacidusseau/ostep-code
-
Notifications
You must be signed in to change notification settings - Fork 0
/
lottery.c
74 lines (62 loc) · 1.46 KB
/
lottery.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
69
70
71
72
73
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
// global ticket count
int gtickets = 0;
struct node_t {
int tickets;
struct node_t *next;
};
struct node_t *head = NULL;
void insert(int tickets) {
struct node_t *tmp = malloc(sizeof(struct node_t));
assert(tmp != NULL);
tmp->tickets = tickets;
tmp->next = head;
head = tmp;
gtickets += tickets;
}
void print_list() {
struct node_t *curr = head;
printf("List: ");
while (curr) {
printf("[%d] ", curr->tickets);
curr = curr->next;
}
printf("\n");
}
int
main(int argc, char *argv[])
{
if (argc != 3) {
fprintf(stderr, "usage: lottery <seed> <loops>\n");
exit(1);
}
int seed = atoi(argv[1]);
int loops = atoi(argv[2]);
srandom(seed);
// populate list with some number of jobs, each
// with some number of tickets
insert(50);
insert(100);
insert(25);
print_list();
int i;
for (i = 0; i < loops; i++) {
int counter = 0;
int winner = random() % gtickets; // get winner
struct node_t *current = head;
// loop until the sum of ticket values is > the winner
while (current) {
counter = counter + current->tickets;
if (counter > winner)
break; // found the winner
current = current->next;
}
// current is the winner: schedule it...
print_list();
printf("winner: %d %d\n\n", winner, current->tickets);
}
return 0;
}