├── 9024 Course Outline.pdf ├── Algorithms └── DP │ ├── BackPack │ ├── Readme.txt │ ├── Set.py │ ├── TopToBottomRem.py │ └── TwoDimensionArray.py │ ├── K SUM │ ├── LsSol.py │ └── Readme.txt │ ├── LIS │ ├── Readme.txt │ ├── dictSol.py │ ├── listSol.py │ └── listSolAdv.py │ └── distinct subsequences │ ├── LsDp.py │ └── Readme.txt ├── Assignment ├── 9024_assignment2.pdf └── asst-1 │ ├── 9024_assignment1.pdf │ ├── Makefile │ ├── assignment1.txt │ ├── autotest │ ├── listIteratorInt.c │ ├── listIteratorInt.h │ ├── testListIteratorInt.c │ └── tests │ ├── 1.exp │ ├── 2.exp │ └── 3.exp ├── Final exam ├── .vscode │ └── settings.json ├── Final-sample.pdf ├── Q1 │ ├── BSTree.c │ ├── BSTree.h │ ├── Q1.c │ └── Q1.pdf └── Q2 │ ├── Graph.c │ ├── Graph.h │ ├── Q2.c │ └── Q2.pdf ├── Mid exam └── sample-midterm.zip ├── Problem Set ├── Week 01a │ ├── 1.c │ ├── 2a.c │ ├── 2b.c │ ├── 3.c │ ├── 5.c │ ├── 6.c │ ├── COMP9024 19T0 - Week 01a Problem Set.html │ └── fibonacci.c ├── Week 01b │ ├── 1.c │ ├── 2.c │ ├── 2b.c │ ├── 3.c │ ├── 4.c │ ├── 5.c │ ├── 6.c │ ├── Queue.h │ └── Stack.h ├── Week 02a │ ├── 1.c │ ├── 2.c │ ├── 3.c │ ├── 4.c │ ├── 6.c │ ├── 6.h │ └── llbuild.c ├── week3a │ ├── 1.txt │ ├── 2.c │ ├── 4.txt │ └── 5.c ├── week4 │ ├── .vscode │ │ └── settings.json │ ├── 1.doc │ ├── 2.doc │ ├── 3.doc │ ├── 4a.c │ ├── 4b.doc │ ├── Graph.c │ ├── Graph.h │ ├── Problem set 4.pdf │ ├── stack.c │ └── stack.h ├── week5 │ ├── 1.doc │ ├── 2.doc │ ├── 3.doc │ ├── 5.doc │ └── Problem set 5.pdf ├── week6a │ ├── 1a.doc │ ├── 1b.c │ ├── 2.doc │ ├── 3.doc │ ├── 4.doc │ ├── 5.doc │ ├── BSTree.c │ ├── BSTree.h │ └── week6a.pdf ├── week6b │ ├── 1.c │ ├── 2.doc │ ├── 3.doc │ ├── 4.doc │ ├── 5.c │ ├── BSTree.c │ └── BSTree.h └── week7 │ ├── 3.doc │ ├── 4.doc │ ├── 5.doc │ ├── 6.doc │ ├── 7.doc │ └── Problem set 7.pdf ├── README.md └── References ├── Cref.pdf └── 排序算法.jpg /9024 Course Outline.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/brmuch/COMP9024/094852af15dca9d5d9fa34d492a4415a476d812e/9024 Course Outline.pdf -------------------------------------------------------------------------------- /Algorithms/DP/BackPack/Readme.txt: -------------------------------------------------------------------------------- 1 | LintCode # 92 BackPack problem 2 | 3 | ViolentSol 22% pass 4 | TopToBottomRem 44% pass 5 | TwoDimensionArray 78% pass 6 | Set 100% pass 7 | -------------------------------------------------------------------------------- /Algorithms/DP/BackPack/Set.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | """ 3 | @param m: An integer m denotes the size of a backpack 4 | @param A: Given n items with size A[i] 5 | @return: The maximum size 6 | """ 7 | def backPack(self, m, A): 8 | # write your code here 9 | if sum(A) <= m: 10 | return sum(A) 11 | 12 | possibleVLS = {0} 13 | for item in A: 14 | temp = list(possibleVLS) 15 | temp.extend([i + item for i in temp if i + item <= m]) 16 | 17 | if m in possibleVLS: 18 | return m 19 | possibleVLS = set(temp) 20 | 21 | return max(possibleVLS) 22 | -------------------------------------------------------------------------------- /Algorithms/DP/BackPack/TopToBottomRem.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | """ 3 | @param m: An integer m denotes the size of a backpack 4 | @param A: Given n items with size A[i] 5 | @return: The maximum size 6 | """ 7 | def backPack(self, m, A): 8 | # write your code here 9 | dicts = dict() 10 | 11 | return self.TopToBottomDP(m, A, dicts) 12 | 13 | 14 | def TopToBottomDP(self, m, A, dicts): 15 | if len(A) == 0 or m < min(A): 16 | return 0 17 | 18 | maxSize, resSize = 0, 0 19 | for item in A: 20 | if item < m: 21 | B = list(A) 22 | B.remove(item) 23 | 24 | if tuple(B) not in dicts.keys(): 25 | resSize = self.TopToBottomDP(m - item, B, dicts) 26 | else: 27 | resSize = dicts[tuple(B)] 28 | 29 | maxSize = resSize + item if resSize + item > maxSize else maxSize 30 | 31 | dicts[tuple(A)] = maxSize 32 | 33 | return maxSize 34 | 35 | 36 | -------------------------------------------------------------------------------- /Algorithms/DP/BackPack/TwoDimensionArray.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | """ 3 | @param m: An integer m denotes the size of a backpack 4 | @param A: Given n items with size A[i] 5 | @return: The maximum size 6 | """ 7 | def backPack(self, m, A): 8 | # write your code here 9 | wholeLs = [False] * sum(A) 10 | wholeLs.insert(0, True) 11 | 12 | if sum(A) <= m: 13 | return sum(A) 14 | 15 | for item in A: 16 | for j in range(item, sum(A) + 1)[::-1]: 17 | if wholeLs[j - item]: 18 | wholeLs[j] = True 19 | 20 | res = wholeLs[:m +1] 21 | return m - res[::-1].index(True) -------------------------------------------------------------------------------- /Algorithms/DP/K SUM/LsSol.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | """ 3 | @param A: An integer array 4 | @param k: A positive integer (k <= length(A)) 5 | @param target: An integer 6 | @return: An integer 7 | """ 8 | def kSum(self, A, k, target): 9 | # write your code here 10 | numDict, A = [None] * (target + 1), [i for i in A if i <= target] 11 | 12 | for a in A: 13 | for i in range(a, target + 1)[::-1]: 14 | if numDict[i] != None and numDict[i - a] != None: 15 | numDict[i].extend([n + 1 for n in numDict[i - a] if n <= k - 1]) 16 | elif numDict[i] == None and numDict[i - a] != None: 17 | numDict[i] = [n + 1 for n in numDict[i - a] if n <= k - 1] 18 | if numDict[a] == None: 19 | numDict[a] = [1] 20 | else: 21 | numDict[a].append(1) 22 | return len([i for i in numDict[target] if i == k]) -------------------------------------------------------------------------------- /Algorithms/DP/K SUM/Readme.txt: -------------------------------------------------------------------------------- 1 | LintCode # 89 K SUM 2 | LsSol.py O(n^2) O(target * K) 73% pass memory Limit Exceeded -------------------------------------------------------------------------------- /Algorithms/DP/LIS/Readme.txt: -------------------------------------------------------------------------------- 1 | LintCode # 76 longest increasing subsequence (LIS) 2 | listSol O(n!) 1124 ms 75% pass 3 | dictSol O(nlogn) 64 ms 100% pass 4 | ListSolAdv O(nlogn) 56 ms 100% pass -------------------------------------------------------------------------------- /Algorithms/DP/LIS/dictSol.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | """ 3 | @param nums: An integer array 4 | @return: The length of LIS (longest increasing subsequence) 5 | """ 6 | def longestIncreasingSubsequence(self, nums): 7 | # write your code here 8 | seqDict = dict(zip(range(1, len(nums)), [None for i in range(1, len(nums))])) 9 | 10 | for num in nums: 11 | ls = list([j for j in seqDict.values() if j != None]) 12 | 13 | if len(ls) == 0: 14 | seqDict[1] = num 15 | continue 16 | elif ls[-1] < num: 17 | seqDict[len(ls) + 1] = num 18 | continue 19 | 20 | for i in range(len(ls)): 21 | if ls[i] > num: 22 | seqDict[i + 1] = num 23 | break 24 | 25 | return len([j for j in seqDict.values() if j != None]) -------------------------------------------------------------------------------- /Algorithms/DP/LIS/listSol.py: -------------------------------------------------------------------------------- 1 | from itertools import product 2 | class Solution: 3 | """ 4 | @param nums: An integer array 5 | @return: The length of LIS (longest increasing subsequence) 6 | """ 7 | def longestIncreasingSubsequence(self, nums): 8 | # write your code here 9 | seqLs = [] 10 | 11 | for num in nums: 12 | for ls in seqLs: 13 | if num > ls[-1]: 14 | temp = list(ls) 15 | temp.append(num) 16 | seqLs.append(temp) 17 | seqLs.append([num]) 18 | 19 | 20 | return max([len(i) for i in seqLs]) if len(seqLs) != 0 else 0 -------------------------------------------------------------------------------- /Algorithms/DP/LIS/listSolAdv.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | """ 3 | @param nums: An integer array 4 | @return: The length of LIS (longest increasing subsequence) 5 | """ 6 | def longestIncreasingSubsequence(self, nums): 7 | # write your code here 8 | seqLs = [] 9 | 10 | for num in nums: 11 | if len(seqLs) == 0 or seqLs[-1] < num: 12 | seqLs.append(num) 13 | continue 14 | 15 | for i in range(len(seqLs)): 16 | if seqLs[i] > num: 17 | seqLs[i] = num 18 | break 19 | 20 | return len(seqLs) -------------------------------------------------------------------------------- /Algorithms/DP/distinct subsequences/LsDp.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | """ 3 | @param S: A string 4 | @param T: A string 5 | @return: Count the number of distinct subsequences 6 | """ 7 | def numDistinct(self, S, T): 8 | # write your code here 9 | if T == None or len(T) == 0: 10 | return 1 11 | 12 | subsequenceLs = [0] * (len(T)) 13 | 14 | for c in S: 15 | for seq in range(0, len(subsequenceLs) - 1)[::-1]: 16 | if subsequenceLs[seq] > 0 and c == T[seq + 1]: 17 | subsequenceLs[seq + 1] += subsequenceLs[seq] 18 | if c == T[0]: 19 | subsequenceLs[0] += 1 20 | 21 | return subsequenceLs[-1] -------------------------------------------------------------------------------- /Algorithms/DP/distinct subsequences/Readme.txt: -------------------------------------------------------------------------------- 1 | LintCode #118 distinct subsequences 2 | LsDp O(n^2) 101ms 100% pass -------------------------------------------------------------------------------- /Assignment/9024_assignment2.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/brmuch/COMP9024/094852af15dca9d5d9fa34d492a4415a476d812e/Assignment/9024_assignment2.pdf -------------------------------------------------------------------------------- /Assignment/asst-1/9024_assignment1.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/brmuch/COMP9024/094852af15dca9d5d9fa34d492a4415a476d812e/Assignment/asst-1/9024_assignment1.pdf -------------------------------------------------------------------------------- /Assignment/asst-1/Makefile: -------------------------------------------------------------------------------- 1 | # Makefile for listIteratorInt 2 | 3 | CC = gcc 4 | CFLAGS = -Wall -Werror -g 5 | 6 | all : testListIterInt 7 | 8 | testListIterInt : listIteratorInt.o testListIteratorInt.o 9 | $(CC) -o testListIterInt listIteratorInt.o testListIteratorInt.o 10 | 11 | testListIteratorInt.o: testListIteratorInt.c listIteratorInt.h 12 | $(CC) $(CFLAGS) -c testListIteratorInt.c 13 | 14 | listIteratorInt.o : listIteratorInt.c listIteratorInt.h 15 | $(CC) $(CFLAGS) -c listIteratorInt.c 16 | 17 | clean : 18 | rm -f *.o testListIterInt core 19 | 20 | -------------------------------------------------------------------------------- /Assignment/asst-1/assignment1.txt: -------------------------------------------------------------------------------- 1 | COMP9024 Assigment1 2 | 3 | Aim of Iterator: 4 | 1.traverse the list in either direction 5 | 2.modify the list during iteration 6 | 3.obtain the iterator's current position in the list -------------------------------------------------------------------------------- /Assignment/asst-1/autotest: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | QNAME="listIteratorInt" 4 | BIN="testListIterInt" 5 | 6 | echo "*** Testing $QNAME ***" 7 | 8 | if [ ! -f "$BIN" ] 9 | then 10 | echo "No such executable: $BIN" 11 | exit 1 12 | fi 13 | 14 | if [ ! -x "$BIN" ] 15 | then 16 | echo "$BIN is not executable" 17 | exit 1 18 | fi 19 | 20 | if [ ! -d tests ] 21 | then 22 | echo "No tests/ directory here. Are you in the right directory?" 23 | exit 1 24 | fi 25 | 26 | 27 | if [ "$#" -eq 0 ] 28 | then 29 | tsts="1 2 3" 30 | elif [ "$#" -eq 1 ] 31 | then 32 | tsts="$1" 33 | else 34 | echo "Usage-1: autotest " 35 | echo "Usage-2: autotest " 36 | exit 1 37 | fi 38 | 39 | for t in $tsts 40 | do 41 | 42 | ./testListIterInt $t | head -500 > tests/$t.out 43 | echo " " 44 | echo " " 45 | echo "------------------------------ " 46 | if cmp -s tests/$t.exp tests/$t.out 47 | then 48 | echo "** Passed Test $t" 49 | else 50 | echo "** Failed Test $t" 51 | echo "> Your output (in tests/$t.out): " 52 | cat tests/$t.out 53 | echo " " 54 | echo " " 55 | echo "> #### Expected output (in tests/$t.exp): " 56 | cat tests/$t.exp 57 | echo "> Compare files tests/$t.exp and tests/$t.out to see differences" 58 | 59 | fi 60 | echo "------------------------------ " 61 | done 62 | 63 | echo " " 64 | 65 | 66 | 67 | 68 | -------------------------------------------------------------------------------- /Assignment/asst-1/listIteratorInt.c: -------------------------------------------------------------------------------- 1 | /* 2 | listIteratorInt.c : list Iterator ADT implementation 3 | Written by Ran Bai 4 | Date: December 2018 5 | */ 6 | 7 | #include 8 | #include 9 | #include 10 | #include "listIteratorInt.h" 11 | 12 | // data structures representing DLList 13 | // one of do_next and do_prev can be 1, when they equal -1, means that dont do prev or next 14 | static int do_next = -1; // determine whether do next function 15 | static int do_prev = -1; // determine whether do prev function 16 | 17 | typedef struct Node { 18 | struct Node *next; // pointer to next node in list 19 | struct Node *prev; // pointer previous node in list 20 | int data; // value of this list item (int) 21 | } Node; 22 | 23 | typedef struct IteratorIntRep { 24 | int count; // count of items in list 25 | int origin; // 1 is cursor in the first place, 0 is not, -1 is undefinable. 26 | Node *first; // first node in list 27 | Node *last; // last node in list 28 | Node *cursor; // cursor node in list, assume cursor is point to the position after the cursor node when origin is 0 29 | } IteratorIntRep; 30 | 31 | /* 32 | 33 | Your local functions here, if any.... 34 | 35 | 36 | */ 37 | 38 | // Function: set flag bit to given value 39 | void set_flag(int prev_val, int next_val){ 40 | do_prev = prev_val; 41 | do_next = next_val; 42 | } 43 | 44 | 45 | // Function: Creates a new list iterator that can store integer values. 46 | IteratorInt IteratorIntNew(){ 47 | IteratorIntRep *new; 48 | new = malloc(sizeof(IteratorIntRep)); 49 | assert(new != NULL); // memory must be allocated sucessfully 50 | 51 | new->count = 0; // Initial attributes of Iterator 52 | new->origin = -1; 53 | new->first = NULL; 54 | new->last = NULL; 55 | new->cursor = NULL; 56 | set_flag(-1, -1); 57 | 58 | return new; 59 | } 60 | 61 | 62 | // Function: Resets cursor to the start of the list. 63 | void reset(IteratorInt it){ 64 | assert(it->cursor != NULL); 65 | it->cursor = it->first; 66 | it->origin = 1; 67 | 68 | set_flag(-1, -1); 69 | } 70 | 71 | 72 | // Function: Inserts the specified value v into the list iterator it. 73 | // Returns 1 if successful, 0 otherwise. 74 | int add(IteratorInt it, int v){ 75 | 76 | Node * new_node = malloc(sizeof(Node)); 77 | if (new_node == NULL) 78 | return 0; // failed malloc memory 79 | 80 | new_node->data = v; 81 | if (it->first == NULL){ // case1: no node exist in Doubly-linked-list 82 | new_node->prev = NULL; 83 | new_node->next = NULL; 84 | 85 | it->first = new_node; 86 | it->last = new_node; 87 | it->cursor = new_node; 88 | it->origin = 0; 89 | } 90 | else if (it->origin == 1){ // case2: add node in the first place 91 | new_node->prev = NULL; 92 | new_node->next = it->first; 93 | 94 | it->first = new_node; 95 | it->cursor = new_node; 96 | it->origin = 0; 97 | } 98 | else if (it->cursor == it->last){ // case3: add node in the last place 99 | new_node->prev = it->cursor; 100 | new_node->next = NULL; 101 | 102 | it->last = new_node; 103 | it->cursor->next = new_node; 104 | it->cursor = new_node; 105 | } 106 | else{ // case4: add node in the middle place 107 | new_node->prev = it->cursor; 108 | new_node->next = it->cursor->next; 109 | 110 | it->cursor->next->prev = new_node; 111 | it->cursor->next = new_node; 112 | it->cursor = new_node; 113 | } 114 | 115 | set_flag(-1, -1); 116 | it->count ++; 117 | return 1; // successful 118 | } 119 | 120 | 121 | // Function: determine whether has next node 122 | // Returns 1 if the given list iterator has more elements when traversing 123 | // the list in the forward direction, returns 0 otherwise. 124 | int hasNext(IteratorInt it){ 125 | return (it->first == NULL || (it->cursor == it->last && it->origin == 0))?0:1; 126 | } 127 | 128 | 129 | // Function: determine whether has previous node 130 | // Returns 1 if the given list iterator has more elements when traversing 131 | // the list in the reverse direction, returns 0 otherwise. 132 | int hasPrevious(IteratorInt it){ 133 | return (it->first == NULL || (it->cursor == it->first && it->origin == 1))?0:1; 134 | } 135 | 136 | 137 | // Function: Returns the pointer to the next value in the given list iterator and advances the cursor position. 138 | // The method returns NULL if it has no next value. 139 | int *next(IteratorInt it){ 140 | int *p; 141 | 142 | // return NULl when cursor point to the end or Doubly-lined-list dont have nodes 143 | if (it->first == NULL || (it->cursor == it->last && it->origin == 0)){ 144 | set_flag(-1, -1); 145 | return NULL; 146 | } 147 | else if (it->cursor == it->first && it->origin == 1){ 148 | it->origin = 0; 149 | p = &(it->cursor->data); 150 | } 151 | else{ 152 | it->cursor = it->cursor->next; 153 | p = &(it->cursor->data); 154 | } 155 | 156 | set_flag(0, 1); // sign do next operation already 157 | return p; 158 | } 159 | 160 | 161 | // Function: Returns the pointer to the previous value in the given list iterator and moves the cursor position backwards. 162 | // The method returns NULL if it has no previous value. 163 | int *previous(IteratorInt it){ 164 | int *p; 165 | 166 | if (it->first == NULL || (it->cursor == it->first && it->origin == 1)){ 167 | set_flag(-1, -1); 168 | return NULL; 169 | } 170 | else if (it->cursor == it->first && it->origin == 0){ 171 | p = &(it->cursor->data); 172 | it->origin =1; 173 | } 174 | else{ 175 | p = &(it->cursor->data); 176 | it->cursor = it->cursor->prev; 177 | } 178 | 179 | set_flag(1, 0); 180 | return p; 181 | } 182 | 183 | 184 | // Function: Deletes from the list iterator the last value that was returned by next or previous or findNext or findPrevious. 185 | // Returns 1 if successful, 0 otherwise (for example, invalid deleteElm call). 186 | int deleteElm(IteratorInt it){ 187 | if (it->first == NULL){ // no node in the Doubly-lined list 188 | set_flag(-1, -1); 189 | return 0; 190 | } 191 | 192 | if (do_next == 0 && do_prev == 1){ // do prev or findorev before 193 | 194 | if ((it->cursor == it->last && it->count > 1) || (it->count == 1 && it->origin == 0)){ // it cant point to the last node after do prev operation 195 | set_flag(-1, -1); 196 | return 0; 197 | } 198 | 199 | if (it->cursor == it->first && it->origin == 1){ // delete the first node 200 | if (it->count == 1){ // Doubly-linked list only have one node 201 | it->first = NULL; 202 | it->last = NULL; 203 | free(it->cursor); 204 | it->cursor = NULL; 205 | it->origin = -1; 206 | } 207 | else{ // Doubly-linked list have more than one node 208 | it->first = it->cursor->next; 209 | Node *temp = it->cursor; 210 | it->cursor = it->cursor->next; 211 | it->cursor->prev = NULL; 212 | free(temp); 213 | } 214 | } 215 | else if (it->cursor->next == it->last){ // delete node in the last place 216 | Node *temp = it->last; 217 | it->last = it->cursor; 218 | it->cursor->next = NULL; 219 | free(temp); 220 | } 221 | else{ // delete node in the middle place 222 | Node *temp = it->cursor->next; 223 | temp->next->prev = it->cursor; 224 | it->cursor->next = temp->next; 225 | free(temp); 226 | } 227 | 228 | } 229 | else if (do_next == 1 && do_prev == 0){ // do next or findnext before 230 | if (it->origin == 1){ // it cant point to the first place after do next operation 231 | set_flag(-1, -1); 232 | return 0; 233 | } 234 | 235 | if (it->count == 1){ // Doubly-linked list only have one node 236 | it->first = NULL; 237 | it->last = NULL; 238 | free(it->cursor); 239 | it->cursor = NULL; 240 | it->origin = -1; 241 | } 242 | else if (it->cursor == it->first){ // node in the first place 243 | Node *temp = it->cursor; 244 | it->cursor = it->cursor->next; 245 | it->first = it->cursor; 246 | it->cursor->prev = NULL; 247 | it->origin = 1; 248 | free(temp); 249 | } 250 | else if (it->cursor == it->last){ // node in the last place 251 | Node *temp = it->cursor; 252 | it->cursor = it->cursor->prev; 253 | it->last = it->cursor; 254 | it->cursor->next = NULL; 255 | free(temp); 256 | } 257 | else{ // node in the middel place 258 | Node *temp = it->cursor; 259 | it->cursor = it->cursor->prev; 260 | it->cursor->next = temp->next; 261 | temp->next->prev = it->cursor; 262 | free(temp); 263 | } 264 | } 265 | else{ 266 | set_flag(-1, -1); 267 | return 0; 268 | } 269 | 270 | set_flag(-1, -1); // clear flag 271 | it->count --; 272 | return 1; 273 | } 274 | 275 | 276 | // Function: Replaces the last element returned by next or previous or findNext or findPrevious with the specified element (v). 277 | // Returns 1 if successful, 0 otherwise (for example, invalid set call). 278 | int set(IteratorInt it, int v){ 279 | 280 | if (it->first == NULL){ // Doubly-linked list dont have any node 281 | set_flag(-1, -1); 282 | return 0; 283 | } 284 | 285 | if (do_next == 0 && do_prev == 1){ // do previous operation before 286 | if (it->cursor == it->first && it->origin == 1){ 287 | it->cursor->data = v; 288 | } 289 | else{ 290 | it->cursor->next->data = v; 291 | } 292 | } 293 | else if (do_next == 1 && do_prev == 0){ // do next operation before 294 | it->cursor->data = v; 295 | } 296 | else{ 297 | set_flag(-1, -1); // invalid operation 298 | return 0; 299 | } 300 | 301 | set_flag(-1, -1); // clear flag 302 | return 1; 303 | } 304 | 305 | 306 | // Function: Returns pointer to the next value in it that matches the given value v and advances the cursor position past the value returned. 307 | // The method returns NULL if there is no such next value and the cursor is not moved from the current position. 308 | int *findNext(IteratorInt it, int v){ 309 | 310 | if (it->first == NULL){ // Doubly-linked list dont have any node 311 | set_flag(-1, -1); 312 | return NULL; 313 | } 314 | 315 | int *p; 316 | 317 | if (it->cursor == it->last && it->origin == 0){ // finish when cursor in the last place 318 | set_flag(-1, -1); 319 | return NULL; 320 | } 321 | else{ 322 | Node * current; 323 | 324 | // determine which node is the first one we should start searching 325 | if (it->origin == 1 && it->cursor == it->first) 326 | current = it->cursor; 327 | else 328 | current = it->cursor->next; 329 | 330 | // searching... 331 | while (current != NULL && current->data != v){ 332 | current = current->next; 333 | } 334 | 335 | if (current != NULL){ // find the node has value same to v 336 | it->origin = 0; 337 | it->cursor = current; 338 | p = &(it->cursor->data); 339 | set_flag(0, 1); 340 | return p; 341 | } 342 | else{ // can't find corresponding node 343 | set_flag(-1, -1); 344 | return NULL; 345 | } 346 | 347 | } 348 | } 349 | 350 | 351 | // Function: Returns pointer to the previous value in it that matches the given value v and moves the cursor position backwards before the value returned. 352 | // The method returns NULL if there is no such previous value and the cursor is not moved from the current position. 353 | int *findPrevious(IteratorInt it, int v){ 354 | if (it->first == NULL){ // if dont have node in Doubly-linked list 355 | set_flag(-1, -1); 356 | return NULL; 357 | } 358 | 359 | int *p; 360 | 361 | if (it->cursor == it->first && it->origin == 1){ // finish when cursor in the first place 362 | set_flag(-1, -1); 363 | return NULL; 364 | } 365 | else{ 366 | Node *current = it->cursor; 367 | 368 | // searching... 369 | while (current != NULL && current->data != v){ 370 | current = current->prev; 371 | } 372 | 373 | if (current == NULL){ // return NUll when can't match 374 | set_flag(-1, -1); 375 | return NULL; 376 | } 377 | else if (current == it->first){ // find correct node in the head 378 | it->origin = 1; 379 | it->cursor = current; 380 | p = &(current->data); 381 | } 382 | else{ // find correct node in the middle of Doubly-linked list 383 | it->cursor = current->prev; 384 | p = &(current->data); 385 | } 386 | set_flag(1, 0); // signed flag bits when succeed 387 | return p; 388 | } 389 | } 390 | 391 | 392 | // Function: Deletes all the nodes in it and frees associated memory. 393 | void freeIt(IteratorInt it){ 394 | Node *p = it->first; 395 | 396 | while (p != NULL){ // free node one by one from first node 397 | Node *temp = p->next; 398 | free(p); 399 | it->count --; 400 | p = temp; 401 | } 402 | 403 | set_flag(-1, -1); // undefinable associated variable 404 | it->origin = -1; 405 | it->first = NULL; 406 | it->last = NULL; 407 | it->cursor = NULL; 408 | free(it); 409 | } 410 | 411 | -------------------------------------------------------------------------------- /Assignment/asst-1/listIteratorInt.h: -------------------------------------------------------------------------------- 1 | /* 2 | listIteratorInt.h 3 | Interface to List Iterator that stores integer values 4 | Written by Ashesh Mahidadia 5 | Date: December 2018 6 | 7 | *** DO NOT modify this file. *** 8 | */ 9 | 10 | #ifndef LISTITERINT_H 11 | #define LISTITERINT_H 12 | 13 | #include 14 | 15 | typedef struct IteratorIntRep *IteratorInt; 16 | 17 | IteratorInt IteratorIntNew(); 18 | int add(IteratorInt it, int v); 19 | int hasNext(IteratorInt it); 20 | int hasPrevious(IteratorInt it); 21 | int *next(IteratorInt it); 22 | int *previous(IteratorInt it); 23 | int deleteElm(IteratorInt it); 24 | int set(IteratorInt it, int v); 25 | int *findNext(IteratorInt it, int v); 26 | int *findPrevious(IteratorInt it, int v); 27 | void reset(IteratorInt it); 28 | void freeIt(IteratorInt it); 29 | 30 | #endif 31 | -------------------------------------------------------------------------------- /Assignment/asst-1/testListIteratorInt.c: -------------------------------------------------------------------------------- 1 | /* 2 | client to test listIteratorInt. 3 | Written by .... 4 | */ 5 | 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include "listIteratorInt.c" 11 | #include "listIteratorInt.h" 12 | 13 | void show(IteratorInt it){ 14 | Node * current = it ->first; 15 | if(it->count == 0){ 16 | printf("^ "); 17 | } 18 | while (current != NULL){ 19 | if(current == it->first && it->origin == 1){ 20 | printf("^ "); 21 | } 22 | printf("%d ", current->data ); 23 | if(it->origin == 0 && current == it->cursor){ 24 | printf("^ "); 25 | } 26 | current = current -> next; 27 | } 28 | printf("\n"); 29 | 30 | current = it->last; 31 | while (current != NULL){ 32 | printf("%d ", current->data); 33 | current = current->prev; 34 | } 35 | printf("\n"); 36 | } 37 | 38 | int main(int argc, char *argv[]) { 39 | 40 | /* The following code, inside the comments, may or may not be correct! 41 | 42 | It's provided in case you find it difficult to understand 43 | how to create a list iterator, and use it's functions. 44 | 45 | The code below only tests basic operations, however 46 | make sure that you do test all the required functions properly in 47 | your test file. 48 | */ 49 | 50 | //int val, result; 51 | 52 | IteratorInt it1 = IteratorIntNew(); 53 | 54 | add(it1, 20); 55 | show(it1); 56 | printf("Number of Node is %d\n", it1->count); 57 | printf("---------------------------------------------\n"); 58 | // 20 ^ 59 | 60 | add(it1, 12); 61 | show(it1); 62 | printf("Number of Node is %d\n", it1->count); 63 | printf("---------------------------------------------\n"); 64 | // 20 12 ^ 65 | 66 | add(it1, 33); 67 | show(it1); 68 | printf("Number of Node is %d\n", it1->count); 69 | printf("---------------------------------------------\n"); 70 | //20 12 33 ^ 71 | 72 | add(it1, 25); 73 | show(it1); 74 | printf("Number of Node is %d\n", it1->count); 75 | printf("---------------------------------------------\n"); 76 | //20 12 33 25 ^ 77 | 78 | printf("The previous one is %d.\n", *previous(it1)); 79 | show(it1); 80 | printf("Number of Node is %d\n", it1->count); 81 | printf("---------------------------------------------\n"); 82 | //return 25 83 | //20 12 33 ^ 25 84 | 85 | printf("The previous one is %d\n", *previous(it1)); 86 | show(it1); 87 | printf("Number of Node is %d\n", it1->count); 88 | printf("---------------------------------------------\n"); 89 | // return 33 90 | // 20 12 ^ 33 25 91 | 92 | printf("The next one is %d\n", *next(it1)); 93 | show(it1); 94 | printf("Number of Node is %d\n", it1->count); 95 | printf("---------------------------------------------\n"); 96 | // return 33 97 | // 20 12 33 ^ 25 98 | 99 | printf("The result is :%d\n", deleteElm(it1)); 100 | show(it1); 101 | printf("Number of Node is %d\n", it1->count); 102 | printf("---------------------------------------------\n"); 103 | // return 1 104 | // 20 12 ^ 25 105 | 106 | printf("The previous one is %d\n", *previous(it1)); 107 | show(it1); 108 | printf("Number of Node is %d\n", it1->count); 109 | printf("---------------------------------------------\n"); 110 | //return 12 111 | // 20 ^ 12 25 112 | 113 | printf("The result is :%d\n", deleteElm(it1)); 114 | show(it1); 115 | printf("Number of Node is %d\n", it1->count); 116 | printf("---------------------------------------------\n"); 117 | // return 1 118 | // 20 ^ 25 119 | 120 | printf("The previous one is %d\n", *previous(it1)); 121 | show(it1); 122 | printf("Number of Node is %d\n", it1->count); 123 | printf("---------------------------------------------\n"); 124 | //return 20 125 | // ^ 20 25 126 | 127 | printf("-------------\n"); 128 | printf("The result is :%d\n", deleteElm(it1)); 129 | show(it1); 130 | printf("Number of Node is %d\n", it1->count); 131 | printf("---------------------------------------------\n"); 132 | // return 1 133 | // ^ 25 134 | 135 | printf("The next one is %d\n", *next(it1)); 136 | show(it1); 137 | printf("Number of Node is %d\n", it1->count); 138 | printf("---------------------------------------------\n"); 139 | // return 25 140 | // 25 ^ 141 | 142 | printf("The result is :%d\n", deleteElm(it1)); 143 | show(it1); 144 | printf("Number of Node is %d\n", it1->count); 145 | printf("---------------------------------------------\n"); 146 | // return 1 147 | // ^ 148 | 149 | add(it1, 55); 150 | show(it1); 151 | printf("Number of Node is %d\n", it1->count); 152 | printf("---------------------------------------------\n"); 153 | // return 1 154 | // 55 ^ 155 | 156 | add(it1, 29); 157 | show(it1); 158 | printf("Number of Node is %d\n", it1->count); 159 | printf("---------------------------------------------\n"); 160 | // return 1 161 | // 55 29 ^ 162 | 163 | reset(it1); 164 | show(it1); 165 | printf("Number of Node is %d\n", it1->count); 166 | printf("---------------------------------------------\n"); 167 | // ^ 55 29 168 | 169 | printf("The next one is %d\n", *next(it1)); 170 | show(it1); 171 | printf("Number of Node is %d\n", it1->count); 172 | printf("---------------------------------------------\n"); 173 | // return 55 174 | // 55 ^ 29 175 | 176 | add(it1, 62); 177 | show(it1); 178 | printf("Number of Node is %d\n", it1->count); 179 | printf("---------------------------------------------\n"); 180 | // 55 62 ^ 29 181 | 182 | add(it1, 44); 183 | show(it1); 184 | printf("Number of Node is %d\n", it1->count); 185 | printf("---------------------------------------------\n"); 186 | //55 62 44 ^ 29 187 | 188 | printf("The previous one is %d\n", *previous(it1)); 189 | show(it1); 190 | printf("Number of Node is %d\n", it1->count); 191 | printf("---------------------------------------------\n"); 192 | // return 44 193 | // 55 62 ^ 44 29 194 | 195 | printf("The next one is %d\n", *next(it1)); 196 | show(it1); 197 | printf("Number of Node is %d\n", it1->count); 198 | printf("---------------------------------------------\n"); 199 | // return 44 200 | // 55 62 44 ^ 29 201 | 202 | deleteElm(it1); 203 | show(it1); 204 | printf("Number of Node is %d\n", it1->count); 205 | printf("---------------------------------------------\n"); 206 | // 55 62 ^ 29 207 | 208 | printf("The previous one is %d\n", *previous(it1)); 209 | show(it1); 210 | printf("Number of Node is %d\n", it1->count); 211 | printf("---------------------------------------------\n"); 212 | // return 62 213 | // 55 ^ 62 29 214 | 215 | printf("The next one is %d\n", *next(it1)); 216 | show(it1); 217 | printf("Number of Node is %d\n", it1->count); 218 | printf("---------------------------------------------\n"); 219 | // return 62 220 | // 55 62 ^ 29 221 | 222 | deleteElm(it1); 223 | show(it1); 224 | printf("Number of Node is %d\n", it1->count); 225 | printf("---------------------------------------------\n"); 226 | // 55 ^ 29 227 | 228 | deleteElm(it1); 229 | show(it1); 230 | printf("Number of Node is %d\n", it1->count); 231 | printf("---------------------------------------------\n"); 232 | // return 0 233 | // 55 ^ 29 234 | 235 | printf("The next one is %d\n", *next(it1)); 236 | show(it1); 237 | printf("Number of Node is %d\n", it1->count); 238 | printf("---------------------------------------------\n"); 239 | // 55 29 ^ 240 | 241 | deleteElm(it1); 242 | show(it1); 243 | printf("Number of Node is %d\n", it1->count); 244 | printf("---------------------------------------------\n"); 245 | // 55 ^ 246 | 247 | printf("The previous one is %d\n", *previous(it1)); 248 | show(it1); 249 | printf("Number of Node is %d\n", it1->count); 250 | printf("---------------------------------------------\n"); 251 | // return 55 252 | // ^ 55 253 | 254 | deleteElm(it1); 255 | show(it1); 256 | printf("Number of Node is %d\n", it1->count); 257 | printf("---------------------------------------------\n"); 258 | // 259 | return EXIT_SUCCESS; 260 | 261 | } 262 | -------------------------------------------------------------------------------- /Assignment/asst-1/tests/1.exp: -------------------------------------------------------------------------------- 1 | add 25, returns 1 2 | add 14, returns 1 3 | add 32, returns 1 4 | add 53, returns 1 5 | add 8, returns 1 6 | --- --- --- --- --- 7 | previous, returns 8 8 | previous, returns 53 9 | previous, returns 32 10 | -------------------------------------------------------------------------------- /Assignment/asst-1/tests/2.exp: -------------------------------------------------------------------------------- 1 | add 25, returns 1 2 | add 14, returns 1 3 | add 32, returns 1 4 | add 53, returns 1 5 | add 8, returns 1 6 | --- --- --- --- --- 7 | previous, returns 8 8 | previous, returns 53 9 | previous, returns 32 10 | next, returns 32 11 | next, returns 53 12 | -------------------------------------------------------------------------------- /Assignment/asst-1/tests/3.exp: -------------------------------------------------------------------------------- 1 | add 25, returns 1 2 | add 14, returns 1 3 | add 32, returns 1 4 | add 53, returns 1 5 | add 8, returns 1 6 | --- --- --- --- --- 7 | previous, returns 8 8 | previous, returns 53 9 | previous, returns 32 10 | delete, returns 1 11 | next, returns 53 12 | previous, returns 53 13 | previous, returns 14 14 | -------------------------------------------------------------------------------- /Final exam/.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "files.associations": { 3 | "graph.h": "c" 4 | } 5 | } -------------------------------------------------------------------------------- /Final exam/Final-sample.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/brmuch/COMP9024/094852af15dca9d5d9fa34d492a4415a476d812e/Final exam/Final-sample.pdf -------------------------------------------------------------------------------- /Final exam/Q1/BSTree.c: -------------------------------------------------------------------------------- 1 | // Binary Search Tree ADT implementation ... COMP9024 17s2 2 | 3 | #include 4 | #include 5 | #include 6 | #include "BSTree.h" 7 | #include "math.h" 8 | 9 | #define data(tree) ((tree)->data) 10 | #define left(tree) ((tree)->left) 11 | #define right(tree) ((tree)->right) 12 | 13 | // make a new node containing data 14 | Tree newNode(Item it) { 15 | Tree new = malloc(sizeof(Node)); 16 | assert(new != NULL); 17 | data(new) = it; 18 | left(new) = right(new) = NULL; 19 | return new; 20 | } 21 | 22 | // create a new empty Tree 23 | Tree newTree() { 24 | return NULL; 25 | } 26 | 27 | // free memory associated with Tree 28 | void freeTree(Tree t) { 29 | if (t != NULL) { 30 | freeTree(left(t)); 31 | freeTree(right(t)); 32 | free(t); 33 | } 34 | } 35 | 36 | // display Tree sideways 37 | void showTreeR(Tree t, int depth) { 38 | if (t != NULL) { 39 | showTreeR(right(t), depth+1); 40 | int i; 41 | for (i = 0; i < depth; i++) 42 | putchar('\t'); // TAB character 43 | printf("%d\n", data(t)); 44 | showTreeR(left(t), depth+1); 45 | } 46 | } 47 | 48 | void showTree(Tree t) { 49 | showTreeR(t, 0); 50 | } 51 | 52 | // compute height of Tree 53 | int TreeHeight(Tree t) { 54 | if (t == NULL) 55 | return 0; 56 | else{ 57 | return TreeHeight(t->left) > TreeHeight(t->right)?TreeHeight(t->left)+1:TreeHeight(t->right)+1; 58 | } 59 | } 60 | 61 | // count #nodes in Tree 62 | int TreeNumNodes(Tree t) { 63 | if (t == NULL) 64 | return 0; 65 | else 66 | return 1 + TreeNumNodes(left(t)) + TreeNumNodes(right(t)); 67 | } 68 | 69 | // check whether a key is in a Tree 70 | bool TreeSearch(Tree t, Item it) { 71 | if (t == NULL) 72 | return false; 73 | else if (it < data(t)) 74 | return TreeSearch(left(t), it); 75 | else if (it > data(t)) 76 | return TreeSearch(right(t), it); 77 | else // it == data(t) 78 | return true; 79 | } 80 | 81 | // insert a new item into a Tree 82 | Tree TreeInsert(Tree t, Item it) { 83 | if (t == NULL) 84 | t = newNode(it); 85 | else if (it < data(t)) 86 | left(t) = TreeInsert(left(t), it); 87 | else if (it > data(t)) 88 | right(t) = TreeInsert(right(t), it); 89 | return t; 90 | } 91 | 92 | Tree joinTrees(Tree t1, Tree t2) { 93 | if (t1 == NULL) 94 | return t2; 95 | else if (t2 == NULL) 96 | return t1; 97 | else { 98 | Tree curr = t2; 99 | Tree parent = NULL; 100 | while (left(curr) != NULL) { // find min element in t2 101 | parent = curr; 102 | curr = left(curr); 103 | } 104 | if (parent != NULL) { 105 | left(parent) = right(curr); // unlink min element from parent 106 | right(curr) = t2; 107 | } 108 | left(curr) = t1; 109 | return curr; // min element is new root 110 | } 111 | } 112 | 113 | // delete an item from a Tree 114 | Tree TreeDelete(Tree t, Item it) { 115 | if (t != NULL) { 116 | if (it < data(t)) 117 | left(t) = TreeDelete(left(t), it); 118 | else if (it > data(t)) 119 | right(t) = TreeDelete(right(t), it); 120 | else { 121 | Tree new; 122 | if (left(t) == NULL && right(t) == NULL) 123 | new = NULL; 124 | else if (left(t) == NULL) // if only right subtree, make it the new root 125 | new = right(t); 126 | else if (right(t) == NULL) // if only left subtree, make it the new root 127 | new = left(t); 128 | else // left(t) != NULL and right(t) != NULL 129 | new = joinTrees(left(t), right(t)); 130 | free(t); 131 | t = new; 132 | } 133 | } 134 | return t; 135 | } 136 | 137 | Tree rotateRight(Tree n1) { 138 | if (n1 == NULL || left(n1) == NULL) 139 | return n1; 140 | Tree n2 = left(n1); 141 | left(n1) = right(n2); 142 | right(n2) = n1; 143 | return n2; 144 | } 145 | 146 | Tree rotateLeft(Tree n2) { 147 | if (n2 == NULL || right(n2) == NULL) 148 | return n2; 149 | Tree n1 = right(n2); 150 | right(n2) = left(n1); 151 | left(n1) = n2; 152 | return n1; 153 | } 154 | 155 | Tree insertAtRoot(Tree t, Item it) { 156 | 157 | printf("Not yet implemented.\n"); 158 | 159 | return t; 160 | } 161 | 162 | Tree partition(Tree t, int i) { 163 | if (t != NULL) { 164 | assert(0 <= i && i < TreeNumNodes(t)); 165 | int m = TreeNumNodes(left(t)); 166 | if (i < m) { 167 | left(t) = partition(left(t), i); 168 | t = rotateRight(t); 169 | } else if (i > m) { 170 | right(t) = partition(right(t), i-m-1); 171 | t = rotateLeft(t); 172 | } 173 | } 174 | return t; 175 | } 176 | 177 | Tree rebalance(Tree t) { 178 | int n = TreeNumNodes(t); 179 | if (n >= 3) { 180 | t = partition(t, n/2); // put node with median key at root 181 | left(t) = rebalance(left(t)); // then rebalance each subtree 182 | right(t) = rebalance(right(t)); 183 | } 184 | return t; 185 | } 186 | 187 | // Count Tree Nodes 188 | int countNodes(Tree t){ 189 | if (t == NULL) 190 | return 0; 191 | else 192 | return countNodes(t->left) + countNodes(t->right) + 1; 193 | } 194 | 195 | // count all Leaf of given Tree 196 | int countLeaf(Tree t){ 197 | if (t == NULL) 198 | return 0; 199 | else{ 200 | int left = countLeaf(t->left); 201 | int right = countLeaf(t->right); 202 | return left + right == 0?1:left + right; 203 | } 204 | } 205 | 206 | // count all nodes have odd value of given Tree 207 | int countOdds(Tree t){ 208 | if (t == NULL) 209 | return 0; 210 | else 211 | return t->data%2 == 1?countOdds(t->left) + countOdds(t->right) + 1:countOdds(t->left) + countOdds(t->right); 212 | 213 | } 214 | 215 | 216 | extern int recur_sup_Balanced(Tree t); 217 | // determine whether Tree is balanced 218 | int isBalanced(Tree t){ 219 | int result = recur_sup_Balanced(t); 220 | return result != -1?1:0; 221 | } 222 | 223 | // support function for isBalanced 224 | // retun -1 if Tree is unbalanced, else return Tree's height 225 | int recur_sup_Balanced(Tree t){ 226 | if (t == NULL) 227 | return 0; 228 | else{ 229 | if (recur_sup_Balanced(t->left) == -1 || recur_sup_Balanced(t->right) == -1 \ 230 | || abs(recur_sup_Balanced(t->right) - recur_sup_Balanced(t->left)) > 1) 231 | return -1; 232 | else{ 233 | int left = recur_sup_Balanced(t->left); 234 | int right = recur_sup_Balanced(t->right); 235 | 236 | return left > right? left + 1: right + 1; 237 | } 238 | } 239 | } -------------------------------------------------------------------------------- /Final exam/Q1/BSTree.h: -------------------------------------------------------------------------------- 1 | // Binary Search Tree ADT interface ... COMP9024 17s2 2 | 3 | #include 4 | 5 | typedef int Item; // item is just a key 6 | 7 | typedef struct Node *Tree; 8 | typedef struct Node { 9 | int data; 10 | Tree left, right; 11 | } Node; 12 | 13 | 14 | 15 | Tree newTree(); // create an empty Tree 16 | void freeTree(Tree); // free memory associated with Tree 17 | void showTree(Tree); // display a Tree (sideways) 18 | 19 | bool TreeSearch(Tree, Item); // check whether an item is in a Tree 20 | int TreeHeight(Tree); // compute height of Tree 21 | int TreeNumNodes(Tree); // count #nodes in Tree 22 | Tree TreeInsert(Tree, Item); // insert a new item into a Tree 23 | Tree TreeDelete(Tree, Item); // delete an item from a Tree 24 | 25 | // internal functions made visible for testing 26 | Tree rotateRight(Tree); 27 | Tree rotateLeft(Tree); 28 | Tree insertAtRoot(Tree, Item); 29 | Tree partition(Tree, int); 30 | Tree rebalance(Tree); 31 | 32 | // Final exam BSTree support function 33 | int isBalanced(Tree t); 34 | int countNodes(Tree t); 35 | int countLeaf(Tree t); 36 | int countOdds(Tree t); -------------------------------------------------------------------------------- /Final exam/Q1/Q1.c: -------------------------------------------------------------------------------- 1 | // Auto Test For final exam Q1 2 | #include "stdio.h" 3 | #include "stdlib.h" 4 | #include "BSTree.h" 5 | 6 | int main(int argc, char ** argv){ 7 | Tree t = newTree(); // build a test tree 8 | 9 | t = TreeInsert(t, 10); 10 | t = TreeInsert(t, 5); 11 | t = TreeInsert(t, 4); 12 | t = TreeInsert(t, 7); 13 | 14 | t = TreeInsert(t, 15); 15 | t = TreeInsert(t, 1); 16 | // t = TreeInsert(t, 12); 17 | //t = TreeInsert(t, 21); 18 | showTree(t); 19 | 20 | printf("Tree height is %d\n", TreeHeight(t)); 21 | printf("Tree Balanced: %d\n", isBalanced(t)); 22 | printf("Leaf number of Tree: %d\n", countLeaf(t)); 23 | printf("Odds number Nodes: %d\n", countOdds(t)); 24 | } -------------------------------------------------------------------------------- /Final exam/Q1/Q1.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/brmuch/COMP9024/094852af15dca9d5d9fa34d492a4415a476d812e/Final exam/Q1/Q1.pdf -------------------------------------------------------------------------------- /Final exam/Q2/Graph.c: -------------------------------------------------------------------------------- 1 | // Graph ADT 2 | // Adjacency Matrix Representation ... COMP9024 17s2 3 | #include "Graph.h" 4 | #include 5 | #include 6 | #include 7 | #include 8 | 9 | Graph newGraph(int V) { 10 | assert(V >= 0); 11 | int i; 12 | 13 | Graph g = malloc(sizeof(GraphRep)); 14 | assert(g != NULL); 15 | g->nV = V; 16 | g->nE = 0; 17 | 18 | // allocate memory for each row 19 | g->edges = malloc(V * sizeof(int *)); 20 | assert(g->edges != NULL); 21 | // allocate memory for each column and initialise with 0 22 | for (i = 0; i < V; i++) { 23 | g->edges[i] = calloc(V, sizeof(int)); 24 | assert(g->edges[i] != NULL); 25 | } 26 | 27 | return g; 28 | } 29 | 30 | // check if vertex is valid in a graph 31 | bool validV(Graph g, Vertex v) { 32 | return (g != NULL && v >= 0 && v < g->nV); 33 | } 34 | 35 | void insertEdge(Graph g, Edge e) { 36 | assert(g != NULL && validV(g,e.v) && validV(g,e.w)); 37 | 38 | if (!g->edges[e.v][e.w]) { // edge e not in graph 39 | g->edges[e.v][e.w] = 1; 40 | g->edges[e.w][e.v] = 1; 41 | g->nE++; 42 | } 43 | } 44 | 45 | void removeEdge(Graph g, Edge e) { 46 | assert(g != NULL && validV(g,e.v) && validV(g,e.w)); 47 | 48 | if (g->edges[e.v][e.w]) { // edge e in graph 49 | g->edges[e.v][e.w] = 0; 50 | g->edges[e.w][e.v] = 0; 51 | g->nE--; 52 | } 53 | } 54 | 55 | bool adjacent(Graph g, Vertex v, Vertex w) { 56 | assert(g != NULL && validV(g,v) && validV(g,w)); 57 | 58 | return (g->edges[v][w] != 0); 59 | } 60 | 61 | void showGraph(Graph g) { 62 | assert(g != NULL); 63 | int i, j; 64 | 65 | printf("Number of vertices: %d\n", g->nV); 66 | printf("Number of edges: %d\n", g->nE); 67 | for (i = 0; i < g->nV; i++) 68 | for (j = i+1; j < g->nV; j++) 69 | if (g->edges[i][j]) 70 | printf("Edge %d - %d\n", i, j); 71 | } 72 | 73 | void freeGraph(Graph g) { 74 | assert(g != NULL); 75 | 76 | int i; 77 | for (i = 0; i < g->nV; i++) 78 | free(g->edges[i]); 79 | free(g->edges); 80 | free(g); 81 | } 82 | 83 | // Q1 84 | extern bool dfs_hasPath(Graph g, int src, int dest, int *visited); 85 | bool hasPath(Graph g,int src,int dest) { 86 | int * visited = calloc(g->nV, sizeof(int)); 87 | return dfs_hasPath(g, src, dest, visited); 88 | } 89 | 90 | // dfs support function for hasPath 91 | bool dfs_hasPath(Graph g, int src, int dest, int *visited) { 92 | visited[src] = 1; 93 | 94 | for (int i = 0; i < g->nV; i ++) { 95 | if (g->edges[src][i] == 1 && visited[i] == 0) { 96 | if (i == dest) 97 | return true; 98 | else if (dfs_hasPath(g, i, dest, visited)){ 99 | return true; 100 | } 101 | } 102 | } 103 | return false; 104 | } 105 | 106 | // Q2 107 | extern bool dfs_findPath(Graph g, int src, int dest, int *visited); 108 | bool findPath(Graph g,int src,int dest) { 109 | int *visited = malloc(g->nV * sizeof(int)); 110 | // initial visited array 111 | for (int i = 0; i < g->nV; i ++) { 112 | visited[i] = -1; 113 | } 114 | visited[src] = src; 115 | 116 | if (dfs_findPath(g, src, dest, visited)) { 117 | int index = dest; 118 | while (index != src) { 119 | printf("%d-", index); 120 | index = visited[index]; 121 | } 122 | printf("%d\n", index); 123 | return true; 124 | } 125 | else { 126 | printf("can not find a path from %d to %d.\n", src, dest); 127 | return false; 128 | } 129 | } 130 | 131 | // support funciton for findPath 132 | bool dfs_findPath(Graph g, int src, int dest, int *visited) { 133 | for (int i = 0; i < g->nV; i ++) { 134 | if (g->edges[src][i] == 1 && visited[i] == -1) { 135 | visited[i] = src; 136 | if (i == dest) 137 | return true; 138 | else if (dfs_findPath(g, i, dest, visited)) 139 | return true; 140 | } 141 | } 142 | return false; 143 | } 144 | 145 | //Q3 warning: exit the node from 146 | extern bool dfs_CycleCheck(Graph g, int v, int *visited, int from); 147 | bool dfsCycleCheck(Graph g,int v) { 148 | int *visited = calloc(g->nV, sizeof(int)); 149 | return dfs_CycleCheck(g, v, visited, -1); 150 | } 151 | 152 | bool dfs_CycleCheck(Graph g, int v, int *visited, int from) { 153 | visited[v] = 1; 154 | 155 | for (int i = 0; i < g->nV; i ++) { 156 | if (g->edges[v][i] == 1 && i != from){ 157 | if (visited[i] == 1) 158 | return true; 159 | else if (dfs_CycleCheck(g, i, visited, v)){ 160 | return true; 161 | } 162 | } 163 | } 164 | return false; 165 | } 166 | 167 | //Q4: 168 | extern void dfs_countReachableNodes(Graph g, int v, int *visited); 169 | int countReachableNodes(Graph g, int v) { 170 | int *visited = calloc(g->nV, sizeof(int)); 171 | int count = 0; 172 | dfs_countReachableNodes(g, v, visited); 173 | for (int i = 0; i < g->nV; i ++) { 174 | for (int j = i + 1; j < g->nV; j ++) 175 | if (g->edges[i][j]) 176 | count ++; 177 | } 178 | free(visited); 179 | return count; 180 | } 181 | 182 | void dfs_countReachableNodes(Graph g, int v, int *visited) { 183 | visited[v] = 1; 184 | 185 | for (int i = 0; i < g->nV; i ++) { 186 | if (g->edges[v][i] == 1 && visited[i] == 0) { 187 | dfs_countReachableNodes(g, i, visited); 188 | } 189 | } 190 | } -------------------------------------------------------------------------------- /Final exam/Q2/Graph.h: -------------------------------------------------------------------------------- 1 | // Graph ADT interface ... COMP9024 17s2 2 | #include 3 | 4 | typedef struct GraphRep *Graph; 5 | 6 | typedef struct GraphRep { 7 | int **edges; // adjacency matrix 8 | int nV; // #vertices 9 | int nE; // #edges 10 | } GraphRep; 11 | 12 | // vertices are ints 13 | typedef int Vertex; 14 | 15 | // edges are pairs of vertices (end-points) 16 | typedef struct Edge { 17 | Vertex v; 18 | Vertex w; 19 | } Edge; 20 | 21 | Graph newGraph(int); 22 | void insertEdge(Graph, Edge); 23 | void removeEdge(Graph, Edge); 24 | bool adjacent(Graph, Vertex, Vertex); 25 | void showGraph(Graph); 26 | void freeGraph(Graph); 27 | 28 | // support function for Q2 in 9024 exam sample 29 | bool hasPath(Graph g,int src,int dest); 30 | bool findPath(Graph g,int src,int dest); 31 | //bool findPathBFS(Graph g,int src,int dest); 32 | bool dfsCycleCheck(Graph g,int v); 33 | //int components(Graph g); 34 | int countReachableNodes(Graph g, int v); 35 | -------------------------------------------------------------------------------- /Final exam/Q2/Q2.c: -------------------------------------------------------------------------------- 1 | // test file for q2 comp9024 2 | #include "stdio.h" 3 | #include "stdlib.h" 4 | #include "Graph.h" 5 | 6 | int main(int argc, char **argv) { 7 | Graph g = newGraph(5); 8 | Edge e; 9 | e.v = 0; 10 | e.w = 1; 11 | insertEdge(g, e); // 0 - 1 12 | e.v = 1; 13 | e.w = 2; 14 | insertEdge(g, e); // 1 - 2 15 | e.v = 1; 16 | e.w = 4; 17 | insertEdge(g, e); // 1 - 4 18 | e.v = 0; 19 | e.w = 3; 20 | insertEdge(g, e); // 0 - 3 21 | e.v = 3; 22 | e.w = 4; 23 | insertEdge(g, e); // 3 - 4 24 | showGraph(g); // showGraph 25 | 26 | printf("HasPath? %d\n", hasPath(g, 0, 4)); 27 | int src = 0; 28 | int dest = 4; 29 | printf("Path from %d to %d? %d\n", src, dest, findPath(g, src, dest)); 30 | //printf("Path from %d to %d? %d\n", src, dest, findPathBFS(g, src, dest)); 31 | printf("HasCycle? %d\n", dfsCycleCheck(g, 0)); 32 | //printf("Components: %d\n", components(g)); 33 | printf("ReachNodes: %d\n", countReachableNodes(g, 0)); 34 | } -------------------------------------------------------------------------------- /Final exam/Q2/Q2.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/brmuch/COMP9024/094852af15dca9d5d9fa34d492a4415a476d812e/Final exam/Q2/Q2.pdf -------------------------------------------------------------------------------- /Mid exam/sample-midterm.zip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/brmuch/COMP9024/094852af15dca9d5d9fa34d492a4415a476d812e/Mid exam/sample-midterm.zip -------------------------------------------------------------------------------- /Problem Set/Week 01a/1.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | int main() 5 | { 6 | int temp, convert; 7 | 8 | for (int number = 10000; number <= 99999; number ++) { 9 | temp = number; 10 | convert = 0; 11 | while (temp > 0) { 12 | convert *= 10; 13 | convert += temp %10; 14 | temp /= 10; 15 | } 16 | if (convert == 4 * number) { 17 | printf("This 5-digit number is %d.", number); 18 | break; 19 | } 20 | } 21 | return 0; 22 | } 23 | -------------------------------------------------------------------------------- /Problem Set/Week 01a/2a.c: -------------------------------------------------------------------------------- 1 | #include"stdio.h" 2 | #include"stdlib.h" 3 | #define SIZE 6 4 | 5 | float innerProduct(float a[], float b[], int n) { 6 | float result = 0; 7 | 8 | for (int i = 0; i < n; i ++) { 9 | result += a[i] * b[i]; 10 | } 11 | 12 | return result; 13 | } 14 | 15 | int main() { 16 | float a[SIZE] = {1.1, 2.2, 3.3, 4.4, 5.5, 6.6}; 17 | float b[SIZE] = {1.1, 2.2, 3.3, 4.4, 5.5, 6.6}; 18 | 19 | printf("The inner product of two vectors is %.2f.", innerProduct(a, b, SIZE)); 20 | } 21 | -------------------------------------------------------------------------------- /Problem Set/Week 01a/2b.c: -------------------------------------------------------------------------------- 1 | #include"stdio.h" 2 | #include"stdlib.h" 3 | 4 | #define M 3 5 | #define N 4 6 | #define P 4 7 | 8 | void matrixProduct(float a[M][N], float b[N][P], float c[M][P]){ 9 | int value = 0; 10 | 11 | for (int i = 0; i < M; i ++){ 12 | for (int j = 0; j < P; j++){ 13 | value = 0; 14 | for (int k = 0; k < N; k ++){ 15 | value += a[i][k] * b[k][j]; 16 | } 17 | c[i][j] = value; 18 | printf("%f ", c[i][j]); 19 | } 20 | printf("\n"); 21 | } 22 | } 23 | 24 | int main(){ 25 | float a[M][N] = {{1, 2, 3, 4}, {1, 2, 3, 4}, {1, 2, 3, 4}}; 26 | float b[N][P] = {{1, 2, 3, 4}, {1, 2, 3, 4}, {1, 2, 3, 4}, {1, 2, 3, 4}}; 27 | float c[M][P]; 28 | 29 | matrixProduct(a, b, c); 30 | } -------------------------------------------------------------------------------- /Problem Set/Week 01a/3.c: -------------------------------------------------------------------------------- 1 | #include"stdio.h" 2 | #include"stdlib.h" 3 | 4 | int main(int argc, char const *argv[]) 5 | { 6 | char catdog[] = { 'a','c','d','g','o','t' }; 7 | 8 | int count = 0; 9 | int i, j, k, l, m, n; 10 | for (i = 0; i < 6; i++) 11 | for (j = 0; j < 6; j++) 12 | for (k = 0; k<6; k++) 13 | for (l = 0; l < 6; l++) 14 | for (m = 0; m < 6; m++) 15 | for (n = 0; n < 6; n++) 16 | if (i!=j && i!=k && i!=l && i!=m && i!=n && 17 | j!=k && j!=l && j!=m && j!=n && 18 | k!=l && k!=m && k!=n && 19 | l!=m && l!=n && m!=n) { 20 | printf("%c%c%c%c%c%c\n", catdog[i], catdog[j], 21 | catdog[k], catdog[l], 22 | catdog[m], catdog[n]); 23 | count++; 24 | } 25 | printf("%d\n", count); 26 | return 0; 27 | } 28 | -------------------------------------------------------------------------------- /Problem Set/Week 01a/5.c: -------------------------------------------------------------------------------- 1 | enum DAY{ 2 | MON, TUE, WED, THU, FRI, SAT, SUN 3 | }; 4 | 5 | typedef struct Date{ 6 | enum DAY day; 7 | int year; 8 | int month; 9 | int date; 10 | int hour; 11 | int minute; 12 | }Date; 13 | 14 | typedef struct Opal{ 15 | int Transction_number; 16 | Date date; 17 | char Mode; 18 | char Details[31]; 19 | int Journey_number; 20 | char Fare_applied[31]; 21 | float Fare; 22 | float Discount; 23 | float Amount; 24 | }Opal; 25 | 26 | -------------------------------------------------------------------------------- /Problem Set/Week 01a/6.c: -------------------------------------------------------------------------------- 1 | #include"stdio.h" 2 | #include"stdlib.h" 3 | 4 | int maximum(int a, int b, int c){ 5 | int max = a > b? a:b; 6 | return max > c? max:c; 7 | } 8 | 9 | int main(int argc, char const *argv[]) 10 | { 11 | printf("%d", maximum(55, 2, 3)); 12 | return 0; 13 | } 14 | -------------------------------------------------------------------------------- /Problem Set/Week 01a/COMP9024 19T0 - Week 01a Problem Set.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | COMP9024 19T0 - Week 01a Problem Set 5 | 26 | 27 |
28 | 29 | 30 | 33 | 37 | 40 |
31 | COMP9024 19T0 32 | 34 | Week 01a Problem Set
35 | Elementary Data and Control Structures in C 36 |
38 | Data Structures and Algorithms 39 |
41 |
42 |
    43 | 44 |
    45 |
  1. (Arithmetic) 46 |

    There is a 5-digit number that satisfies 4·abcde = edcba, that is, when multiplied by 4 yields the same number read backwards. Write a C-program to find this number.

    47 | 73 | 74 |
    75 |
  2. (Arrays) 76 |
      77 |
    1. 78 |

      79 | Write a C-function that returns the inner product of two n-dimensional vectors a and b, encoded as 1-dimensional arrays of n floating point numbers. 80 |

      81 |

      82 | Use the function prototype float innerProduct(float a[], float b[], int n). 83 |

      84 |

      85 | Hint: The inner product of two vectors is calculated as `sum_(i=1..n)bb"a"_(i)*bb"b"_(i)` 86 |

      87 | 88 |
    2. 89 |

      90 | Write a C-function to compute C as the matrix product of matrices A and B. 91 |

      92 |

      93 | Use the function prototype void matrixProduct(float a[M][N], float b[N][P], float c[M][P]). 94 |
      95 | You can assume that M, N, P are given as symbolic constants, e.g. 96 |

       97 | #define M 3
       98 | #define N 4
       99 | #define P 4
      100 | 
      101 |

      102 | Hint: The product of an m×n matrix A and an n×p matrix B is the m×p matrix C such that `bb"C"_(ij) = sum_(k=1..n)bb"A"_(ik)*bb"B"_(kj)`  for all i∈{1..m} and j∈{1..p}. 103 |

      104 |
    105 | 130 | 131 |
    132 |
  3. (Characters) 133 |

    134 | Write a C-program that outputs, in alphabetical order, all strings that use each of the characters 'c', 'a', 't', 'd', 'o', 'g' exactly once.

    135 |

    How many strings does the program generate?

    136 | 167 | 168 |
    169 |
  4. (Elementary control structures) 170 |
      171 |
    1. 172 |

      173 | Write a C-function that takes a positive integer n as argument and outputs a series of numbers according to the following process, until 1 is reached:

      174 |
        175 |
      • if n is even, then nn/2 176 |
      • if n is odd, then n ← 3*n+1 177 |
      178 | 179 |
    2. 180 |

      181 | The Fibonacci numbers are defined as follows: 182 |

        183 |
      • Fib(1) = 1 184 |
      • Fib(2) = 1 185 |
      • Fib(n) = Fib(n-1)+Fib(n-2) for n≥3 186 |
      187 |

      Write a C program fibonacci.c that applies the process described in Part a. to the first 10 Fibonacci numbers.

      188 | The output of the program should begin with 189 |
      190 | Fib[1] = 1
      191 | 1
      192 | Fib[2] = 1
      193 | 1
      194 | Fib[3] = 2
      195 | 2
      196 | 1
      197 | Fib[4] = 3
      198 | 3
      199 | 10
      200 | 5
      201 | 16
      202 | 8
      203 | 4
      204 | 2
      205 | 1
      206 | 
      207 |
    208 | 209 |
    210 |

    We have created a script that can automatically test your program. To run this test you can execute the dryrun program that corresponds to the problem set and week, i.e. prob01 for this week. It expects to find a program named fibonacci.c in the current directory. You can use dryrun as follows:

    211 |
    212 | ~cs9024/bin/dryrun prob01a
    213 | 
    214 |
    215 | 216 |

    Note: Please ensure that your output follows exactly the format shown above.

    217 | 218 | 219 | 253 | 254 |
    255 |
  5. (Elementary data structures) 256 |

    257 | Define a data structure to store all information of a single ride with the Opal card. Here are two sample records: 258 |

    259 | 260 |

    261 | You may assume that individual stops (such as "Anzac Pde D opp UNSW") require no more than 31 characters. 262 |

    263 |

    264 | Determine the memory requirements of your data structure, assuming that each integer and floating point number takes 4 bytes. 265 |

    266 |

    267 | If you want to store millions of records, how would you improve your data structure? 268 |

    269 | 300 | 301 |
    302 |
  6. Challenge Exercise 303 |

    Write a C-function that takes 3 integers as arguments and returns the largest of them. The following restrictions apply: 304 |

      305 |
    • You are not permitted to use if statements. 306 |
    • You are not permitted to use loops (e.g. while). 307 |
    • You are not permitted to call any function. 308 |
    • You are only permitted to use data and control structures introduced in Week 1's lecture. 309 |
    310 |

    311 | 320 | 321 |
