aboutsummaryrefslogtreecommitdiff
path: root/week05/Exercise5.cpp
blob: 81175037bd2878443b6968022b08ef84af6030d7 (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
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
#include <cstring>

struct Checklist {
private:
	bool checked;
	char* contents;

	Checklist* subchecklists;
	unsigned allocated;
	unsigned size;

	void resize() {
		allocated *= 2;
		Checklist* biggerSubs = new Checklist[allocated];
		for (int i = 0; i < size; i++) {
			biggerSubs[i] = subchecklists[i];
		}
		delete[] subchecklists;
		subchecklists = biggerSubs;
	}

	void free() {
		delete[] contents;
		delete[] subchecklists;
	}
	void copyFrom(const Checklist& other) {
		this->checked = other.checked;

		unsigned contSize = strlen(other.contents);
		this->contents = new char[contSize+1];
		strcpy(this->contents, other.contents);

		this->allocated = other.allocated;
		this->size = other.size;
		this->subchecklists = new Checklist[allocated];
		for (int i = 0; i < size; i++) {
			this->subchecklists[i] = other.subchecklists[i];
		}
	}

public:
	Checklist(const char* contents) {
		checked = false;

		unsigned contSize = strlen(contents);
		this->contents = new char[contSize+1];
		strcpy(this->contents, contents);

		this->allocated = 2;
		this->size = 0;
		this->subchecklists = new Checklist[allocated];
	}

	Checklist() {
		checked = false;
		contents = nullptr;
		subchecklists = nullptr;
		allocated = size = 0;
	}
	~Checklist() {
		free();
	}
	Checklist(const Checklist& other) {
		copyFrom(other);
	}
	Checklist& operator=(const Checklist& other) {
		if (this != &other) {
			free();
			copyFrom(other);
		}
		return *this;
	}

	void AddChecklist(const Checklist& newChecklist) {
		if (allocated == size) {
			resize();
		}
		subchecklists[size++] = newChecklist;
	}
	void RemoveChecklist(unsigned index) {
		if (index >= size) return;

		size--;
		for (int i = index; i < size; i++) {
			subchecklists[i] = subchecklists[i+1];
		}
	}

	void SwapRight(unsigned index) {
		if (index >= size-1) return;

		Checklist temp = subchecklists[index];
		subchecklists[index] = subchecklists[index+1];
		subchecklists[index+1] = temp;
	}
	void SwapLeft(unsigned index) {
		if (index == 0 || index >= size) return;

		Checklist temp = subchecklists[index];
		subchecklists[index] = subchecklists[index-1];
		subchecklists[index-1] = temp;
	}
};