Add license
[knight_shuffling_tower.git] / tower.c
blobae46c34ff3e5685238a8d4bc2b207e214bd94dd7
1 #include <stdlib.h>
2 #include <stdio.h>
4 #include "ast.h"
5 #include "tower.h"
7 struct fifo_node;
8 typedef struct fifo_node {
9 DATA *data;
10 struct fifo_node *prev;
11 } fifo_node;
13 static fifo_node *tower_entrance = NULL;
14 static fifo_node *tower_exit = NULL;
16 struct ast *const_true;
17 struct ast *const_false;
18 DATA knights[KNIGHT_NUM + 1];
20 void tower_push(DATA * d)
22 fifo_node *new_node;
24 if (!tower_entrance) {
25 tower_entrance = malloc(sizeof (fifo_node));
26 if (!tower_entrance) {
27 fprintf(stderr, "Fatal: Could not allocate memory for tower\n");
28 exit(-1);
31 tower_exit = tower_entrance;
32 tower_entrance->data = d;
33 tower_entrance->prev = NULL;
34 } else {
35 new_node = malloc(sizeof (fifo_node));
36 if (!new_node) {
37 fprintf(stderr, "Fatal: Could not allocate memory for tower\n");
38 exit(-1);
41 new_node->data = d;
42 new_node->prev = NULL;
43 tower_entrance->prev = new_node;
44 tower_entrance = new_node;
48 DATA *tower_pop()
50 DATA *to_return = NULL;
51 fifo_node *to_delete;
53 if (!tower_exit)
54 exit(0);
56 to_return = tower_exit->data;
58 if (tower_entrance == tower_exit) {
59 free(tower_exit);
60 tower_entrance = NULL;
61 tower_exit = NULL;
62 } else {
63 to_delete = tower_exit;
64 tower_exit = tower_exit->prev;
65 free(to_delete);
68 return to_return;
71 void shuffle()
73 int idx, tidx;
74 DATA t;
76 for (idx = 1; idx <= KNIGHT_NUM; ++idx) {
77 tidx = 1 + rand() % KNIGHT_NUM;
78 t = knights[tidx];
79 knights[tidx] = knights[idx];
80 knights[idx] = t;
84 void tower_initialize()
86 int i;
88 const_true = malloc(sizeof (ast));
89 const_true->type = A_VAR;
90 const_true->adata.avar = malloc(sizeof (ast_var));
91 const_true->adata.avar->type = COMPUTED_VAL;
92 const_true->adata.avar->val.computed_val.type = KBOOL;
93 const_true->adata.avar->val.computed_val.val = 1;
95 const_false = malloc(sizeof (ast));
96 const_false->type = A_VAR;
97 const_false->adata.avar = malloc(sizeof (ast_var));
98 const_false->adata.avar->type = COMPUTED_VAL;
99 const_false->adata.avar->val.computed_val.type = KBOOL;
100 const_false->adata.avar->val.computed_val.val = 0;
102 for (i = 1; i <= 9; ++i) {
103 knights[i].type = KINT;
104 knights[i].val = i;
106 shuffle();