aboutsummaryrefslogtreecommitdiff
path: root/priority_queue.c
blob: 79377c358cdd6ec304effdda5afa0662d77c00f5 (plain) (blame)
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
#include <stdio.h>
#include <curses.h>
#include "priority_queue.h"
#include "error.h"

PositionPQ *ppq_new(Position pos, size_t priority) {
    PositionPQ *ppq = malloc(sizeof(PositionPQ));
    ppq->pos = pos;
    ppq->priority = priority;
    ppq->prev = NULL;
    ppq->next = NULL;
    return ppq;
}

/* It works, but I don't trust it.
 * Left the `printf`s as they were when I was debugging this shit, I have a
 * feeling I'll need them later. */
void ppq_insert(PositionPQ *ppq, Position pos, size_t priority) {
    /* printf("Inserting %li %li with prio %li\n", pos.x, pos.y, priority); */
    while (ppq->next != NULL) {
        if (ppq->priority > priority) {
            printf(" inserting in middle\n");
            PositionPQ *n = ppq_new(pos, priority);
            n->prev = ppq->prev;
            n->next = ppq;
            if (ppq->prev != NULL) {
                ppq->prev->next = n;
            }
            ppq->prev = n;
            return;
        } else {
            ppq = ppq->next;
        }
    }

    /* Reached end node */

    if (priority > ppq->priority) { /* Insert after */
        /* printf(" reached end, inserting after\n"); */
        PositionPQ *n = ppq_new(pos, priority);
        n->prev = ppq;
        ppq->next = n;
        return;
    } else { /* Insert before */
        /* printf(" reached end, inserting before\n"); */
        PositionPQ *n = ppq_new(pos, priority);
        n->prev = ppq->prev;
        n->next = ppq;
        if (ppq->prev != NULL) {
            ppq->prev->next = n;
        }
        ppq->prev = n;
        return;
    }
}

Position ppq_pop(PositionPQ *ppq) {
    Position pos = ppq->pos;
    ppq->next->prev = NULL;
    PositionPQ *next = ppq->next;
    free(ppq);
    ppq = next;
    return pos;
}

void ppq_reprioritize(PositionPQ *ppq, Position pos, size_t priority) {
    (void)ppq, (void)pos, (void)priority;
    todo();
}

void ppq_print(PositionPQ *ppq) {
    int i = 0;
    while (ppq->next != NULL) {
        printf("%i - %li: %li, %li\n", i++, ppq->priority, ppq->pos.x, ppq->pos.y);
        ppq = ppq->next;
    }
    printf("%i - %li: %li, %li\n", i++, ppq->priority, ppq->pos.x, ppq->pos.y);
}