aboutsummaryrefslogtreecommitdiffstats
path: root/oving2.c
blob: f949609a172ba1a0932b4f076b6a9f48b9b67b73 (plain)
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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
/*
 * oving2.c
 * implements TDT4120 - AlgDat oving 2
 *
 * Erik Liodden
 */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "structure.h"
#include "io.h"

struct node {
	char c;
	int pos;
};

void free_q(void *qp)
{
	struct queue *q = (struct queue *)qp;
	queue_dispose(q);
}

int comp_q(const void *qp1, const void *qp2)
{
	struct queue *q1 = (struct queue *)qp1;
	struct queue *q2 = (struct queue *)qp2;
	return queue_length(q2) - queue_length(q1);
}

/* read_input: read from stdin to buffer */
void read_input(struct heap *h)
{
	struct queue q;
	struct node node;
	char *str, *token;
	size_t len, i;
	char **lines;

	heap_init(h, sizeof(struct queue), &free_q, &comp_q);
	lines = read_lines(&len, stdin);
	for (i = 0; i < len; i++) {
		if (strlen(*(lines + i)) < 4)
			continue;
		queue_init(&q, sizeof(struct node), NULL);
		node.c = **(lines + i);
		str = strdup(*(lines + i) + 2);
		token = strtok(str, ",");
		while(token != NULL) {
			node.pos = atoi(token);
			queue_enqueue(&q, &node);
			token = strtok(NULL, ",");
		}
		free(str);
		heap_max_heap_insert(h, &q);
	}
	dispose_read_lines(lines, len);
}

void merge(struct queue *q, struct queue *p1, struct queue *p2)
{
	struct node n1, n2;

	while(queue_length(p1) && queue_length(p2)) {
		queue_peek(p1, &n1);
		queue_peek(p2, &n2);
		if (n1.pos <= n2.pos) {
			queue_dequeue(p1, &n1);
			queue_enqueue(q, &n1);
		} else {
			queue_dequeue(p2, &n2);
			queue_enqueue(q, &n2);
		}
	}
	while(queue_length(p1)) {
		queue_dequeue(p1, &n1);
		queue_enqueue(q, &n1);
	}
	while(queue_length(p2)) {
		queue_dequeue(p2, &n2);
		queue_enqueue(q, &n2);
	}
}

void merge_lines(struct heap *h)
{
	struct queue q, p1, p2;

	while(heap_length(h) > 1) {
		queue_init(&q, sizeof(struct node), NULL);
		heap_extract_max(h, &p1);
		heap_extract_max(h, &p2);
		merge(&q, &p1, &p2);
		queue_dispose(&p1);
		queue_dispose(&p2);
		heap_max_heap_insert(h, &q);
	}
}

int main(void)
{
	struct heap h;
	struct queue q;
	struct node n;

	read_input(&h);
	merge_lines(&h);
	heap_extract_max(&h, &q);
	while(queue_length(&q)) {
		queue_dequeue(&q, &n);
		printf("%c", n.c);
	}
	printf("\n");
	queue_dispose(&q);
	heap_dispose(&h);
	return 0;
}