322 | 323 | 324 | -------------------------------------------------------------------------------- /Problem Set/Week 01a/fibonacci.c: -------------------------------------------------------------------------------- 1 | #include"stdio.h" 2 | #include"stdlib.h" 3 | #define SIZE 10 4 | 5 | void operation(int n){ 6 | if (n == 1) { 7 | printf("%d\n", n); 8 | } 9 | else{ 10 | if (n % 2 == 1){ 11 | printf("%d\n", n); 12 | operation(3 * n + 1); 13 | } 14 | else{ 15 | printf("%d\n", n); 16 | operation(n / 2); 17 | } 18 | } 19 | } 20 | 21 | int * Fibonacci(){ 22 | static int F[SIZE]; 23 | if (SIZE < 1){ 24 | return F; 25 | } 26 | else if (SIZE == 1){ 27 | F[0] == 1; 28 | return F; 29 | } 30 | else if (SIZE == 2){ 31 | F[0] == 1; 32 | F[1] == 1; 33 | return F; 34 | } 35 | else{ 36 | F[0] = 1; 37 | F[1] = 1; 38 | for (int i = 2; i < SIZE; i++){ 39 | F[i] = F[i-1] + F[i-2]; 40 | } 41 | return F; 42 | } 43 | } 44 | 45 | int main(int argc, char const *argv[]) 46 | { 47 | int * f = Fibonacci(); 48 | for (int i = 0; i < SIZE; i++){ 49 | printf("Fib[%d] = %d\n", i + 1, f[i]); 50 | operation(f[i]); 51 | } 52 | return 0; 53 | } 54 | -------------------------------------------------------------------------------- /Problem Set/Week 01b/1.c: -------------------------------------------------------------------------------- 1 | // Stack ADO implementation ... COMP9024 2 | #include "Stack.h" 3 | #include 4 | 5 | #define MAXITEMS 10 6 | 7 | static struct { 8 | int item[MAXITEMS]; 9 | int top; 10 | } stackObject; // defines the Data Object 11 | 12 | void StackInit() { // set up empty stack 13 | stackObject.top = -1; 14 | } 15 | 16 | int StackIsEmpty() { // check whether stack is empty 17 | return (stackObject.top < 0); 18 | } 19 | 20 | void StackPush(int ch) { // insert integer on top of stack 21 | assert(stackObject.top < MAXITEMS-1); 22 | stackObject.top++; 23 | int i = stackObject.top; 24 | stackObject.item[i] = ch; 25 | } 26 | 27 | int StackPop() { // remove integer from top of stack 28 | assert(stackObject.top > -1); 29 | int i = stackObject.top; 30 | int ch = stackObject.item[i]; 31 | stackObject.top--; 32 | return ch; 33 | } -------------------------------------------------------------------------------- /Problem Set/Week 01b/2.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include "stdlib.h" 3 | #include "1.c" 4 | 5 | int main(int argc, char const *argv[]) 6 | { 7 | int num, temp; 8 | 9 | StackInit(); 10 | printf("Enter a positive number: "); 11 | scanf("%d", &num); 12 | 13 | for (int i = 0; i < num; i++){ 14 | printf("Enter a number: "); 15 | scanf("%d", &temp); 16 | StackPush(temp); 17 | } 18 | 19 | for (int i = 0; i < num; i++){ 20 | printf("%d\n", StackPop()); 21 | } 22 | return 0; 23 | } -------------------------------------------------------------------------------- /Problem Set/Week 01b/2b.c: -------------------------------------------------------------------------------- 1 | #include "stdio.h" 2 | #include "stdlib.h" 3 | #include "1.c" 4 | 5 | int main(int argc, char const *argv[]) 6 | { 7 | StackInit(); 8 | 9 | for (int i = 1; i < argc; i++){ 10 | StackPush(atoi(argv[i])); 11 | } 12 | 13 | while (!StackIsEmpty()){ 14 | printf("%d\n", StackPop()); 15 | } 16 | return 0; 17 | } 18 | -------------------------------------------------------------------------------- /Problem Set/Week 01b/3.c: -------------------------------------------------------------------------------- 1 | #include "stdio.h" 2 | #include "stdlib.h" 3 | #include "1.c" 4 | 5 | int main(int argc, char const *argv[]) 6 | { 7 | int k; 8 | int number = atoi(argv[1]); 9 | printf("Plz input the base k:"); 10 | scanf("%d", &k); 11 | StackInit(); 12 | 13 | while (number != 0){ 14 | StackPush(number % k); 15 | number /= k; 16 | } 17 | 18 | printf("Result:"); 19 | while (!StackIsEmpty()){ 20 | printf("%d", StackPop()); 21 | } 22 | return 0; 23 | } 24 | -------------------------------------------------------------------------------- /Problem Set/Week 01b/4.c: -------------------------------------------------------------------------------- 1 | #include"Queue.h" 2 | #include 3 | 4 | #define MAXITEMS 10 5 | 6 | static struct { 7 | int item[MAXITEMS]; 8 | int tail; 9 | } queueObject; 10 | 11 | void QueueInit(){ // set up empty queue 12 | queueObject.tail = -1; 13 | } 14 | 15 | int QueueIsEmpty(){ // check whether queue is empty 16 | return (queueObject.tail < -1); 17 | } 18 | 19 | void QueueEnqueue(int atom){ // insert int at end of queue 20 | assert(queueObject.tail < MAXITEMS - 1); 21 | queueObject.tail ++; 22 | queueObject.item[queueObject.tail] = atom; 23 | } 24 | 25 | int QueueDequeue(){ // remove int from front of queue 26 | assert(queueObject.tail > -1); 27 | int i = queueObject.item[0]; 28 | 29 | for (int j = 0; j < queueObject.tail; j ++){ 30 | queueObject.item[j] = queueObject.item[j + 1]; 31 | } 32 | 33 | queueObject.tail --; 34 | return i; 35 | } 36 | -------------------------------------------------------------------------------- /Problem Set/Week 01b/5.c: -------------------------------------------------------------------------------- 1 | 5.a 2 | int data[12] = {5, 3, 6, 2, 7, 4, 9, 1, 8}; 3 | and assuming that &data[0] == 0x10000, what are the values of the following expressions? 4 | 5 | Titles Answers 6 | data + 4 0x10000 + 4*4 = 0x10010 7 | *data + 4 5 + 4 = 9 8 | *(data + 4) 7 9 | data[4] 7 10 | *(data + *(data + 3)) 6 11 | data[data[2]] 9 12 | 13 | 5.b 14 | typedef struct { 15 | int studentID; 16 | int age; 17 | char gender; 18 | float WAM; 19 | } PersonT; 20 | 21 | PersonT per1; 22 | PersonT per2; 23 | PersonT *ptr; 24 | 25 | ptr = &per1; 26 | per1.studentID = 3141592; 27 | ptr->gender = 'M'; 28 | ptr = &per2; 29 | ptr->studentID = 2718281; 30 | ptr->gender = 'F'; 31 | per1.age = 25; 32 | per2.age = 24; 33 | ptr = &per1; 34 | per2.WAM = 86.0; 35 | ptr->WAM = 72.625; 36 | What are the values of the fields in the per1 and per2 record after execution of the above statements? 37 | per1.studentID = 3141592; 38 | per1.age = 25; 39 | per1.gender = 'M'; 40 | per1.WAM = 72.625; 41 | 42 | per2->studentID = 2718281; 43 | per2->gender = 'F'; 44 | per2.age = 24; 45 | per2.WAM = 86.0; -------------------------------------------------------------------------------- /Problem Set/Week 01b/6.c: -------------------------------------------------------------------------------- 1 | #include "stdio.h" 2 | #include "stdlib.h" 3 | #include "string.h" 4 | 5 | int main(int argc, char const *argv[]) 6 | { 7 | for (int i = strlen(argv[1]); i > 0; i--){ 8 | for (int j = 0; j < i; j++){ 9 | printf("%c", argv[1][j]); 10 | } 11 | printf("\n"); 12 | } 13 | return 0; 14 | } 15 | -------------------------------------------------------------------------------- /Problem Set/Week 01b/Queue.h: -------------------------------------------------------------------------------- 1 | // Integer Queue ADO header file 2 | void QueueInit(); // set up empty queue 3 | int QueueIsEmpty(); // check whether queue is empty 4 | void QueueEnqueue(int); // insert int at end of queue 5 | int QueueDequeue(); // remove int from front of queue -------------------------------------------------------------------------------- /Problem Set/Week 01b/Stack.h: -------------------------------------------------------------------------------- 1 | // Stack ADO header file ... COMP9024 2 | 3 | void StackInit(); // set up empty stack 4 | int StackIsEmpty(); // check whether stack is empty 5 | void StackPush(int); // insert char on top of stack 6 | int StackPop(); // remove integer from top of stack 7 | -------------------------------------------------------------------------------- /Problem Set/Week 02a/1.c: -------------------------------------------------------------------------------- 1 | #include "stdio.h" 2 | #include "stdlib.h" 3 | 4 | /* Makes an array of 10 integers and returns a pointer to it */ 5 | 6 | int *makeArrayOfInts(void) { 7 | int * arr; 8 | arr = malloc(10 * sizeof(int)); 9 | int i; 10 | for (i=0; i<10; i++) { 11 | arr[i] = i; 12 | } 13 | return arr; 14 | } 15 | 16 | int main(int argc, char const *argv[]) 17 | { 18 | int * arrays = makeArrayOfInts(); 19 | for (int i = 0; i < 10; i ++){ 20 | printf("%d\n", arrays[i]); 21 | } 22 | free(arrays); 23 | return 0; 24 | } 25 | -------------------------------------------------------------------------------- /Problem Set/Week 02a/2.c: -------------------------------------------------------------------------------- 1 | // Memory management 2 | #include 3 | #include 4 | 5 | void func(int **a) { 6 | *a = malloc(sizeof(int)); 7 | } 8 | 9 | int main(void) { 10 | int *p; 11 | func(&p); 12 | *p = 6; 13 | printf("%d\n",*p); 14 | free(p); 15 | return 0; 16 | } -------------------------------------------------------------------------------- /Problem Set/Week 02a/3.c: -------------------------------------------------------------------------------- 1 | //Dynamic arrays 2 | /*Write a C-program that uses a dynamic array of 3 | unsigned long long int numbers (8 bytes, only positive numbers) to compute 4 | the n'th Fibonacci number, where n is given as command line argument. 5 | For example, ./fib 60 should result in 1548008755920. 6 | */ 7 | 8 | #include "stdio.h" 9 | #include "stdlib.h" 10 | 11 | int main(int argc, char const *argv[]) 12 | { 13 | int serial, i; 14 | if (argc != 2) { 15 | fprintf(stderr, "Stderr: %s\n", argv[0]); 16 | return 1; 17 | } 18 | serial = atoi(argv[1]); 19 | 20 | unsigned long long int * Fib = malloc(serial * sizeof(unsigned long long int)); 21 | 22 | Fib[0] = 1; 23 | Fib[1] = 1; 24 | 25 | for (i = 2; i < serial; i++){ 26 | Fib[i] = Fib[i-1] + Fib[i-2]; 27 | } 28 | 29 | printf("%lld\n", Fib[serial - 1]); 30 | free(Fib); 31 | return 0; 32 | } 33 | -------------------------------------------------------------------------------- /Problem Set/Week 02a/4.c: -------------------------------------------------------------------------------- 1 | /*a.In the stack ADT, elements are added to ("push") and removed from ("pop") 2 | the beginning of the linked list. For a queue, we have two options: either 3 | we add ("enqueue") new elements at the end and continue to take elements off 4 | ("dequeue") from the beginning. Or we continue to add elements at the beginning and 5 | dequeue from the end. Operating on both ends will be more efficient if we use a 6 | datastructure with two pointers: one pointing to the first and one pointing to the 7 | last element of a list. 8 | 9 | b.The solution is to use the queue Q to process the elements in two phases. 10 | In the first phase, we iteratively pop all the elements from S and enqueue them in Q, 11 | then dequeue the elements from Q and push them back onto S. As a result, 12 | all the elements are now in reversed order on S. In the second phase, we again 13 | pop all the elements from S, but this time we also look for the element x. 14 | By again passing the elements through Q and back onto S, we reverse the reversal, 15 | thereby restoring the original order of the elements on S.*/ -------------------------------------------------------------------------------- /Problem Set/Week 02a/6.c: -------------------------------------------------------------------------------- 1 | #include "stdio.h" 2 | #include "stdlib.h" 3 | #include "6.h" 4 | 5 | int main(int argc, char const *argv[]) 6 | { 7 | NodeT * all = NULL; 8 | int value; 9 | 10 | printf("Enter an integer: "); 11 | while (scanf("%d", &value) != 0){ 12 | NodeT * new = makeNode(value); 13 | all = joinLL(all, new); 14 | printf("Enter an integer: "); 15 | } 16 | 17 | if (all == NULL){ 18 | printf("First half is"); 19 | printf("\nSecond half is"); 20 | } 21 | else{ 22 | // half and second are two pointer, point to all 23 | NodeT * half = malloc(sizeof(NodeT)); 24 | NodeT * second = malloc(sizeof(NodeT)); 25 | half -> next = all; 26 | second -> next = all; 27 | 28 | // divide all into two linked list, half is first one, second is last one 29 | // second move two steps when half move one step each time 30 | while (second -> next != NULL){ 31 | half = half -> next; 32 | second = second -> next; 33 | if (second -> next != NULL) 34 | second = second -> next; 35 | else 36 | break; 37 | } 38 | second = half -> next; 39 | 40 | half -> next = NULL; 41 | printf("First half is "); 42 | showLL(all); 43 | printf("\nSecond half is "); 44 | showLL(second); 45 | } 46 | return 0; 47 | } 48 | -------------------------------------------------------------------------------- /Problem Set/Week 02a/6.h: -------------------------------------------------------------------------------- 1 | #include "stdio.h" 2 | #include "stdlib.h" 3 | #include "assert.h" 4 | 5 | typedef struct node { 6 | struct node * next; 7 | int data; 8 | }NodeT; 9 | 10 | NodeT *makeNode(int value){ 11 | NodeT * nd = malloc(sizeof(NodeT)); 12 | assert(nd != NULL); 13 | nd -> data = value; 14 | nd -> next = NULL; 15 | 16 | return nd; 17 | } 18 | 19 | void freeLL(NodeT *list) { 20 | NodeT *p = list; 21 | while (p != NULL) { 22 | NodeT *temp = p->next; 23 | free(p); 24 | p = temp; 25 | } 26 | } 27 | 28 | void showLL(NodeT *head){ 29 | NodeT * cursor = head; 30 | while (cursor != NULL){ 31 | printf("%d",cursor -> data); 32 | cursor = cursor -> next; 33 | if (cursor != NULL){ 34 | printf("->"); 35 | } 36 | } 37 | } 38 | 39 | NodeT *joinLL(NodeT *head1, NodeT *head2){ 40 | if (head1 == NULL){ 41 | head1 = head2; 42 | } 43 | else{ 44 | NodeT * cursor = head1; 45 | while (cursor -> next != NULL){ 46 | cursor = cursor -> next; 47 | } 48 | cursor -> next = head2; 49 | } 50 | return head1; 51 | } 52 | -------------------------------------------------------------------------------- /Problem Set/Week 02a/llbuild.c: -------------------------------------------------------------------------------- 1 | //Dynamic linked lists 2 | #include "stdio.h" 3 | #include "stdlib.h" 4 | #include "assert.h" 5 | 6 | typedef struct node { 7 | struct node * next; 8 | int data; 9 | }NodeT; 10 | 11 | NodeT *makeNode(int value){ 12 | NodeT * nd = malloc(sizeof(NodeT)); 13 | assert(nd != NULL); 14 | nd -> data = value; 15 | nd -> next = NULL; 16 | 17 | return nd; 18 | } 19 | 20 | void freeLL(NodeT *list) { 21 | NodeT *p = list; 22 | while (p != NULL) { 23 | NodeT *temp = p->next; 24 | free(p); 25 | p = temp; 26 | } 27 | } 28 | 29 | void showLL(NodeT *head){ 30 | NodeT * cursor = head; 31 | while (cursor != NULL){ 32 | printf("%d",cursor -> data); 33 | cursor = cursor -> next; 34 | if (cursor != NULL){ 35 | printf("->"); 36 | } 37 | } 38 | } 39 | 40 | NodeT *joinLL(NodeT *head1, NodeT *head2){ 41 | if (head1 == NULL){ 42 | head1 = head2; 43 | } 44 | else{ 45 | NodeT * cursor = head1; 46 | while (cursor -> next != NULL){ 47 | cursor = cursor -> next; 48 | } 49 | cursor -> next = head2; 50 | } 51 | return head1; 52 | } 53 | 54 | int main(int argc, char const *argv[]) 55 | { 56 | NodeT * all = NULL; 57 | int value; 58 | 59 | printf("Enter a integer: "); 60 | while (scanf("%d", &value) == 1){ 61 | NodeT * new = makeNode(value); 62 | all = joinLL(all, new); 63 | printf("Enter a integer: "); 64 | } 65 | 66 | printf("Finished."); 67 | if (all == NULL) 68 | exit(0); 69 | else{ 70 | printf(" List is: "); 71 | showLL(all); 72 | } 73 | free(all); 74 | 75 | return 0; 76 | } 77 | -------------------------------------------------------------------------------- /Problem Set/week3a/1.txt: -------------------------------------------------------------------------------- 1 | a.path 2 | smallest: any path with one edge (e.g. a-b or g-m) 3 | largest: some path including all nodes (e.g. m-g-h-k-i-j-a-b-c-d-e-f) 4 | 5 | b.cycle 6 | smallest: need at least 3 nodes (e.g. i-j-k-i or h-i-k-h) 7 | largest: path including most nodes (e.g. g-h-k-i-j-a-b-c-d-e-f-g) (can't involve m) 8 | 9 | c.spanning tree 10 | smallest: any spanning tree must include all nodes (the largest path above is an example) 11 | largest: same 12 | 13 | d.vertex degree 14 | smallest: there is a node that has degree 1 (vertex m) 15 | largest: in this graph, 5 (b or f) 16 | 17 | e.clique 18 | smallest: any vertex by itself is a clique of size 1 19 | largest: this graph has a clique of size 5 (nodes b,c,d,e,f) -------------------------------------------------------------------------------- /Problem Set/week3a/2.c: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/brmuch/COMP9024/094852af15dca9d5d9fa34d492a4415a476d812e/Problem Set/week3a/2.c -------------------------------------------------------------------------------- /Problem Set/week3a/4.txt: -------------------------------------------------------------------------------- 1 | adjacent(g,v,w): 2 | Input graph g in upper-triangle matrix representation 3 | v, w vertices such that v≠w 4 | Output true if v and w adjacent in g, false otherwise 5 | 6 | if v>w then 7 | swap v and w // to ensure v= 2, then the graph hasCycle 8 | -------------------------------------------------------------------------------- /Problem Set/week4/4a.c: -------------------------------------------------------------------------------- 1 | // DFS traverling all graph 2 | #include "stdio.h" 3 | #include "stdlib.h" 4 | #include "string.h" 5 | #include "Graph.h" 6 | #include "stack.h" 7 | #define SIZE 1000 8 | 9 | // Function used for sorting 10 | int comp(const void*a,const void*b) 11 | { 12 | return *(int*)a-*(int*)b; 13 | } 14 | 15 | extern bool IsTravel(int *compo, int v, int length); 16 | 17 | void components(Graph g){ 18 | int all_traverl[SIZE]; // initial 19 | int compo[SIZE]; 20 | int size = 0, all_size = 0, part = 1; 21 | stack st = newStack(); 22 | 23 | for (int i = 0; i < g->nV;) { 24 | StackPush(st, i); 25 | // sign all nodes connected to nodes in the stack 26 | while (!StackIsEmpty(st)){ 27 | int p = StackPop(st); 28 | compo[size] = p; 29 | all_traverl[all_size] = p; 30 | size ++; 31 | all_size ++; 32 | 33 | for (int k = p + 1; k < g->nV; k ++) { 34 | if (g->edges[p][k] != 0){ 35 | if (!IsTravel(compo, k, size)){ 36 | StackPush(st, k); 37 | } 38 | g->edges[p][k] = 0; 39 | } 40 | } 41 | } 42 | // print components 43 | qsort(compo, size, sizeof(int), comp); 44 | printf("Component %d:\n", part); 45 | for (int k = 0; k < size; k ++) { 46 | printf("%d\n", compo[k]); 47 | } 48 | 49 | size = 0; 50 | do{ 51 | i ++; 52 | }while (IsTravel(all_traverl, i, all_size)); 53 | part ++; 54 | } 55 | printf("Number of components: %d", part - 1); 56 | } 57 | 58 | // determine whether add node already traverling 59 | bool IsTravel(int *compo, int v, int length) { 60 | for (int i = 0; i < length; i ++) { 61 | if (compo[i] == v){ 62 | return true; 63 | } 64 | } 65 | return false; 66 | } 67 | 68 | // Main Function 69 | int main(int argc, char **argv){ 70 | int num; // Number of Vertices 71 | char buff[SIZE]; // Input BUFF 72 | 73 | printf("Enter the number of vertices: "); 74 | scanf("%d", &num); 75 | Graph g = newGraph(num); 76 | 77 | printf("Enter an edge (from): "); 78 | scanf("%s", buff); 79 | while (strcmp(buff, "done") != 0){ 80 | Edge e; 81 | e.v = atoi(buff); // v 82 | 83 | printf("Enter an edge (to): "); 84 | scanf("%s", buff); 85 | e.w = atoi(buff); // w 86 | insertEdge(g, e); // insert Edge to Graph 87 | 88 | printf("Enter an edge (from): "); 89 | scanf("%s", buff); 90 | } 91 | printf("Finished.\n"); 92 | 93 | components(g); 94 | return 0; 95 | } -------------------------------------------------------------------------------- /Problem Set/week4/4b.doc: -------------------------------------------------------------------------------- 1 | 1. edge d was removed 2 | cc[] array doesn't change 3 | 4 | 2. edge b was removed 5 | cc[] array will change to 6 | cc[] = {0, 0, 1, 2, 2, 2, 1, 0, 1, 2} -------------------------------------------------------------------------------- /Problem Set/week4/Graph.c: -------------------------------------------------------------------------------- 1 | // Graph ADT 2 | // Adjacency Matrix Representation ... COMP9024 17s2 3 | // undirected Grapy 4 | #include "Graph.h" 5 | #include 6 | #include 7 | #include 8 | 9 | Graph newGraph(int V) { 10 | assert(V >= 0); 11 | int i; 12 | 13 | Graph g = malloc(sizeof(GraphRep)); 14 | assert(g != NULL); 15 | g->nV = V; 16 | g->nE = 0; 17 | 18 | // allocate memory for each row 19 | g->edges = malloc(V * sizeof(int *)); 20 | assert(g->edges != NULL); 21 | // allocate memory for each column and initialise with 0 22 | for (i = 0; i < V; i++) { 23 | g->edges[i] = calloc(V, sizeof(int)); 24 | assert(g->edges[i] != NULL); 25 | } 26 | 27 | return g; 28 | } 29 | 30 | // check if vertex is valid in a graph 31 | bool validV(Graph g, Vertex v) { 32 | return (g != NULL && v >= 0 && v < g->nV); 33 | } 34 | 35 | void insertEdge(Graph g, Edge e) { 36 | assert(g != NULL && validV(g,e.v) && validV(g,e.w)); 37 | 38 | if (!g->edges[e.v][e.w]) { // edge e not in graph 39 | g->edges[e.v][e.w] = 1; 40 | g->edges[e.w][e.v] = 1; 41 | g->nE++; 42 | } 43 | } 44 | 45 | void removeEdge(Graph g, Edge e) { 46 | assert(g != NULL && validV(g,e.v) && validV(g,e.w)); 47 | 48 | if (g->edges[e.v][e.w]) { // edge e in graph 49 | g->edges[e.v][e.w] = 0; 50 | g->edges[e.w][e.v] = 0; 51 | g->nE--; 52 | } 53 | } 54 | 55 | bool adjacent(Graph g, Vertex v, Vertex w) { 56 | assert(g != NULL && validV(g,v) && validV(g,w)); 57 | 58 | return (g->edges[v][w] != 0); 59 | } 60 | 61 | void showGraph(Graph g) { 62 | assert(g != NULL); 63 | int i, j; 64 | 65 | printf("Number of vertices: %d\n", g->nV); 66 | printf("Number of edges: %d\n", g->nE); 67 | for (i = 0; i < g->nV; i++) 68 | for (j = i+1; j < g->nV; j++) 69 | if (g->edges[i][j]) 70 | printf("Edge %d - %d\n", i, j); 71 | } 72 | 73 | void freeGraph(Graph g) { 74 | assert(g != NULL); 75 | 76 | int i; 77 | for (i = 0; i < g->nV; i++) 78 | free(g->edges[i]); 79 | free(g->edges); 80 | free(g); 81 | } -------------------------------------------------------------------------------- /Problem Set/week4/Graph.h: -------------------------------------------------------------------------------- 1 | // Graph ADT interface ... COMP9024 17s2 2 | #include 3 | 4 | typedef struct GraphRep { 5 | int **edges; // adjacency matrix 6 | int nV; // #vertices 7 | int nE; // #edges 8 | } GraphRep; 9 | 10 | typedef struct GraphRep *Graph; 11 | 12 | // vertices are ints 13 | typedef int Vertex; 14 | 15 | // edges are pairs of vertices (end-points) 16 | typedef struct Edge { 17 | Vertex v; 18 | Vertex w; 19 | } Edge; 20 | 21 | Graph newGraph(int); 22 | void insertEdge(Graph, Edge); 23 | void removeEdge(Graph, Edge); 24 | bool adjacent(Graph, Vertex, Vertex); 25 | void showGraph(Graph); 26 | void freeGraph(Graph); -------------------------------------------------------------------------------- /Problem Set/week4/Problem set 4.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/brmuch/COMP9024/094852af15dca9d5d9fa34d492a4415a476d812e/Problem Set/week4/Problem set 4.pdf -------------------------------------------------------------------------------- /Problem Set/week4/stack.c: -------------------------------------------------------------------------------- 1 | // Stack ADT implementation ... COMP9024 17s2 2 | #include 3 | #include 4 | #include "stack.h" 5 | 6 | 7 | // set up empty stack 8 | stack newStack() { 9 | stack S = malloc(sizeof(StackRep)); 10 | S->height = 0; 11 | S->top = NULL; 12 | return S; 13 | } 14 | 15 | // remove unwanted stack 16 | void dropStack(stack S) { 17 | NodeT *curr = S->top; 18 | while (curr != NULL) { 19 | NodeT *temp = curr->next; 20 | free(curr); 21 | curr = temp; 22 | } 23 | free(S); 24 | } 25 | 26 | // check whether stack is empty 27 | int StackIsEmpty(stack S) { 28 | return (S->height == 0); 29 | } 30 | 31 | // insert an int on top of stack 32 | void StackPush(stack S, int v) { 33 | NodeT *new = malloc(sizeof(NodeT)); 34 | assert(new != NULL); 35 | new->data = v; 36 | new->next = S->top; 37 | S->top = new; 38 | S->height++; 39 | } 40 | 41 | // remove int from top of stack 42 | int StackPop(stack S) { 43 | assert(S->height > 0); 44 | NodeT *head = S->top; 45 | S->top = S->top->next; 46 | S->height--; 47 | int d = head->data; 48 | free(head); 49 | return d; 50 | } -------------------------------------------------------------------------------- /Problem Set/week4/stack.h: -------------------------------------------------------------------------------- 1 | // Stack ADT header file ... COMP9024 17s2 2 | typedef struct node { 3 | int data; 4 | struct node *next; 5 | } NodeT; 6 | 7 | typedef struct StackRep { 8 | int height; 9 | NodeT *top; 10 | } StackRep; 11 | 12 | typedef struct StackRep *stack; 13 | 14 | stack newStack(); // set up empty stack 15 | void dropStack(stack); // remove unwanted stack 16 | int StackIsEmpty(stack); // check whether stack is empty 17 | void StackPush(stack, int); // insert an int on top of stack 18 | int StackPop(stack); // remove int from top of stack -------------------------------------------------------------------------------- /Problem Set/week5/1.doc: -------------------------------------------------------------------------------- 1 | a. adjacency matrix representation 2 | Graph 1 Graph 2 3 | 0 1 0 0 0 0 0 2 0 0 0 4 4 | 0 0 0 0 0 1 2 0 0 0 0 3 5 | 0 0 0 0 0 0 0 0 0 0 0 5 6 | 0 0 0 0 0 1 0 0 0 0 0 2 7 | 0 0 0 0 0 0 0 0 0 0 0 1 8 | 1 1 1 1 1 0 4 3 5 2 1 0 9 | 10 | b. adjacency list representation 11 | Graph 1 12 | 0->1 13 | 1->5 14 | 2 15 | 3->5 16 | 4 17 | 5->0->1->2->3->4 18 | 19 | Graph 2 20 | 0->1, 2->5, 4 21 | 1->0, 2->5, 3 22 | 2->5, 5 23 | 3->5, 2 24 | 4->5, 1 25 | 5->0, 4->1, 3->2, 5->3, 2->4, 1 26 | -------------------------------------------------------------------------------- /Problem Set/week5/2.doc: -------------------------------------------------------------------------------- 1 | // MST – Kruskal's algorithm 2 | a. 3 | 1---2 4 | \ 5 | 3---4 6 6 | \ / 7 | 6---7 8 | of course, I use Kruskal's algorithm 9 | 10 | b. 11 | The spanning tree constructed by Kruskal's algorithm 12 | 1---2 13 | \ 14 | 3---4 6 15 | \ / 16 | 6---7 17 | and 9 edges I consider. 18 | 19 | c. 20 | For a graph G=(V, E), the least number of edges considered by Kruskal's Algorithm is V-1; 21 | the most number of edges are all E.The worst case would be when we had to consider all E edges. 22 | If we added a vertex 8 to the graph, and connected it to vertex 5 with edge cost 11 (or any cost larger than all the other edge costs in the graph). 23 | (if (5,8) is before (2,5) in the list and after including (5,8) all nodes are included. so must greater than 10) -------------------------------------------------------------------------------- /Problem Set/week5/3.doc: -------------------------------------------------------------------------------- 1 | // MST – Prim's algorithm 2 | start from vertice 0 3 | edges: 4 | 0-2 5 | 9-7 6 | 7-1 7 | 7-6 8 | 7-4 9 | 4-3 10 | 3-5 11 | -------------------------------------------------------------------------------- /Problem Set/week5/5.doc: -------------------------------------------------------------------------------- 1 | a. Dijkstra's algorithm 2 | 3 | start from node 0 4 | vset = {0, 1, 2, 3, 4, 5, 6, 7} 5 | dist[] 0 ∞ ∞ ∞ ∞ ∞ ∞ ∞ 6 | pred[] - - - - - - - - 7 | 8 | vset = {1, 2, 3, 4, 5, 6, 7} 9 | dist[] 0 5 4 6 ∞ ∞ ∞ ∞ 10 | pred[] - 0 0 0 - - - - 11 | 12 | vset = {1, 3, 4, 5, 6, 7} 13 | dist[] 0 5 4 5 7 11 ∞ ∞ 14 | pred[] - 0 0 2 2 2 - - 15 | 16 | vset = {3, 4, 5, 6, 7} 17 | dist[] 0 5 4 5 7 7 12 ∞ 18 | pred[] - 0 0 2 2 1 1 - 19 | 20 | vset = {4, 5, 6, 7} 21 | dist[] 0 5 4 5 7 7 12 ∞ 22 | pred[] - 0 0 2 2 1 1 - 23 | 24 | vset = {5, 6, 7} 25 | dist[] 0 5 4 5 7 7 12 15 26 | pred[] - 0 0 2 2 1 1 4 27 | 28 | vset = {6, 7} 29 | dist[] 0 5 4 5 7 7 10 13 30 | pred[] - 0 0 2 2 1 5 5 31 | 32 | vset = {7} 33 | dist[] 0 5 4 5 7 7 10 13 34 | pred[] - 0 0 2 2 1 5 5 35 | 36 | so we can know the simplest route to every node: 37 | 0: 0 38 | 1: 0-1 39 | 2: 0-2 40 | 3: 0-2-3 41 | 4: 0-2-4 42 | 5: 0-1-5 43 | 6: 0-1-5-6 44 | 7: 0-1-5-7 -------------------------------------------------------------------------------- /Problem Set/week5/Problem set 5.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/brmuch/COMP9024/094852af15dca9d5d9fa34d492a4415a476d812e/Problem Set/week5/Problem set 5.pdf -------------------------------------------------------------------------------- /Problem Set/week6a/1a.doc: -------------------------------------------------------------------------------- 1 | a. 2 | h=⌈log2(n+1)⌉−1 3 | -------------------------------------------------------------------------------- /Problem Set/week6a/1b.c: -------------------------------------------------------------------------------- 1 | // implement the function int TreeHeight(Tree t) 2 | #include "stdio.h" 3 | #include "stdlib.h" 4 | #include "BSTree.h" 5 | 6 | int main(int argc, char **argv){ 7 | Tree t = newTree(); 8 | t = TreeInsert(t, 10); 9 | t = TreeInsert(t, 5); 10 | t = TreeInsert(t, 6); 11 | t = TreeInsert(t, 8); 12 | t = TreeInsert(t, 1); 13 | t = TreeInsert(t, 9); 14 | t = TreeInsert(t, 5); 15 | printf("The Height of Tree is %d.", TreeHeight(t)); 16 | return 0; 17 | } -------------------------------------------------------------------------------- /Problem Set/week6a/2.doc: -------------------------------------------------------------------------------- 1 | a. 2 | One obvious class of trees with this property is "right-deep" trees. 3 | Such trees have no left sub-trees on any node 4 | Empty trees and trees with just one node(root node) have all output orders the same. 5 | 6 | b. 7 | #include "stdio.h" 8 | #include "stdlib.h" 9 | #include "string.h" 10 | 11 | void TreeTraversal(tree,style){ 12 | if (tree == NULL) 13 | return; 14 | else{ 15 | if (!strcmp(style,"NLR")) 16 | printf("%d\n", tree->data); 17 | 18 | TreeTraversal(tree->left); 19 | 20 | if (!strcmp(style,"LNR")) 21 | printf("%d\n", tree->data); 22 | 23 | TreeTraversal(tree->right); 24 | 25 | if (!strcmp(style,"LRN")) 26 | printf("%d\n", tree->data); 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /Problem Set/week6a/3.doc: -------------------------------------------------------------------------------- 1 | // Insertion and deletion 2 | a. 3 | insert 6 2 4 10 12 8 1 4 | 6 6 6 6 6 6 6 5 | / / / \ / \ / \ / \ 6 | 2 2 2 10 2 10 2 10 2 10 7 | \ \ \ \ \ /\ / \ /\ 8 | 4 4 4 12 4 8 12 1 4 8 12 9 | 10 | 11 | b. 12 | TreeDelete(t,12); 13 | 6 14 | / \ 15 | 2 10 16 | / \ / 17 | 1 4 8 18 | TreeDelete(t,6); 19 | 8 20 | / \ 21 | 2 10 22 | / \ 23 | 1 4 24 | TreeDelete(t,2); 25 | 8 26 | / \ 27 | 4 10 28 | / 29 | 1 30 | TreeDelete(t,4); 31 | 8 32 | / \ 33 | 1 10 -------------------------------------------------------------------------------- /Problem Set/week6a/4.doc: -------------------------------------------------------------------------------- 1 | // Insertion at root 2 | a. 3 | 1 2 3 4 5 6 4 | The tree resulting from inserting these values "at leaf" 5 | 1 6 | \ 7 | 2 8 | \ 9 | 3 10 | \ 11 | 4 12 | \ 13 | 5 14 | \ 15 | 6 16 | The tree resulting from inserting these values "at root" 17 | 6 18 | / 19 | 5 20 | / 21 | 4 22 | / 23 | 3 24 | / 25 | 2 26 | / 27 | 1 28 | The tree resulting from alternating between at-leaf-insertion and at-root-insertion 29 | 6 30 | / 31 | 4 32 | / \ 33 | 2 5 34 | / \ 35 | 1 3 36 | the resulting tree will be of height floor(n/2). 37 | 38 | b. 39 | Tree insertAtRoot(Tree t, Item it) { 40 | if (t == NULL) { 41 | t = newNode(it); 42 | } else if (it < data(t)) { 43 | left(t) = insertAtRoot(left(t), it); 44 | t = rotateRight(t); 45 | } else if (it > data(t)) { 46 | right(t) = insertAtRoot(right(t), it); 47 | t = rotateLeft(t); 48 | } 49 | return t; 50 | } 51 | 52 | Tree rotateLeft(Tree t){ 53 | if (t == NULL || t->right == NULL) 54 | return t; 55 | Tree right = t->right; 56 | t->right = right->left; 57 | right->left = t; 58 | 59 | return right; 60 | } 61 | 62 | Tree rotateRight(Tree t){ 63 | if (t == NULL || t->left == NULL) 64 | return t; 65 | Tree left = t->left; 66 | t->left = left->right; 67 | left->right = t; 68 | 69 | return left; 70 | } -------------------------------------------------------------------------------- /Problem Set/week6a/5.doc: -------------------------------------------------------------------------------- 1 | // ReBalancing Tree 2 | 3 | rebalance(t); 4 | step 1: skip if tree node < 3, else do step 2 5 | step 2: partition(t, floor(n / 2)); // put node with median key at root 6 | step 3: rebalance(t->left) 7 | step 4: rebalance(t->right) 8 | 9 | 2 2 8 8 10 | \ \ / \ / \ 11 | 4 8 2 10 4 10 12 | \ / \ \ \ / \ \ 13 | 8 4 10 4 12 2 6 12 14 | / \ \ \ \ 15 | 6 10 6 12 6 16 | \ 17 | 12 -------------------------------------------------------------------------------- /Problem Set/week6a/BSTree.c: -------------------------------------------------------------------------------- 1 | // Binary Search Tree ADT implementation ... COMP9024 17s2 2 | 3 | #include 4 | #include 5 | #include 6 | #include "BSTree.h" 7 | 8 | #define data(tree) ((tree)->data) 9 | #define left(tree) ((tree)->left) 10 | #define right(tree) ((tree)->right) 11 | 12 | typedef struct Node { 13 | int data; 14 | Tree left, right; 15 | } Node; 16 | 17 | // make a new node containing data 18 | Tree newNode(Item it) { 19 | Tree new = malloc(sizeof(Node)); 20 | assert(new != NULL); 21 | data(new) = it; 22 | left(new) = right(new) = NULL; 23 | return new; 24 | } 25 | 26 | // create a new empty Tree 27 | Tree newTree() { 28 | return NULL; 29 | } 30 | 31 | // free memory associated with Tree 32 | void freeTree(Tree t) { 33 | if (t != NULL) { 34 | freeTree(left(t)); 35 | freeTree(right(t)); 36 | free(t); 37 | } 38 | } 39 | 40 | // display Tree sideways 41 | void showTreeR(Tree t, int depth) { 42 | if (t != NULL) { 43 | showTreeR(right(t), depth+1); 44 | int i; 45 | for (i = 0; i < depth; i++) 46 | putchar('\t'); // TAB character 47 | printf("%d\n", data(t)); 48 | showTreeR(left(t), depth+1); 49 | } 50 | } 51 | 52 | void showTree(Tree t) { 53 | showTreeR(t, 0); 54 | } 55 | 56 | // compute height of Tree 57 | int TreeHeight(Tree t) { 58 | if (t == NULL) 59 | return -1; 60 | else 61 | return TreeHeight(t->left) > TreeHeight(t->right)? TreeHeight(t->left) + 1:TreeHeight(t->right) + 1; 62 | } 63 | 64 | // count #nodes in Tree 65 | int TreeNumNodes(Tree t) { 66 | if (t == NULL) 67 | return 0; 68 | else 69 | return 1 + TreeNumNodes(left(t)) + TreeNumNodes(right(t)); 70 | } 71 | 72 | // check whether a key is in a Tree 73 | bool TreeSearch(Tree t, Item it) { 74 | if (t == NULL) 75 | return false; 76 | else if (it < data(t)) 77 | return TreeSearch(left(t), it); 78 | else if (it > data(t)) 79 | return TreeSearch(right(t), it); 80 | else // it == data(t) 81 | return true; 82 | } 83 | 84 | // insert a new item into a Tree 85 | Tree TreeInsert(Tree t, Item it) { 86 | if (t == NULL) 87 | t = newNode(it); 88 | else if (it < data(t)) 89 | left(t) = TreeInsert(left(t), it); 90 | else if (it > data(t)) 91 | right(t) = TreeInsert(right(t), it); 92 | return t; 93 | } 94 | 95 | Tree joinTrees(Tree t1, Tree t2) { 96 | if (t1 == NULL) 97 | return t2; 98 | else if (t2 == NULL) 99 | return t1; 100 | else { 101 | Tree curr = t2; 102 | Tree parent = NULL; 103 | while (left(curr) != NULL) { // find min element in t2 104 | parent = curr; 105 | curr = left(curr); 106 | } 107 | if (parent != NULL) { 108 | left(parent) = right(curr); // unlink min element from parent 109 | right(curr) = t2; 110 | } 111 | left(curr) = t1; 112 | return curr; // min element is new root 113 | } 114 | } 115 | 116 | // delete an item from a Tree 117 | Tree TreeDelete(Tree t, Item it) { 118 | if (t != NULL) { 119 | if (it < data(t)) 120 | left(t) = TreeDelete(left(t), it); 121 | else if (it > data(t)) 122 | right(t) = TreeDelete(right(t), it); 123 | else { 124 | Tree new; 125 | if (left(t) == NULL && right(t) == NULL) 126 | new = NULL; 127 | else if (left(t) == NULL) // if only right subtree, make it the new root 128 | new = right(t); 129 | else if (right(t) == NULL) // if only left subtree, make it the new root 130 | new = left(t); 131 | else // left(t) != NULL and right(t) != NULL 132 | new = joinTrees(left(t), right(t)); 133 | free(t); 134 | t = new; 135 | } 136 | } 137 | return t; 138 | } 139 | 140 | Tree rotateRight(Tree n1) { 141 | if (n1 == NULL || left(n1) == NULL) 142 | return n1; 143 | Tree n2 = left(n1); 144 | left(n1) = right(n2); 145 | right(n2) = n1; 146 | return n2; 147 | } 148 | 149 | Tree rotateLeft(Tree n2) { 150 | if (n2 == NULL || right(n2) == NULL) 151 | return n2; 152 | Tree n1 = right(n2); 153 | right(n2) = left(n1); 154 | left(n1) = n2; 155 | return n1; 156 | } 157 | 158 | Tree insertAtRoot(Tree t, Item it) { 159 | 160 | printf("Not yet implemented.\n"); 161 | 162 | return t; 163 | } 164 | 165 | Tree partition(Tree t, int i) { 166 | if (t != NULL) { 167 | assert(0 <= i && i < TreeNumNodes(t)); 168 | int m = TreeNumNodes(left(t)); 169 | if (i < m) { 170 | left(t) = partition(left(t), i); 171 | t = rotateRight(t); 172 | } else if (i > m) { 173 | right(t) = partition(right(t), i-m-1); 174 | t = rotateLeft(t); 175 | } 176 | } 177 | return t; 178 | } 179 | 180 | Tree rebalance(Tree t) { 181 | int n = TreeNumNodes(t); 182 | if (n >= 3) { 183 | t = partition(t, n/2); // put node with median key at root 184 | left(t) = rebalance(left(t)); // then rebalance each subtree 185 | right(t) = rebalance(right(t)); 186 | } 187 | return t; 188 | } -------------------------------------------------------------------------------- /Problem Set/week6a/BSTree.h: -------------------------------------------------------------------------------- 1 | // Binary Search Tree ADT interface ... COMP9024 17s2 2 | 3 | #include 4 | 5 | typedef int Item; // item is just a key 6 | 7 | typedef struct Node *Tree; 8 | 9 | Tree newTree(); // create an empty Tree 10 | void freeTree(Tree); // free memory associated with Tree 11 | void showTree(Tree); // display a Tree (sideways) 12 | 13 | bool TreeSearch(Tree, Item); // check whether an item is in a Tree 14 | int TreeHeight(Tree); // compute height of Tree 15 | int TreeNumNodes(Tree); // count #nodes in Tree 16 | Tree TreeInsert(Tree, Item); // insert a new item into a Tree 17 | Tree TreeDelete(Tree, Item); // delete an item from a Tree 18 | 19 | // internal functions made visible for testing 20 | Tree rotateRight(Tree); 21 | Tree rotateLeft(Tree); 22 | Tree insertAtRoot(Tree, Item); 23 | Tree partition(Tree, int); 24 | Tree rebalance(Tree); -------------------------------------------------------------------------------- /Problem Set/week6a/week6a.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/brmuch/COMP9024/094852af15dca9d5d9fa34d492a4415a476d812e/Problem Set/week6a/week6a.pdf -------------------------------------------------------------------------------- /Problem Set/week6b/1.c: -------------------------------------------------------------------------------- 1 | // Week 06b Problem Set 2 | // Random Numbers, Real Balanced Trees 3 | 4 | 5 | -------------------------------------------------------------------------------- /Problem Set/week6b/2.doc: -------------------------------------------------------------------------------- 1 | // Splay trees 2 | Method: 3 | 1. every insert operation should make inserted node in the root place(through left rotate or right rotate). 4 | 2. simply moves item to root if found, or nearest node if not found 5 | 6 | a. 7 | 5 --> 3 --> 8 --> 7 --> 4 8 | \ / / \ / \ 9 | 5 3 3 8 3 7 10 | \ \ / \ 11 | 5 5 5 8 12 | 13 | b. 14 | Following steps are: 15 | SearchSplay(t,7); 16 | SearchSplay(t,8); 17 | SearchSplay(t,6); 18 | 4 --> 7 --> 8 --> 5 19 | / \ / \ / / \ 20 | 3 7 4 8 7 4 8 21 | / \ / \ / / / 22 | 5 8 3 5 4 3 7 23 | / \ 24 | 3 5 -------------------------------------------------------------------------------- /Problem Set/week6b/3.doc: -------------------------------------------------------------------------------- 1 | // AVL trees (BST Trees + rotate rules) 2 | // A tree is unbalanced when: abs(height(left)-height(right)) > 1 3 | // This can be repaired by a single rotation: 4 | // 1. if left subtree too deep, rotate right 5 | // 2. if right subtree too deep, rotate left 6 | use 12 10 8 6 4 2 create AVL tree 7 | 8 | 12 --> 12 --> 10 --> 10 --> 10 --> 6 9 | / /\ /\ /\ / \ 10 | 10 8 12 8 12 6 12 4 10 11 | / / \ / /\ 12 | 6 4 8 2 8 12 -------------------------------------------------------------------------------- /Problem Set/week6b/4.doc: -------------------------------------------------------------------------------- 1 | // 2-3-4 trees 2 | // Insertion into 2-3-4 Trees algorithms (if full then splits) 3 | 4 | a. insert 1 2 3 4 5 8 6 7 9 10 to build a new 2-3-4 trees 5 | 1 --> 1, 2 --> 1, 2, 3 --> 2 --> 2 --> 2, 4 6 | / \ / \ / / \ 7 | 1 3, 4 1 3, 4, 5 1 3 5, 6 8 | 9 | 2, 4 --> 2, 4, 6 --> 2, 4, 6 --> 4 10 | / / \ / / / \ / / / \ / \ 11 | 1 3 5, 6, 7 1 3 5 7, 8 1 3 5 7, 8, 9 2 6, 8 12 | / \ | \ \ 13 | 1 3 5 7 9, 10 14 | b. 15 | Once you have built the tree, count the number of comparisons needed to search for each of the following values in the tree: 16 | 1 7 9 13 17 | search(1) = 3 cmp 4, 2, 1 18 | search(7) = 4 cmp 4, 6, 8, 7 19 | search(9) = 4 cmp 4, 6, 8, 9 20 | search(13) = 5 cmp 4, 6, 8, 9, 10 -------------------------------------------------------------------------------- /Problem Set/week6b/5.c: -------------------------------------------------------------------------------- 1 | // Extend the BSTree ADT from the lecture (BSTree.h, BSTree.c) by an implementation of the function 2 | // Written by Ashe Mahidadia 3 | Tree AVLrepair(Tree t) { 4 | int hL = TreeHeight(left(t)); 5 | int hR = TreeHeight(right(t)); 6 | if ((hL - hR) > 1) 7 | t = rotateRight(t); 8 | else if ((hR - hL) > 1) 9 | t = rotateLeft(t); 10 | return t; 11 | } 12 | 13 | Tree deleteAVL(Tree t, Item it) { 14 | if (t != NULL) { 15 | if (it < data(t)) { 16 | left(t) = TreeDelete(left(t), it); 17 | t = AVLrepair(t); 18 | } else if (it > data(t)) { 19 | right(t) = TreeDelete(right(t), it); 20 | t = AVLrepair(t); 21 | } else { 22 | Tree new; 23 | if (left(t) == NULL && right(t) == NULL) 24 | new = NULL; 25 | else if (left(t) == NULL) // if only right subtree, make it the new root 26 | new = right(t); 27 | else if (right(t) == NULL) // if only left subtree, make it the new root 28 | new = left(t); 29 | else { // left(t) != NULL and right(t) != NULL 30 | new = joinTrees(left(t), right(t)); 31 | t = AVLrepair(new); 32 | } 33 | free(t); 34 | t = new; 35 | } 36 | } 37 | return t; 38 | } -------------------------------------------------------------------------------- /Problem Set/week6b/BSTree.c: -------------------------------------------------------------------------------- 1 | // Binary Search Tree ADT implementation ... COMP9024 17s2 2 | 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include "BSTree.h" 8 | 9 | #define RANDOM_ROOT_INSERT (random() % 10 < 4) // 40% chance 10 | 11 | #define data(tree) ((tree)->data) 12 | #define left(tree) ((tree)->left) 13 | #define right(tree) ((tree)->right) 14 | 15 | typedef struct Node { 16 | int data; 17 | Tree left, right; 18 | } Node; 19 | 20 | // make a new node containing data 21 | Tree newNode(Item it) { 22 | Tree new = malloc(sizeof(Node)); 23 | assert(new != NULL); 24 | data(new) = it; 25 | left(new) = right(new) = NULL; 26 | return new; 27 | } 28 | 29 | // create a new empty Tree 30 | Tree newTree() { 31 | return NULL; 32 | } 33 | 34 | // free memory associated with Tree 35 | void freeTree(Tree t) { 36 | if (t != NULL) { 37 | freeTree(left(t)); 38 | freeTree(right(t)); 39 | free(t); 40 | } 41 | } 42 | 43 | // display Tree horizontally 44 | // code by Jin Qu 45 | void showTreeR(Tree t, int index, int **record, int *largest) { 46 | // record largest element along the way 47 | if (t != NULL) { 48 | record[index] = &data(t); 49 | if (data(t) > *largest) 50 | *largest = data(t); 51 | showTreeR(left(t), 2 * index + 1, record, largest); 52 | showTreeR(right(t), 2 * index + 2, record, largest); 53 | } 54 | } 55 | 56 | void showTree(Tree t) { 57 | int i, h = TreeHeight(t), largest = 0; 58 | 59 | //use an array of pointers to distinguish NULL node and node with value 0 60 | int **record = calloc(pow(2, h + 1) - 1, sizeof(int*)); 61 | assert(record != NULL); 62 | showTreeR(t, 0, record, &largest); 63 | int size, lv = 0; 64 | if (largest) 65 | size = floor(log10(largest)) + 1; 66 | else 67 | size = 1; 68 | for (i = 0; i < pow(2, h + 1) - 1; i++) { 69 | int space = size * ((int)(pow(2, h - lv + 1) - 1) / 2); 70 | printf("%*s", space, ""); 71 | 72 | // centralize nodes 73 | if (record[i]) { 74 | printf("%*d", size, *record[i]); 75 | } else { 76 | printf("%*s", size, ""); 77 | } 78 | printf("%*s", space + size, ""); 79 | if (i == pow(2, lv + 1) - 2) { 80 | printf("\n\n"); 81 | lv++; 82 | } 83 | } 84 | free(record); 85 | } 86 | 87 | // compute height of Tree 88 | int TreeHeight(Tree t) { 89 | if (t == NULL) { 90 | return 0; 91 | } else { 92 | int lheight = 1 + TreeHeight(left(t)); 93 | int rheight = 1 + TreeHeight(right(t)); 94 | if (lheight > rheight) 95 | return lheight; 96 | else 97 | return rheight; 98 | } 99 | } 100 | 101 | // count #nodes in Tree 102 | int TreeNumNodes(Tree t) { 103 | if (t == NULL) 104 | return 0; 105 | else 106 | return 1 + TreeNumNodes(left(t)) + TreeNumNodes(right(t)); 107 | } 108 | 109 | // check whether a key is in a Tree 110 | bool TreeSearch(Tree t, Item it) { 111 | if (t == NULL) 112 | return false; 113 | else if (it < data(t)) 114 | return TreeSearch(left(t), it); 115 | else if (it > data(t)) 116 | return TreeSearch(right(t), it); 117 | else // it == data(t) 118 | return true; 119 | } 120 | 121 | // insert a new item into a Tree 122 | Tree TreeInsert(Tree t, Item it) { 123 | if (t == NULL) 124 | t = newNode(it); 125 | else if (it < data(t)) 126 | left(t) = TreeInsert(left(t), it); 127 | else if (it > data(t)) 128 | right(t) = TreeInsert(right(t), it); 129 | return t; 130 | } 131 | 132 | Tree joinTrees(Tree t1, Tree t2) { 133 | if (t1 == NULL) 134 | return t1; 135 | else if (t2 == NULL) 136 | return t2; 137 | else { 138 | Tree curr = t2; 139 | Tree parent = NULL; 140 | while (left(curr) != NULL) { // find min element in t2 141 | parent = curr; 142 | curr = left(curr); 143 | } 144 | if (parent != NULL) { 145 | left(parent) = right(curr); // unlink min element from parent 146 | right(curr) = t2; 147 | } 148 | left(curr) = t1; 149 | return curr; // min element is new root 150 | } 151 | } 152 | 153 | // delete an item from a Tree 154 | Tree TreeDelete(Tree t, Item it) { 155 | if (t != NULL) { 156 | if (it < data(t)) 157 | left(t) = TreeDelete(left(t), it); 158 | else if (it > data(t)) 159 | right(t) = TreeDelete(right(t), it); 160 | else { 161 | Tree new; 162 | if (left(t) == NULL && right(t) == NULL) 163 | new = NULL; 164 | else if (left(t) == NULL) // if only right subtree, make it the new root 165 | new = right(t); 166 | else if (right(t) == NULL) // if only left subtree, make it the new root 167 | new = left(t); 168 | else // left(t) != NULL and right(t) != NULL 169 | new = joinTrees(left(t), right(t)); 170 | free(t); 171 | t = new; 172 | } 173 | } 174 | return t; 175 | } 176 | 177 | Tree rotateRight(Tree n1) { 178 | if (n1 == NULL || left(n1) == NULL) 179 | return n1; 180 | Tree n2 = left(n1); 181 | left(n1) = right(n2); 182 | right(n2) = n1; 183 | return n2; 184 | } 185 | 186 | void deleteAVL(Tree t, Item it){ 187 | 188 | } 189 | 190 | Tree rotateLeft(Tree n2) { 191 | if (n2 == NULL || right(n2) == NULL) 192 | return n2; 193 | Tree n1 = right(n2); 194 | right(n2) = left(n1); 195 | left(n1) = n2; 196 | return n1; 197 | } 198 | 199 | Tree insertAtRoot(Tree t, Item it) { 200 | if (t == NULL) { 201 | t = newNode(it); 202 | } else if (it < data(t)) { 203 | left(t) = insertAtRoot(left(t), it); 204 | t = rotateRight(t); 205 | } else if (it > data(t)) { 206 | right(t) = insertAtRoot(right(t), it); 207 | t = rotateLeft(t); 208 | } 209 | return t; 210 | } 211 | 212 | Tree insertRandom(Tree t, Item it) { 213 | if (t == NULL) 214 | t = newNode(it); 215 | if (RANDOM_ROOT_INSERT) 216 | return insertAtRoot(t, it); 217 | else 218 | return TreeInsert(t, it); 219 | } 220 | 221 | Tree insertAVL(Tree t, Item it) { 222 | if (t == NULL) 223 | return newNode(it); 224 | if (it == data(t)) 225 | return t; 226 | 227 | if (it < data(t)) 228 | left(t) = insertAVL(left(t), it); 229 | else 230 | right(t) = insertAVL(right(t), it); 231 | 232 | int hL = TreeHeight(left(t)); 233 | int hR = TreeHeight(right(t)); 234 | if ((hL - hR) > 1) { 235 | if (it > data(left(t))) 236 | left(t) = rotateLeft(left(t)); 237 | t = rotateRight(t); 238 | } else if ((hR - hL) > 1) { 239 | if (it < data(right(t))) 240 | right(t) = rotateRight(right(t)); 241 | t = rotateLeft(t); 242 | } 243 | 244 | return t; 245 | } 246 | 247 | Tree partition(Tree t, int i) { 248 | if (t != NULL) { 249 | assert(0 <= i && i < TreeNumNodes(t)); 250 | int m = TreeNumNodes(left(t)); 251 | if (i < m) { 252 | left(t) = partition(left(t), i); 253 | t = rotateRight(t); 254 | } else if (i > m) { 255 | right(t) = partition(right(t), i-m-1); 256 | t = rotateLeft(t); 257 | } 258 | } 259 | return t; 260 | } 261 | 262 | Tree rebalance(Tree t) { 263 | int n = TreeNumNodes(t); 264 | if (n >= 3) { 265 | t = partition(t, n/2); // put node with median key at root 266 | left(t) = rebalance(left(t)); // then rebalance each subtree 267 | right(t) = rebalance(right(t)); 268 | } 269 | return t; 270 | } -------------------------------------------------------------------------------- /Problem Set/week6b/BSTree.h: -------------------------------------------------------------------------------- 1 | // Binary Search Tree ADT interface ... COMP9024 17s2 2 | 3 | #include 4 | 5 | typedef int Item; // item is just a key 6 | 7 | typedef struct Node *Tree; 8 | 9 | Tree newTree(); // create an empty Tree 10 | void freeTree(Tree); // free memory associated with Tree 11 | void showTree(Tree); // display a Tree (sideways) 12 | 13 | bool TreeSearch(Tree, Item); // check whether an item is in a Tree 14 | int TreeHeight(Tree); // compute height of Tree 15 | int TreeNumNodes(Tree); // count #nodes in Tree 16 | Tree TreeInsert(Tree, Item); // insert a new item into a Tree 17 | Tree TreeDelete(Tree, Item); // delete an item from a Tree 18 | 19 | // internal functions made visible for testing 20 | Tree rotateRight(Tree); 21 | Tree rotateLeft(Tree); 22 | Tree insertAtRoot(Tree, Item); 23 | Tree insertRandom(Tree, Item); 24 | Tree insertAVL(Tree, Item); 25 | Tree partition(Tree, int); 26 | Tree rebalance(Tree); -------------------------------------------------------------------------------- /Problem Set/week7/3.doc: -------------------------------------------------------------------------------- 1 | // Boyer-Moore algorithms 2 | 3 | pattern: 4 | xywapaswyy 5 | 0123456789 6 | 7 | last-occurrence function(L) 8 | x y w a p s 9 | 0 9 7 5 4 6 -------------------------------------------------------------------------------- /Problem Set/week7/4.doc: -------------------------------------------------------------------------------- 1 | // compute failure function of KMP algorithm 2 | 3 | cgtacgttcgtac 4 | 0000123012345 -------------------------------------------------------------------------------- /Problem Set/week7/5.doc: -------------------------------------------------------------------------------- 1 | // Boyer-Moore Algorithms 2 | 3 | Text: 4 | ABCACBBDABCADD 5 | Pattern: 6 | ABCAD 7 | 8 | Comparison process: 9 | ABCACBBDABCADD 10 | ABCAD 11 | ? 12 | 13 | ABCACBBDABCADD 14 | ABCAD 15 | ? 16 | 17 | ABCACBBDABCADD 18 | ABCAD 19 | ? 20 | 21 | ABCACBBDABCADD 22 | ABCAD 23 | ||||| 24 | 25 | So, totally compare 8 times -------------------------------------------------------------------------------- /Problem Set/week7/6.doc: -------------------------------------------------------------------------------- 1 | // Text: aaabaadaabaaa 2 | // Pattern: aabaaa 3 | 4 | // Use KMP Algorithm 5 | 6 | Failure function 7 | F[i] 0 1 2 3 4 5 8 | 0 1 0 1 2 2 9 | 10 | Comparison process 11 | aaabaadaabaaa 12 | aabaaa 13 | 123 14 | 15 | aaabaadaabaaa 16 | aabaaa 17 | 45678 18 | 19 | aaabaadaabaaa 20 | aabaaa 21 | 9 22 | 23 | aaabaadaabaaa 24 | aabaaa 25 | 10 26 | 27 | aaabaadaabaaa 28 | aabaaa 29 | 11 30 | 31 | aaabaadaabaaa 32 | aabaaa 33 | 12 34 | 13 35 | 14 36 | 15 37 | 16 38 | 17 39 | 40 | so totally compare 17 times 41 | -------------------------------------------------------------------------------- /Problem Set/week7/7.doc: -------------------------------------------------------------------------------- 1 | // Huffman code 2 | Text: 3 | ababbcdcbaabcacbbbs 4 | 5 | Frequency: 6 | a b c d s 7 | 5 8 4 1 1 8 | 9 | so Huffman Tree is: 10 | 19 11 | / \ 12 | 11 b 13 | / \ 14 | 6 a 15 | / \ 16 | 2 c 17 | / \ 18 | d s 19 | 20 | 21 | -------------------------------------------------------------------------------- /Problem Set/week7/Problem set 7.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/brmuch/COMP9024/094852af15dca9d5d9fa34d492a4415a476d812e/Problem Set/week7/Problem set 7.pdf -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # COMP9024 2 | Data Structures and Algorithms 3 | -------------------------------------------------------------------------------- /References/Cref.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/brmuch/COMP9024/094852af15dca9d5d9fa34d492a4415a476d812e/References/Cref.pdf -------------------------------------------------------------------------------- /References/排序算法.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/brmuch/COMP9024/094852af15dca9d5d9fa34d492a4415a476d812e/References/排序算法.jpg --------------------------------------------------------------------------------