├── Course_1_Object-Oriented Data Structures in Cpp ├── Week_1_Orientation_Write_a_cpp_program │ ├── Week_1_Challenge.cpp │ ├── Week_1_Challenge.exe │ ├── Week_1_Orientation Quiz_and_Reference Manual.pdf │ └── Week_1_Quiz_and_Reference Manual.pdf ├── Week_2_Understanding Cpp memory model │ ├── Week_2_Challenge_and_Reference Solution.pdf │ ├── Week_2_Challenge_implementation.cpp │ ├── Week_2_Challenge_implementation.exe │ ├── Week_2_Hello World_Project │ │ ├── .objs │ │ │ ├── main.d │ │ │ ├── main.o │ │ │ ├── tests │ │ │ │ ├── part1.d │ │ │ │ └── part1.o │ │ │ └── uiuc │ │ │ │ └── catch │ │ │ │ ├── catchmain.d │ │ │ │ └── catchmain.o │ │ ├── Makefile │ │ ├── main │ │ ├── main.cpp │ │ ├── test │ │ ├── tests │ │ │ └── part1.cpp │ │ ├── uiuc │ │ │ ├── catch │ │ │ │ ├── catch.hpp │ │ │ │ └── catchmain.cpp │ │ │ └── make │ │ │ │ └── uiuc.mk │ │ └── version.txt │ ├── Week_2_Hello World_Project_Description.pdf │ ├── Week_2_Hello World_Project_full implementation.zip │ ├── Week_2_Hello World_Project_starter.zip │ ├── Week_2_Hello World_Project_submission_.zip │ ├── Week_2_Project_Pass.pdf │ └── Week_2_Quiz_and_Reference Manual.pdf ├── Week_3_Developing Cpp Classes │ ├── Week_3_Challenge_and_Reference Solution.pdf │ ├── Week_3_Challenge_implementation.cpp │ ├── Week_3_Challenge_implementation.exe │ └── Week_3_Quiz_and_Reference Manual.pdf └── Week_4_Engineering Cpp software solution │ ├── Week4_Image_Project │ └── Week4_Image_Project │ │ ├── .objs │ │ ├── ImageTransform.d │ │ ├── ImageTransform.o │ │ ├── main.d │ │ ├── main.o │ │ ├── tests │ │ │ ├── part1.d │ │ │ ├── part1.o │ │ │ ├── part2.d │ │ │ └── part2.o │ │ └── uiuc │ │ │ ├── HSLAPixel.d │ │ │ ├── HSLAPixel.o │ │ │ ├── PNG.d │ │ │ ├── PNG.o │ │ │ ├── catch │ │ │ ├── catchmain.d │ │ │ └── catchmain.o │ │ │ └── lodepng │ │ │ ├── lodepng.d │ │ │ └── lodepng.o │ │ ├── ImageTransform │ │ ├── ImageTransform.cpp │ │ ├── ImageTransform.h │ │ ├── ImageTransform_submission.zip │ │ ├── Makefile │ │ ├── alma.png │ │ ├── main.cpp │ │ ├── overlay.png │ │ ├── test │ │ ├── tests │ │ ├── part1.cpp │ │ └── part2.cpp │ │ └── uiuc │ │ ├── HSLAPixel.cpp │ │ ├── HSLAPixel.h │ │ ├── PNG.cpp │ │ ├── PNG.h │ │ ├── RGB_HSL.h │ │ ├── catch │ │ ├── catch.hpp │ │ └── catchmain.cpp │ │ ├── lodepng │ │ ├── lodepng.cpp │ │ └── lodepng.h │ │ └── make │ │ └── uiuc.mk │ ├── Week4_Image_Project_full implementation.zip │ ├── Week_4_Challenge_and_Reference Solution.pdf │ ├── Week_4_Challenge_implementation.cpp │ ├── Week_4_Challenge_implementation.exe │ ├── Week_4_Image_Project_Description.pdf │ ├── Week_4_Image_Project_starter.zip │ ├── Week_4_Image_Project_submission.zip │ └── Week_4_Quiz_and_Reference Manual.pdf ├── Course_2_Ordered Data Structures ├── Week_1_Linear data structures │ ├── Week1_Challenge_implementation.cpp │ ├── Week1_Challenge_implementation.exe │ ├── Week1_Project_LinkedList_and_MergeSort │ │ ├── LinkedList.h │ │ ├── LinkedListExercises.h │ │ ├── Makefile │ │ ├── main.cpp │ │ ├── tests │ │ │ └── week1_tests.cpp │ │ ├── uiuc │ │ │ ├── catch │ │ │ │ ├── catch.hpp │ │ │ │ └── catchmain.cpp │ │ │ └── make │ │ │ │ └── uiuc.mk │ │ └── version.txt │ ├── Week1_Project_LinkedList_and_MergeSort_Description.pdf │ ├── Week1_Project_LinkedList_and_MergeSort_full implementation.zip │ ├── Week1_Project_LinkedList_and_MergeSort_starter_files_20191015a.zip │ ├── Week1_Project_LinkedList_and_MergeSort_submission.zip │ ├── Week_1_Challenge_and_Reference Solution.pdf │ ├── Week_1_Orientation Quiz_and_Reference Manual.pdf │ └── Week_1_Quiz_and_Reference Manual.pdf ├── Week_2_Introduction to Tree structures │ ├── Week2_Challenge_implementation.cpp │ ├── Week2_Challenge_implementation.exe │ ├── Week_2_Challenge_and_Reference Solution.pdf │ └── Week_2_Quiz_and_Reference Manual.pdf ├── Week_3_Advanced Tree Structures │ ├── Week3_Challenge_implementation.cpp │ ├── Week3_Challenge_implementation.exe │ ├── Week3_Project_GenericTree │ │ └── GenericTree │ │ │ ├── GenericTree.h │ │ │ ├── GenericTreeExercises.h │ │ │ ├── Makefile │ │ │ ├── main.cpp │ │ │ ├── tests │ │ │ └── week3_tests.cpp │ │ │ └── uiuc │ │ │ ├── catch │ │ │ ├── catch.hpp │ │ │ └── catchmain.cpp │ │ │ └── make │ │ │ └── uiuc.mk │ ├── Week3_Project_GenericTree_Description.pdf │ ├── Week3_Project_GenericTree_full implementation.zip │ ├── Week3_Project_GenericTree_starter_files_20191015a.zip │ ├── Week3_Project_GenericTree_submission.zip │ ├── Week_3_Challenge_and_Reference Solution.pdf │ └── Week_3_Quiz_and_Reference Manual.pdf └── Week_4_Heap Structures │ ├── Week4_Challenge_implementation.cpp │ ├── Week4_Challenge_implementation.exe │ ├── Week_4_Challenge_and_Reference Solution.pdf │ └── Week_4_Quiz_and_Reference Manual.pdf ├── Course_3_Unorder Data Structures ├── Week_1_Hashing │ ├── Week_1_Challenge_and_Reference Solution.pdf │ ├── Week_1_Challenge_imlementation.cpp │ ├── Week_1_Challenge_imlementation.exe │ ├── Week_1_Project_UnorderedMap │ │ └── UnorderedMap │ │ │ ├── IntPair.h │ │ │ ├── Makefile │ │ │ ├── UnorderedMapCommon.cpp │ │ │ ├── UnorderedMapCommon.h │ │ │ ├── UnorderedMapExercises.cpp │ │ │ ├── main.cpp │ │ │ ├── tests │ │ │ └── week1_tests.cpp │ │ │ ├── through_the_looking_glass.txt │ │ │ ├── uiuc │ │ │ ├── catch │ │ │ │ ├── catch.hpp │ │ │ │ └── catchmain.cpp │ │ │ └── make │ │ │ │ └── uiuc.mk │ │ │ └── v20190502a.txt │ ├── Week_1_Project_UnorderedMap_Description.pdf │ ├── Week_1_Project_UnorderedMap_full implementation.zip │ ├── Week_1_Project_UnorderedMap_starter_files.zip │ ├── Week_1_Quiz_and_Reference Manual.pdf │ └── Week_1_UnorderedMap_submission.zip ├── Week_2_Disjoint-sets │ ├── Week2_Challenge_implementation.cpp │ ├── Week2_Challenge_implementation.exe │ ├── Week_2_Challenge_and_Reference Solution.pdf │ └── Week_2_Quiz_and_Reference Manual.pdf ├── Week_3_Graph │ ├── Graph implementation.PNG │ ├── Week_3_Challenge_and_Reference Solution.pdf │ ├── Week_3_Challenge_implementation.cpp │ ├── Week_3_Challenge_implementation.exe │ ├── Week_3_Project_GraphSearch │ │ ├── GraphSearchCommon.h │ │ ├── GraphSearchExercises.cpp │ │ ├── GridGraph.cpp │ │ ├── GridGraph.h │ │ ├── IntPair2.h │ │ ├── Makefile │ │ ├── PuzzleState.cpp │ │ ├── PuzzleState.h │ │ ├── main.cpp │ │ ├── tests │ │ │ └── week3_tests.cpp │ │ ├── uiuc │ │ │ ├── catch │ │ │ │ ├── catch.hpp │ │ │ │ └── catchmain.cpp │ │ │ └── make │ │ │ │ └── uiuc.mk │ │ └── version.txt │ ├── Week_3_Project_GraphSearch_Description.pdf │ ├── Week_3_Project_GraphSearch_full implementation.zip │ ├── Week_3_Project_GraphSearch_starter_files.zip │ ├── Week_3_Project_GraphSearch_submission.zip │ └── Week_3_Quiz_and_Reference Manual.pdf └── Week_4_Graph-algorithm │ ├── Week4_Challenge_implementation.cpp │ ├── Week4_Challenge_implementation.exe │ ├── Week_4_Challenge_and_Reference Solution.pdf │ └── Week_4_Quiz_and_Reference Manual.pdf ├── LICENSE └── README.md /Course_1_Object-Oriented Data Structures in Cpp/Week_1_Orientation_Write_a_cpp_program/Week_1_Challenge.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | 5 | 6 | // You should define Pair here: 7 | // (Use as many lines as you need!) 8 | // ... 9 | // ... 10 | class Pair{ 11 | public: 12 | int a; 13 | int b; 14 | 15 | int sum() 16 | { 17 | return (a+b); 18 | } 19 | 20 | }; 21 | //End of definition of class Pair 22 | 23 | 24 | 25 | // This main() function will help you test your work. 26 | // Click Run to see what happens. 27 | // When you're sure you're finished, click Submit for grading 28 | // with our additional hidden tests. 29 | int main() { 30 | Pair p; 31 | p.a = 100; 32 | p.b = 200; 33 | 34 | // expected output 35 | // Success! 36 | if (p.a + p.b == p.sum()) { 37 | 38 | std::cout << "Success!" << std::endl; 39 | 40 | } else { 41 | 42 | std::cout << "p.sum() returns " << p.sum() << " instead of " << (p.a + p.b) << std::endl; 43 | } 44 | return 0; 45 | } -------------------------------------------------------------------------------- /Course_1_Object-Oriented Data Structures in Cpp/Week_1_Orientation_Write_a_cpp_program/Week_1_Challenge.exe: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/brianchiang-tw/Accelerated_Computer_Science_Fundamentals_Specialization/ff5f477f10e514c46e417a8dab4d4e60100725d5/Course_1_Object-Oriented Data Structures in Cpp/Week_1_Orientation_Write_a_cpp_program/Week_1_Challenge.exe -------------------------------------------------------------------------------- /Course_1_Object-Oriented Data Structures in Cpp/Week_1_Orientation_Write_a_cpp_program/Week_1_Orientation Quiz_and_Reference Manual.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/brianchiang-tw/Accelerated_Computer_Science_Fundamentals_Specialization/ff5f477f10e514c46e417a8dab4d4e60100725d5/Course_1_Object-Oriented Data Structures in Cpp/Week_1_Orientation_Write_a_cpp_program/Week_1_Orientation Quiz_and_Reference Manual.pdf -------------------------------------------------------------------------------- /Course_1_Object-Oriented Data Structures in Cpp/Week_1_Orientation_Write_a_cpp_program/Week_1_Quiz_and_Reference Manual.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/brianchiang-tw/Accelerated_Computer_Science_Fundamentals_Specialization/ff5f477f10e514c46e417a8dab4d4e60100725d5/Course_1_Object-Oriented Data Structures in Cpp/Week_1_Orientation_Write_a_cpp_program/Week_1_Quiz_and_Reference Manual.pdf -------------------------------------------------------------------------------- /Course_1_Object-Oriented Data Structures in Cpp/Week_2_Understanding Cpp memory model/Week_2_Challenge_and_Reference Solution.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/brianchiang-tw/Accelerated_Computer_Science_Fundamentals_Specialization/ff5f477f10e514c46e417a8dab4d4e60100725d5/Course_1_Object-Oriented Data Structures in Cpp/Week_2_Understanding Cpp memory model/Week_2_Challenge_and_Reference Solution.pdf -------------------------------------------------------------------------------- /Course_1_Object-Oriented Data Structures in Cpp/Week_2_Understanding Cpp memory model/Week_2_Challenge_implementation.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | // This class Pair has already been defined for you. 4 | // (You may not change this definition.) 5 | class Pair { 6 | public: 7 | int first, second; 8 | 9 | void check() { 10 | first = 5; 11 | std::cout << "Congratulations! The check() method of the Pair class \n has executed. (But, this isn't enough to guarantee \n that your code is correct.)" << std::endl; 12 | } 13 | 14 | }; 15 | 16 | 17 | 18 | 19 | // Insert your declaration and implementation of the function pairFactory() 20 | // below, by replacing "..." with proper C++ code. Be sure to declare the 21 | // function type to return a pointer to a Pair. 22 | 23 | Pair* pairFactory() { 24 | // ... 25 | // (You can use as many lines as you want.) 26 | 27 | // create an instance of class Pair 28 | Pair* pair_ptr = new Pair(); 29 | 30 | // return the memory address of pair_ptr 31 | return pair_ptr; 32 | } 33 | 34 | 35 | 36 | 37 | // Your function should be able to satisfy the tests below. You should try 38 | // some other things to convince yourself. If you have a bug in this problem, 39 | // the usual symptom is that after you submit, the grader will crash with a 40 | // system error. :-) 41 | 42 | 43 | // expected output of main() 44 | /* 45 | 46 | Congratulations! The check() method of the Pair class 47 | has executed. (But, this isn't enough to guarantee 48 | that your code is correct.) 49 | If you can see this text, the system hasn't crashed yet! 50 | 51 | */ 52 | 53 | 54 | int main() { 55 | Pair *p; 56 | p = pairFactory(); 57 | 58 | // This function call should work without crashing: 59 | p->check(); 60 | 61 | // Deallocating the heap memory. (Assuming it was made on the heap!) 62 | delete p; 63 | 64 | std::cout << "If you can see this text, the system hasn't crashed yet!" << std::endl; 65 | 66 | return 0; 67 | } 68 | -------------------------------------------------------------------------------- /Course_1_Object-Oriented Data Structures in Cpp/Week_2_Understanding Cpp memory model/Week_2_Challenge_implementation.exe: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/brianchiang-tw/Accelerated_Computer_Science_Fundamentals_Specialization/ff5f477f10e514c46e417a8dab4d4e60100725d5/Course_1_Object-Oriented Data Structures in Cpp/Week_2_Understanding Cpp memory model/Week_2_Challenge_implementation.exe -------------------------------------------------------------------------------- /Course_1_Object-Oriented Data Structures in Cpp/Week_2_Understanding Cpp memory model/Week_2_Hello World_Project/.objs/main.d: -------------------------------------------------------------------------------- 1 | .objs/main.o: main.cpp 2 | -------------------------------------------------------------------------------- /Course_1_Object-Oriented Data Structures in Cpp/Week_2_Understanding Cpp memory model/Week_2_Hello World_Project/.objs/main.o: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/brianchiang-tw/Accelerated_Computer_Science_Fundamentals_Specialization/ff5f477f10e514c46e417a8dab4d4e60100725d5/Course_1_Object-Oriented Data Structures in Cpp/Week_2_Understanding Cpp memory model/Week_2_Hello World_Project/.objs/main.o -------------------------------------------------------------------------------- /Course_1_Object-Oriented Data Structures in Cpp/Week_2_Understanding Cpp memory model/Week_2_Hello World_Project/.objs/tests/part1.d: -------------------------------------------------------------------------------- 1 | .objs/tests/part1.o: tests/part1.cpp tests/../uiuc/catch/catch.hpp 2 | 3 | tests/../uiuc/catch/catch.hpp: 4 | -------------------------------------------------------------------------------- /Course_1_Object-Oriented Data Structures in Cpp/Week_2_Understanding Cpp memory model/Week_2_Hello World_Project/.objs/tests/part1.o: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/brianchiang-tw/Accelerated_Computer_Science_Fundamentals_Specialization/ff5f477f10e514c46e417a8dab4d4e60100725d5/Course_1_Object-Oriented Data Structures in Cpp/Week_2_Understanding Cpp memory model/Week_2_Hello World_Project/.objs/tests/part1.o -------------------------------------------------------------------------------- /Course_1_Object-Oriented Data Structures in Cpp/Week_2_Understanding Cpp memory model/Week_2_Hello World_Project/.objs/uiuc/catch/catchmain.d: -------------------------------------------------------------------------------- 1 | .objs/uiuc/catch/catchmain.o: uiuc/catch/catchmain.cpp \ 2 | uiuc/catch/catch.hpp 3 | 4 | uiuc/catch/catch.hpp: 5 | -------------------------------------------------------------------------------- /Course_1_Object-Oriented Data Structures in Cpp/Week_2_Understanding Cpp memory model/Week_2_Hello World_Project/.objs/uiuc/catch/catchmain.o: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/brianchiang-tw/Accelerated_Computer_Science_Fundamentals_Specialization/ff5f477f10e514c46e417a8dab4d4e60100725d5/Course_1_Object-Oriented Data Structures in Cpp/Week_2_Understanding Cpp memory model/Week_2_Hello World_Project/.objs/uiuc/catch/catchmain.o -------------------------------------------------------------------------------- /Course_1_Object-Oriented Data Structures in Cpp/Week_2_Understanding Cpp memory model/Week_2_Hello World_Project/Makefile: -------------------------------------------------------------------------------- 1 | # Executable names: 2 | EXE = main 3 | TEST = test 4 | 5 | # Add all object files needed for compiling: 6 | EXE_OBJ = main.o 7 | OBJS = main.o 8 | 9 | # Generated files 10 | # (none) 11 | 12 | # Include the master templated makefile: 13 | include uiuc/make/uiuc.mk 14 | -------------------------------------------------------------------------------- /Course_1_Object-Oriented Data Structures in Cpp/Week_2_Understanding Cpp memory model/Week_2_Hello World_Project/main: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/brianchiang-tw/Accelerated_Computer_Science_Fundamentals_Specialization/ff5f477f10e514c46e417a8dab4d4e60100725d5/Course_1_Object-Oriented Data Structures in Cpp/Week_2_Understanding Cpp memory model/Week_2_Hello World_Project/main -------------------------------------------------------------------------------- /Course_1_Object-Oriented Data Structures in Cpp/Week_2_Understanding Cpp memory model/Week_2_Hello World_Project/main.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * @file main.cpp 3 | * University of Illinois 4 | * Object-Oriented Data Structures in C++ - Week 2 5 | * Hello World Project 6 | * 7 | * @author Eric Huber - University of Illinois staff - July 2019 8 | **/ 9 | 10 | // You need to include some header(s) here! 11 | #include 12 | 13 | using namespace std; 14 | // You need to define your main() function here! 15 | 16 | int main(int argc, char* argv[]) 17 | { 18 | 19 | cout << "Hello, world!" << endl; 20 | cout << "Greetings from Illinois!" << endl; 21 | 22 | return 0; 23 | } 24 | 25 | // Notes: 26 | 27 | // If you get a compiler error saying "undefined reference to main", 28 | // it means you haven't defined your main function correctly. 29 | 30 | // Standard output is the system stream for normal text output on the terminal. 31 | // One way to write to it, that you have learned, is with std::cout. 32 | 33 | // Your main function should write the following messages to standard output: 34 | // Hello, world! 35 | // Greetings from Illinois! 36 | 37 | // Also note, the autograder does not care about letter case, punctuation, 38 | // or spacing! But it does care about spelling and the order of words! 39 | 40 | -------------------------------------------------------------------------------- /Course_1_Object-Oriented Data Structures in Cpp/Week_2_Understanding Cpp memory model/Week_2_Hello World_Project/test: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/brianchiang-tw/Accelerated_Computer_Science_Fundamentals_Specialization/ff5f477f10e514c46e417a8dab4d4e60100725d5/Course_1_Object-Oriented Data Structures in Cpp/Week_2_Understanding Cpp memory model/Week_2_Hello World_Project/test -------------------------------------------------------------------------------- /Course_1_Object-Oriented Data Structures in Cpp/Week_2_Understanding Cpp memory model/Week_2_Hello World_Project/tests/part1.cpp: -------------------------------------------------------------------------------- 1 | 2 | // University of Illinois 3 | // CS 400 MP 0: Hello World 4 | // Tests prepared by Eric Huber 5 | // Based on Zephyr test runner by Prof. Wade Fagen-Ulmschneider and the CS 225 Course Staff 6 | // Based on Catch2 unit testing framework 7 | 8 | #include 9 | 10 | #include "../uiuc/catch/catch.hpp" 11 | 12 | TEST_CASE("Should find your compiled main executable", "[weight=1]") { 13 | int result = std::system("test -x ./main"); 14 | REQUIRE(0 == result); 15 | } 16 | 17 | // TEST_CASE("Should have ownership permissions to run your main executable", "[weight=1]") { 18 | // int result = std::system("test `stat -c \"%U\" ./test` = `whoami`"); 19 | // REQUIRE(0 == result); 20 | // } 21 | 22 | TEST_CASE("Should find \"Hello, world!\" in standard output", "[weight=1]") { 23 | int result = std::system("./main | tr \'\n\' \' \' | tr A-Z a-z | sed \'s/[^a-z]//g\' | grep helloworld > /dev/null"); 24 | REQUIRE(0 == result); 25 | } 26 | 27 | TEST_CASE("Should find \"Greetings from Illinois!\" in standard output", "[weight=1]") { 28 | int result = std::system("./main | tr \'\n\' \' \' | tr A-Z a-z | sed \'s/[^a-z]//g\' | grep greetingsfromillinois > /dev/null"); 29 | REQUIRE(0 == result); 30 | } 31 | 32 | -------------------------------------------------------------------------------- /Course_1_Object-Oriented Data Structures in Cpp/Week_2_Understanding Cpp memory model/Week_2_Hello World_Project/uiuc/catch/catchmain.cpp: -------------------------------------------------------------------------------- 1 | #define CATCH_CONFIG_MAIN 2 | #include "catch.hpp" 3 | -------------------------------------------------------------------------------- /Course_1_Object-Oriented Data Structures in Cpp/Week_2_Understanding Cpp memory model/Week_2_Hello World_Project/uiuc/make/uiuc.mk: -------------------------------------------------------------------------------- 1 | 2 | # University of Illinois 3 | # CS 400 MP 0: Hello World 4 | 5 | # Original Makefile created by Wade Fagen-Ulmschneider 6 | # A few tweaks for CS 400 by Eric Huber 7 | 8 | # Add standard object files (HSLAPixel, PNG, and LodePNG) 9 | OBJS += 10 | 11 | # Use ./.objs to store all .o file (keeping the directory clean) 12 | OBJS_DIR = .objs 13 | 14 | # Use all .cpp files in /tests/ 15 | OBJS_TEST = $(filter-out $(EXE_OBJ), $(OBJS)) 16 | CPP_TEST = $(wildcard tests/*.cpp) 17 | CPP_TEST += uiuc/catch/catchmain.cpp 18 | OBJS_TEST += $(CPP_TEST:.cpp=.o) 19 | 20 | # Config 21 | CXX_CLANG = clang++ 22 | CXX_GNU = g++ 23 | CXX_WHICH = $(CXX_GNU) 24 | CXX = $(CXX_WHICH) 25 | LD = $(CXX_WHICH) 26 | # STDVERSION = -std=c++1y # deprecated nomenclature 27 | STDVERSION = -std=c++14 # proper but requires newer compiler versions (for better or worse) 28 | STDLIBVERSION_CLANG = -stdlib=libc++ # Clang's version; not present on default AWS Cloud9 instance 29 | STDLIBVERSION_GNU = # blank on purpose; default GNU library 30 | STDLIBVERSION = $(STDLIBVERSION_GNU) 31 | WARNINGS = -pedantic -Wall -Wfatal-errors -Wextra -Wno-unused-parameter -Wno-unused-variable 32 | CXXFLAGS = $(CS400) $(STDVERSION) $(STDLIBVERSION) -g -O0 $(WARNINGS) -MMD -MP -msse2 -c 33 | LDFLAGS = $(CS400) $(STDVERSION) $(STDLIBVERSION) -lpthread 34 | ASANFLAGS = -fsanitize=address -fno-omit-frame-pointer 35 | 36 | # Rules for first executable 37 | $(EXE): 38 | $(LD) $^ $(LDFLAGS) -o $@ 39 | @echo "" 40 | @echo " Built the main executable program file for the project: " $(EXE) 41 | @echo " (Make sure you try \"make test\" too!)" 42 | @echo "" 43 | 44 | # Rule for `all` 45 | all: $(EXE) $(TEST) 46 | 47 | # Pattern rules for object files 48 | $(OBJS_DIR): 49 | @mkdir -p $(OBJS_DIR) 50 | @mkdir -p $(OBJS_DIR)/uiuc 51 | @mkdir -p $(OBJS_DIR)/uiuc/catch 52 | @mkdir -p $(OBJS_DIR)/tests 53 | 54 | $(OBJS_DIR)/%.o: %.cpp | $(OBJS_DIR) 55 | $(CXX) $(CXXFLAGS) $< -o $@ 56 | 57 | # Rules for executables 58 | $(TEST): 59 | @make main 60 | $(LD) $^ $(LDFLAGS) -o $@ 61 | @echo "" 62 | @echo " Built the test suite program: " $(TEST) 63 | @echo "" 64 | 65 | # Executable dependencies 66 | $(EXE): $(patsubst %.o, $(OBJS_DIR)/%.o, $(OBJS)) 67 | $(TEST): $(patsubst %.o, $(OBJS_DIR)/%.o, $(OBJS_TEST)) 68 | 69 | # Include automatically generated dependencies 70 | -include $(OBJS_DIR)/*.d 71 | -include $(OBJS_DIR)/uiuc/*.d 72 | -include $(OBJS_DIR)/uiuc/catch/*.d 73 | -include $(OBJS_DIR)/tests/*.d 74 | 75 | clean: 76 | rm -rf $(EXE) $(TEST) $(OBJS_DIR) $(CLEAN_RM) 77 | 78 | tidy: clean 79 | rm -rf doc 80 | 81 | .PHONY: all tidy clean 82 | -------------------------------------------------------------------------------- /Course_1_Object-Oriented Data Structures in Cpp/Week_2_Understanding Cpp memory model/Week_2_Hello World_Project/version.txt: -------------------------------------------------------------------------------- 1 | 2 | 20190722b 3 | -------------------------------------------------------------------------------- /Course_1_Object-Oriented Data Structures in Cpp/Week_2_Understanding Cpp memory model/Week_2_Hello World_Project_Description.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/brianchiang-tw/Accelerated_Computer_Science_Fundamentals_Specialization/ff5f477f10e514c46e417a8dab4d4e60100725d5/Course_1_Object-Oriented Data Structures in Cpp/Week_2_Understanding Cpp memory model/Week_2_Hello World_Project_Description.pdf -------------------------------------------------------------------------------- /Course_1_Object-Oriented Data Structures in Cpp/Week_2_Understanding Cpp memory model/Week_2_Hello World_Project_full implementation.zip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/brianchiang-tw/Accelerated_Computer_Science_Fundamentals_Specialization/ff5f477f10e514c46e417a8dab4d4e60100725d5/Course_1_Object-Oriented Data Structures in Cpp/Week_2_Understanding Cpp memory model/Week_2_Hello World_Project_full implementation.zip -------------------------------------------------------------------------------- /Course_1_Object-Oriented Data Structures in Cpp/Week_2_Understanding Cpp memory model/Week_2_Hello World_Project_starter.zip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/brianchiang-tw/Accelerated_Computer_Science_Fundamentals_Specialization/ff5f477f10e514c46e417a8dab4d4e60100725d5/Course_1_Object-Oriented Data Structures in Cpp/Week_2_Understanding Cpp memory model/Week_2_Hello World_Project_starter.zip -------------------------------------------------------------------------------- /Course_1_Object-Oriented Data Structures in Cpp/Week_2_Understanding Cpp memory model/Week_2_Hello World_Project_submission_.zip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/brianchiang-tw/Accelerated_Computer_Science_Fundamentals_Specialization/ff5f477f10e514c46e417a8dab4d4e60100725d5/Course_1_Object-Oriented Data Structures in Cpp/Week_2_Understanding Cpp memory model/Week_2_Hello World_Project_submission_.zip -------------------------------------------------------------------------------- /Course_1_Object-Oriented Data Structures in Cpp/Week_2_Understanding Cpp memory model/Week_2_Project_Pass.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/brianchiang-tw/Accelerated_Computer_Science_Fundamentals_Specialization/ff5f477f10e514c46e417a8dab4d4e60100725d5/Course_1_Object-Oriented Data Structures in Cpp/Week_2_Understanding Cpp memory model/Week_2_Project_Pass.pdf -------------------------------------------------------------------------------- /Course_1_Object-Oriented Data Structures in Cpp/Week_2_Understanding Cpp memory model/Week_2_Quiz_and_Reference Manual.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/brianchiang-tw/Accelerated_Computer_Science_Fundamentals_Specialization/ff5f477f10e514c46e417a8dab4d4e60100725d5/Course_1_Object-Oriented Data Structures in Cpp/Week_2_Understanding Cpp memory model/Week_2_Quiz_and_Reference Manual.pdf -------------------------------------------------------------------------------- /Course_1_Object-Oriented Data Structures in Cpp/Week_3_Developing Cpp Classes/Week_3_Challenge_and_Reference Solution.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/brianchiang-tw/Accelerated_Computer_Science_Fundamentals_Specialization/ff5f477f10e514c46e417a8dab4d4e60100725d5/Course_1_Object-Oriented Data Structures in Cpp/Week_3_Developing Cpp Classes/Week_3_Challenge_and_Reference Solution.pdf -------------------------------------------------------------------------------- /Course_1_Object-Oriented Data Structures in Cpp/Week_3_Developing Cpp Classes/Week_3_Challenge_implementation.cpp: -------------------------------------------------------------------------------- 1 | /* Class Pair has already been declared 2 | * as shown in the following comments: 3 | */ 4 | 5 | #include 6 | 7 | using namespace std; 8 | 9 | 10 | class Pair { 11 | 12 | public: 13 | int *pa,*pb; 14 | 15 | Pair(int, int); 16 | 17 | Pair(const Pair &); 18 | 19 | ~Pair(); 20 | 21 | }; 22 | 23 | 24 | // Implement its member functions below. 25 | 26 | Pair::Pair(int a_val_ , int b_val_ ) 27 | { 28 | // allocate pa with a_val_ 29 | // allocate pb with b_val_ 30 | pa = new int( a_val_ ); 31 | pb = new int( b_val_ ); 32 | } 33 | //End of constructor 34 | 35 | Pair::Pair(const Pair& p) 36 | { 37 | pa = new int( *(p.pa) ); 38 | pb = new int( *(p.pb) ); 39 | } 40 | //End of copy construtor with deep-copy 41 | 42 | Pair::~Pair() 43 | { 44 | // deallocate pa and pb 45 | delete pa; 46 | delete pb; 47 | 48 | // Set released ptr points to NULL 49 | pa = nullptr; 50 | pb = nullptr; 51 | } 52 | //End of destructor 53 | 54 | 55 | /* Here is a main() function you can use 56 | * to check your implementation of the 57 | * class Pair member functions. 58 | */ 59 | 60 | 61 | // expected output 62 | /* 63 | 64 | If this message is printed, at least the program hasn't crashed yet! 65 | But you may want to print other diagnostic messages too. 66 | 67 | */ 68 | 69 | int main() { 70 | Pair p(15,16); 71 | Pair q(p); 72 | Pair *hp = new Pair(23,42); 73 | delete hp; 74 | 75 | std::cout << "If this message is printed," 76 | << " at least the program hasn't crashed yet!\n" 77 | << "But you may want to print other diagnostic messages too." << std::endl; 78 | return 0; 79 | } -------------------------------------------------------------------------------- /Course_1_Object-Oriented Data Structures in Cpp/Week_3_Developing Cpp Classes/Week_3_Challenge_implementation.exe: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/brianchiang-tw/Accelerated_Computer_Science_Fundamentals_Specialization/ff5f477f10e514c46e417a8dab4d4e60100725d5/Course_1_Object-Oriented Data Structures in Cpp/Week_3_Developing Cpp Classes/Week_3_Challenge_implementation.exe -------------------------------------------------------------------------------- /Course_1_Object-Oriented Data Structures in Cpp/Week_3_Developing Cpp Classes/Week_3_Quiz_and_Reference Manual.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/brianchiang-tw/Accelerated_Computer_Science_Fundamentals_Specialization/ff5f477f10e514c46e417a8dab4d4e60100725d5/Course_1_Object-Oriented Data Structures in Cpp/Week_3_Developing Cpp Classes/Week_3_Quiz_and_Reference Manual.pdf -------------------------------------------------------------------------------- /Course_1_Object-Oriented Data Structures in Cpp/Week_4_Engineering Cpp software solution/Week4_Image_Project/Week4_Image_Project/.objs/ImageTransform.d: -------------------------------------------------------------------------------- 1 | .objs/ImageTransform.o: ImageTransform.cpp uiuc/PNG.h uiuc/HSLAPixel.h \ 2 | ImageTransform.h 3 | 4 | uiuc/PNG.h: 5 | 6 | uiuc/HSLAPixel.h: 7 | 8 | ImageTransform.h: 9 | -------------------------------------------------------------------------------- /Course_1_Object-Oriented Data Structures in Cpp/Week_4_Engineering Cpp software solution/Week4_Image_Project/Week4_Image_Project/.objs/ImageTransform.o: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/brianchiang-tw/Accelerated_Computer_Science_Fundamentals_Specialization/ff5f477f10e514c46e417a8dab4d4e60100725d5/Course_1_Object-Oriented Data Structures in Cpp/Week_4_Engineering Cpp software solution/Week4_Image_Project/Week4_Image_Project/.objs/ImageTransform.o -------------------------------------------------------------------------------- /Course_1_Object-Oriented Data Structures in Cpp/Week_4_Engineering Cpp software solution/Week4_Image_Project/Week4_Image_Project/.objs/main.d: -------------------------------------------------------------------------------- 1 | .objs/main.o: main.cpp ImageTransform.h uiuc/PNG.h uiuc/HSLAPixel.h 2 | 3 | ImageTransform.h: 4 | 5 | uiuc/PNG.h: 6 | 7 | uiuc/HSLAPixel.h: 8 | -------------------------------------------------------------------------------- /Course_1_Object-Oriented Data Structures in Cpp/Week_4_Engineering Cpp software solution/Week4_Image_Project/Week4_Image_Project/.objs/main.o: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/brianchiang-tw/Accelerated_Computer_Science_Fundamentals_Specialization/ff5f477f10e514c46e417a8dab4d4e60100725d5/Course_1_Object-Oriented Data Structures in Cpp/Week_4_Engineering Cpp software solution/Week4_Image_Project/Week4_Image_Project/.objs/main.o -------------------------------------------------------------------------------- /Course_1_Object-Oriented Data Structures in Cpp/Week_4_Engineering Cpp software solution/Week4_Image_Project/Week4_Image_Project/.objs/tests/part1.d: -------------------------------------------------------------------------------- 1 | .objs/tests/part1.o: tests/part1.cpp tests/../uiuc/catch/catch.hpp \ 2 | tests/../ImageTransform.h tests/../uiuc/PNG.h tests/../uiuc/HSLAPixel.h 3 | 4 | tests/../uiuc/catch/catch.hpp: 5 | 6 | tests/../ImageTransform.h: 7 | 8 | tests/../uiuc/PNG.h: 9 | 10 | tests/../uiuc/HSLAPixel.h: 11 | -------------------------------------------------------------------------------- /Course_1_Object-Oriented Data Structures in Cpp/Week_4_Engineering Cpp software solution/Week4_Image_Project/Week4_Image_Project/.objs/tests/part1.o: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/brianchiang-tw/Accelerated_Computer_Science_Fundamentals_Specialization/ff5f477f10e514c46e417a8dab4d4e60100725d5/Course_1_Object-Oriented Data Structures in Cpp/Week_4_Engineering Cpp software solution/Week4_Image_Project/Week4_Image_Project/.objs/tests/part1.o -------------------------------------------------------------------------------- /Course_1_Object-Oriented Data Structures in Cpp/Week_4_Engineering Cpp software solution/Week4_Image_Project/Week4_Image_Project/.objs/tests/part2.d: -------------------------------------------------------------------------------- 1 | .objs/tests/part2.o: tests/part2.cpp tests/../uiuc/catch/catch.hpp \ 2 | tests/../ImageTransform.h tests/../uiuc/PNG.h tests/../uiuc/HSLAPixel.h 3 | 4 | tests/../uiuc/catch/catch.hpp: 5 | 6 | tests/../ImageTransform.h: 7 | 8 | tests/../uiuc/PNG.h: 9 | 10 | tests/../uiuc/HSLAPixel.h: 11 | -------------------------------------------------------------------------------- /Course_1_Object-Oriented Data Structures in Cpp/Week_4_Engineering Cpp software solution/Week4_Image_Project/Week4_Image_Project/.objs/tests/part2.o: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/brianchiang-tw/Accelerated_Computer_Science_Fundamentals_Specialization/ff5f477f10e514c46e417a8dab4d4e60100725d5/Course_1_Object-Oriented Data Structures in Cpp/Week_4_Engineering Cpp software solution/Week4_Image_Project/Week4_Image_Project/.objs/tests/part2.o -------------------------------------------------------------------------------- /Course_1_Object-Oriented Data Structures in Cpp/Week_4_Engineering Cpp software solution/Week4_Image_Project/Week4_Image_Project/.objs/uiuc/HSLAPixel.d: -------------------------------------------------------------------------------- 1 | .objs/uiuc/HSLAPixel.o: uiuc/HSLAPixel.cpp uiuc/HSLAPixel.h 2 | 3 | uiuc/HSLAPixel.h: 4 | -------------------------------------------------------------------------------- /Course_1_Object-Oriented Data Structures in Cpp/Week_4_Engineering Cpp software solution/Week4_Image_Project/Week4_Image_Project/.objs/uiuc/HSLAPixel.o: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/brianchiang-tw/Accelerated_Computer_Science_Fundamentals_Specialization/ff5f477f10e514c46e417a8dab4d4e60100725d5/Course_1_Object-Oriented Data Structures in Cpp/Week_4_Engineering Cpp software solution/Week4_Image_Project/Week4_Image_Project/.objs/uiuc/HSLAPixel.o -------------------------------------------------------------------------------- /Course_1_Object-Oriented Data Structures in Cpp/Week_4_Engineering Cpp software solution/Week4_Image_Project/Week4_Image_Project/.objs/uiuc/PNG.d: -------------------------------------------------------------------------------- 1 | .objs/uiuc/PNG.o: uiuc/PNG.cpp uiuc/lodepng/lodepng.h uiuc/HSLAPixel.h \ 2 | uiuc/PNG.h uiuc/RGB_HSL.h 3 | 4 | uiuc/lodepng/lodepng.h: 5 | 6 | uiuc/HSLAPixel.h: 7 | 8 | uiuc/PNG.h: 9 | 10 | uiuc/RGB_HSL.h: 11 | -------------------------------------------------------------------------------- /Course_1_Object-Oriented Data Structures in Cpp/Week_4_Engineering Cpp software solution/Week4_Image_Project/Week4_Image_Project/.objs/uiuc/PNG.o: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/brianchiang-tw/Accelerated_Computer_Science_Fundamentals_Specialization/ff5f477f10e514c46e417a8dab4d4e60100725d5/Course_1_Object-Oriented Data Structures in Cpp/Week_4_Engineering Cpp software solution/Week4_Image_Project/Week4_Image_Project/.objs/uiuc/PNG.o -------------------------------------------------------------------------------- /Course_1_Object-Oriented Data Structures in Cpp/Week_4_Engineering Cpp software solution/Week4_Image_Project/Week4_Image_Project/.objs/uiuc/catch/catchmain.d: -------------------------------------------------------------------------------- 1 | .objs/uiuc/catch/catchmain.o: uiuc/catch/catchmain.cpp \ 2 | uiuc/catch/catch.hpp 3 | 4 | uiuc/catch/catch.hpp: 5 | -------------------------------------------------------------------------------- /Course_1_Object-Oriented Data Structures in Cpp/Week_4_Engineering Cpp software solution/Week4_Image_Project/Week4_Image_Project/.objs/uiuc/catch/catchmain.o: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/brianchiang-tw/Accelerated_Computer_Science_Fundamentals_Specialization/ff5f477f10e514c46e417a8dab4d4e60100725d5/Course_1_Object-Oriented Data Structures in Cpp/Week_4_Engineering Cpp software solution/Week4_Image_Project/Week4_Image_Project/.objs/uiuc/catch/catchmain.o -------------------------------------------------------------------------------- /Course_1_Object-Oriented Data Structures in Cpp/Week_4_Engineering Cpp software solution/Week4_Image_Project/Week4_Image_Project/.objs/uiuc/lodepng/lodepng.d: -------------------------------------------------------------------------------- 1 | .objs/uiuc/lodepng/lodepng.o: uiuc/lodepng/lodepng.cpp \ 2 | uiuc/lodepng/lodepng.h 3 | 4 | uiuc/lodepng/lodepng.h: 5 | -------------------------------------------------------------------------------- /Course_1_Object-Oriented Data Structures in Cpp/Week_4_Engineering Cpp software solution/Week4_Image_Project/Week4_Image_Project/.objs/uiuc/lodepng/lodepng.o: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/brianchiang-tw/Accelerated_Computer_Science_Fundamentals_Specialization/ff5f477f10e514c46e417a8dab4d4e60100725d5/Course_1_Object-Oriented Data Structures in Cpp/Week_4_Engineering Cpp software solution/Week4_Image_Project/Week4_Image_Project/.objs/uiuc/lodepng/lodepng.o -------------------------------------------------------------------------------- /Course_1_Object-Oriented Data Structures in Cpp/Week_4_Engineering Cpp software solution/Week4_Image_Project/Week4_Image_Project/ImageTransform: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/brianchiang-tw/Accelerated_Computer_Science_Fundamentals_Specialization/ff5f477f10e514c46e417a8dab4d4e60100725d5/Course_1_Object-Oriented Data Structures in Cpp/Week_4_Engineering Cpp software solution/Week4_Image_Project/Week4_Image_Project/ImageTransform -------------------------------------------------------------------------------- /Course_1_Object-Oriented Data Structures in Cpp/Week_4_Engineering Cpp software solution/Week4_Image_Project/Week4_Image_Project/ImageTransform.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | #include "uiuc/PNG.h" 6 | #include "uiuc/HSLAPixel.h" 7 | #include "ImageTransform.h" 8 | 9 | /* ****************** 10 | (Begin multi-line comment...) 11 | 12 | Write your name and email address in the comment space here: 13 | 14 | Name: 15 | Email: 16 | 17 | (...end multi-line comment.) 18 | ******************** */ 19 | 20 | using uiuc::PNG; 21 | using uiuc::HSLAPixel; 22 | 23 | /** 24 | * Returns an image that has been transformed to grayscale. 25 | * 26 | * The saturation of every pixel is set to 0, removing any color. 27 | * 28 | * @return The grayscale image. 29 | */ 30 | PNG grayscale(PNG image) { 31 | /// This function is already written for you so you can see how to 32 | /// interact with our PNG class. 33 | for (unsigned x = 0; x < image.width(); x++) { 34 | for (unsigned y = 0; y < image.height(); y++) { 35 | HSLAPixel & pixel = image.getPixel(x, y); 36 | 37 | // `pixel` is a reference to the memory stored inside of the PNG `image`, 38 | // which means you're changing the image directly. No need to `set` 39 | // the pixel since you're directly changing the memory of the image. 40 | pixel.s = 0; 41 | } 42 | } 43 | 44 | return image; 45 | } 46 | 47 | 48 | 49 | /** 50 | * Returns an image with a spotlight centered at (`centerX`, `centerY`). 51 | * 52 | * A spotlight adjusts the luminance of a pixel based on the distance the pixel 53 | * is away from the center by decreasing the luminance by 0.5% per 1 pixel euclidean 54 | * distance away from the center. 55 | * 56 | * For example, a pixel 3 pixels above and 4 pixels to the right of the center 57 | * is a total of `sqrt((3 * 3) + (4 * 4)) = sqrt(25) = 5` pixels away and 58 | * its luminance is decreased by 2.5% (0.975x its original value). At a 59 | * distance over 160 pixels away, the luminance will always decreased by 80%. 60 | * 61 | * The modified PNG is then returned. 62 | * 63 | * @param image A PNG object which holds the image data to be modified. 64 | * @param centerX The center x coordinate of the crosshair which is to be drawn. 65 | * @param centerY The center y coordinate of the crosshair which is to be drawn. 66 | * 67 | * @return The image with a spotlight. 68 | */ 69 | PNG createSpotlight(PNG image, int centerX, int centerY) { 70 | 71 | // luminance degration = 0.5 % per pixel 72 | // = 0.005 per pixel 73 | double luminance_degrade = 0.005; 74 | 75 | for (unsigned x = 0; x < image.width(); x++) { 76 | for (unsigned y = 0; y < image.height(); y++) { 77 | 78 | // get pixel reference from image 79 | HSLAPixel & pixel = image.getPixel(x, y); 80 | 81 | // original pixel luminance 82 | double original_luminance = pixel.l; 83 | 84 | // calculate radius 85 | //double radius = floor( sqrt( ( x - centerX )^2 + ( y - centerY )^2 ) ); 86 | double radius = ( sqrt( pow( x - centerX, 2 ) + pow( y - centerY, 2 ) ) ); 87 | 88 | // maximal degration stop at r = 160 89 | if ( radius >= 160.0 ) 90 | { 91 | radius = 160.0; 92 | } 93 | 94 | double luminance_adjustment = radius * luminance_degrade; 95 | 96 | // update new pixel luminance 97 | pixel.l = original_luminance * ( 1.0 - luminance_adjustment ); 98 | 99 | 100 | } 101 | //end of loop y 102 | 103 | } 104 | //end of loop x 105 | 106 | return image; 107 | 108 | } 109 | //end of function PNG createSpotlight 110 | 111 | 112 | /** 113 | * Returns a image transformed to Illini colors. 114 | * 115 | * The hue of every pixel is set to the a hue value of either orange or 116 | * blue, based on if the pixel's hue value is closer to orange than blue. 117 | * 118 | * @param image A PNG object which holds the image data to be modified. 119 | * 120 | * @return The illinify'd image. 121 | **/ 122 | PNG illinify(PNG image) { 123 | 124 | 125 | for (unsigned x = 0; x < image.width(); x++) { 126 | for (unsigned y = 0; y < image.height(); y++) { 127 | 128 | HSLAPixel & pixel = image.getPixel(x, y); 129 | 130 | // `pixel` is a reference to the memory stored inside of the PNG `image`, 131 | // which means you're changing the image directly. No need to `set` 132 | // the pixel since you're directly changing the memory of the image. 133 | 134 | double current_hue = pixel.h; 135 | double illini_orange = 11.0; 136 | double illini_blue = 216.0; 137 | 138 | //double dist_to_orange = current_hue - illini_orange; 139 | //double dist_to_blue = current_hue - illini_blue; 140 | 141 | double dist_to_orange = min( abs( current_hue - illini_orange ), abs( 360.0+illini_orange-current_hue ) ); 142 | double dist_to_blue = min( abs( current_hue - illini_blue ), abs( 360.0+illini_blue-current_hue ) ); 143 | 144 | 145 | if( dist_to_orange < dist_to_blue ) 146 | { 147 | pixel.h = illini_orange; 148 | } 149 | else 150 | { 151 | pixel.h = illini_blue; 152 | } 153 | //end of if...else... 154 | 155 | } 156 | //end of loop y 157 | 158 | } 159 | //end of loop x 160 | 161 | 162 | return image; 163 | } 164 | //end of function PNG illinify(PNG image) 165 | 166 | 167 | /** 168 | * Returns an immge that has been watermarked by another image. 169 | * 170 | * The luminance of every pixel of the second image is checked, if that 171 | * pixel's luminance is 1 (100%), then the pixel at the same location on 172 | * the first image has its luminance increased by 0.2. 173 | * 174 | * @param firstImage The first of the two PNGs, which is the base image. 175 | * @param secondImage The second of the two PNGs, which acts as the stencil. 176 | * 177 | * @return The watermarked image. 178 | */ 179 | PNG watermark(PNG firstImage, PNG secondImage) { 180 | 181 | for (unsigned x = 0; x < secondImage.width(); x++) { 182 | 183 | for (unsigned y = 0; y < secondImage.height(); y++) { 184 | 185 | HSLAPixel & stencil_pixel = secondImage.getPixel(x, y); 186 | HSLAPixel & base_pixel = firstImage.getPixel(x, y); 187 | 188 | if( 1.0 == stencil_pixel.l ) 189 | { 190 | double luminance_upper_bound = 1.0; 191 | double watermark_luminance_offset = 0.2; 192 | // luminance + 0.2, but not exceed upper bound 1.0 193 | double new_base_pixel_luminance = min( base_pixel.l + watermark_luminance_offset, luminance_upper_bound ); 194 | 195 | // update base pixel luminance 196 | base_pixel.l = new_base_pixel_luminance; 197 | } 198 | 199 | 200 | 201 | } 202 | //end of for y loop 203 | } 204 | //end of for x loop 205 | 206 | 207 | 208 | return firstImage; 209 | } 210 | //end of function PNG watermark(PNG firstImage, PNG secondImage) 211 | -------------------------------------------------------------------------------- /Course_1_Object-Oriented Data Structures in Cpp/Week_4_Engineering Cpp software solution/Week4_Image_Project/Week4_Image_Project/ImageTransform.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include "uiuc/PNG.h" 4 | using namespace uiuc; 5 | 6 | PNG grayscale(PNG image); 7 | PNG createSpotlight(PNG image, int centerX, int centerY); 8 | PNG illinify(PNG image); 9 | PNG watermark(PNG firstImage, PNG secondImage); 10 | -------------------------------------------------------------------------------- /Course_1_Object-Oriented Data Structures in Cpp/Week_4_Engineering Cpp software solution/Week4_Image_Project/Week4_Image_Project/ImageTransform_submission.zip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/brianchiang-tw/Accelerated_Computer_Science_Fundamentals_Specialization/ff5f477f10e514c46e417a8dab4d4e60100725d5/Course_1_Object-Oriented Data Structures in Cpp/Week_4_Engineering Cpp software solution/Week4_Image_Project/Week4_Image_Project/ImageTransform_submission.zip -------------------------------------------------------------------------------- /Course_1_Object-Oriented Data Structures in Cpp/Week_4_Engineering Cpp software solution/Week4_Image_Project/Week4_Image_Project/Makefile: -------------------------------------------------------------------------------- 1 | # Executable names: 2 | EXE = ImageTransform 3 | TEST = test 4 | 5 | # Add all object files needed for compiling: 6 | EXE_OBJ = main.o 7 | OBJS = main.o ImageTransform.o 8 | 9 | # Generated files 10 | CLEAN_RM = out-*.png 11 | 12 | # Include the master templated makefile: 13 | include uiuc/make/uiuc.mk 14 | -------------------------------------------------------------------------------- /Course_1_Object-Oriented Data Structures in Cpp/Week_4_Engineering Cpp software solution/Week4_Image_Project/Week4_Image_Project/alma.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/brianchiang-tw/Accelerated_Computer_Science_Fundamentals_Specialization/ff5f477f10e514c46e417a8dab4d4e60100725d5/Course_1_Object-Oriented Data Structures in Cpp/Week_4_Engineering Cpp software solution/Week4_Image_Project/Week4_Image_Project/alma.png -------------------------------------------------------------------------------- /Course_1_Object-Oriented Data Structures in Cpp/Week_4_Engineering Cpp software solution/Week4_Image_Project/Week4_Image_Project/main.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * @file main.cpp 3 | * A simple C++ program that manipulates an image. 4 | * 5 | * @author University of Illinois CS 225 Course Staff 6 | * @author Updated by University of Illinois CS 400 Course Staff 7 | **/ 8 | 9 | #include "ImageTransform.h" 10 | #include "uiuc/PNG.h" 11 | 12 | int main() { 13 | uiuc::PNG png, png2, result; 14 | 15 | png.readFromFile("alma.png"); 16 | result = grayscale(png); 17 | result.writeToFile("out-grayscale.png"); 18 | 19 | result = createSpotlight(png, 450, 150); 20 | result.writeToFile("out-spotlight.png"); 21 | 22 | result = illinify(png); 23 | result.writeToFile("out-illinify.png"); 24 | 25 | png2.readFromFile("overlay.png"); 26 | result = watermark(png, png2); 27 | result.writeToFile("out-watermark.png"); 28 | 29 | return 0; 30 | } 31 | -------------------------------------------------------------------------------- /Course_1_Object-Oriented Data Structures in Cpp/Week_4_Engineering Cpp software solution/Week4_Image_Project/Week4_Image_Project/overlay.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/brianchiang-tw/Accelerated_Computer_Science_Fundamentals_Specialization/ff5f477f10e514c46e417a8dab4d4e60100725d5/Course_1_Object-Oriented Data Structures in Cpp/Week_4_Engineering Cpp software solution/Week4_Image_Project/Week4_Image_Project/overlay.png -------------------------------------------------------------------------------- /Course_1_Object-Oriented Data Structures in Cpp/Week_4_Engineering Cpp software solution/Week4_Image_Project/Week4_Image_Project/test: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/brianchiang-tw/Accelerated_Computer_Science_Fundamentals_Specialization/ff5f477f10e514c46e417a8dab4d4e60100725d5/Course_1_Object-Oriented Data Structures in Cpp/Week_4_Engineering Cpp software solution/Week4_Image_Project/Week4_Image_Project/test -------------------------------------------------------------------------------- /Course_1_Object-Oriented Data Structures in Cpp/Week_4_Engineering Cpp software solution/Week4_Image_Project/Week4_Image_Project/tests/part1.cpp: -------------------------------------------------------------------------------- 1 | 2 | // Original version by CS 225 Course Staff 3 | // CS 400 revision with member type testing by Eric Huber 4 | 5 | #include 6 | 7 | #include "../uiuc/catch/catch.hpp" 8 | 9 | #include "../ImageTransform.h" 10 | #include "../uiuc/PNG.h" 11 | #include "../uiuc/HSLAPixel.h" 12 | 13 | namespace uiuc_testing { 14 | // Based on the floating point type detector template here: 15 | // https://en.cppreference.com/w/cpp/types/is_floating_point 16 | template< class T > 17 | struct is_double : std::integral_constant::value> {}; 18 | } 19 | 20 | TEST_CASE("HSLAPixel should have member h as double", "[weight=1]") { 21 | REQUIRE(uiuc_testing::is_double::value); 22 | } 23 | 24 | TEST_CASE("HSLAPixel should have member s as double", "[weight=1]") { 25 | REQUIRE(uiuc_testing::is_double::value); 26 | } 27 | 28 | TEST_CASE("HSLAPixel should have member l as double", "[weight=1]") { 29 | REQUIRE(uiuc_testing::is_double::value); 30 | } 31 | 32 | TEST_CASE("HSLAPixel should have member a as double", "[weight=1]") { 33 | REQUIRE(uiuc_testing::is_double::value); 34 | } 35 | 36 | // The following tests are disabled. 37 | // They evaluate constructors, but the Week 1-2 content doesn't cover constructors currently. 38 | #undef DO_PART1_CTOR_TESTS 39 | #ifdef DO_PART1_CTOR_TESTS 40 | 41 | // HSLAPixel default constructor 42 | TEST_CASE("HSLAPixel's default constructor should create a white pixel", "[weight=1]") { 43 | HSLAPixel pixel; 44 | REQUIRE( pixel.l == 1 ); 45 | } 46 | 47 | TEST_CASE("HSLAPixel's default constructor should create an opaque pixel", "[weight=1]") { 48 | HSLAPixel pixel; 49 | REQUIRE( pixel.a == 1 ); 50 | } 51 | 52 | 53 | // HSLAPixel 3-param constructor 54 | TEST_CASE("HSLAPixel's HSL constructor should create a pixel with provided HSL values", "[weight=1]") { 55 | HSLAPixel pixel(260, 0.8, 0.7); 56 | REQUIRE( pixel.h == 260 ); 57 | REQUIRE( pixel.s == 0.8 ); 58 | REQUIRE( pixel.l == 0.7 ); 59 | } 60 | 61 | TEST_CASE("HSLAPixel's HSL constructor should create an opaque pixel", "[weight=1]") { 62 | HSLAPixel pixel(260, 0.8, 0.7); 63 | REQUIRE( pixel.a == 1 ); 64 | } 65 | 66 | 67 | // HSLAPixel 4-param constructor 68 | TEST_CASE("HSLAPixel's HSLA constructor should create a pixel with provided HSLA values", "[weight=1]") { 69 | HSLAPixel pixel(260, 0.8, 0.7, 0.4); 70 | REQUIRE( pixel.h == 260 ); 71 | REQUIRE( pixel.s == 0.8 ); 72 | REQUIRE( pixel.l == 0.7 ); 73 | REQUIRE( pixel.a == 0.4 ); 74 | } 75 | 76 | #endif 77 | 78 | -------------------------------------------------------------------------------- /Course_1_Object-Oriented Data Structures in Cpp/Week_4_Engineering Cpp software solution/Week4_Image_Project/Week4_Image_Project/tests/part2.cpp: -------------------------------------------------------------------------------- 1 | #include "../uiuc/catch/catch.hpp" 2 | 3 | #include "../ImageTransform.h" 4 | #include "../uiuc/PNG.h" 5 | #include "../uiuc/HSLAPixel.h" 6 | 7 | PNG createRainbowPNG() { 8 | PNG png(360, 100); 9 | for (unsigned x = 0; x < png.width(); x++) { 10 | for (unsigned y = 0; y < png.height(); y++) { 11 | HSLAPixel & pixel = png.getPixel(x, y); 12 | pixel.h = x; 13 | pixel.s = y / 100.0; 14 | pixel.l = 0.5; 15 | } 16 | } 17 | return png; 18 | } 19 | 20 | PNG createWatermark() { 21 | PNG png(360, 100); 22 | for (unsigned x = 0; x < png.width(); x++) { 23 | for (unsigned y = 0; y < png.height(); y++) { 24 | HSLAPixel & pixel = png.getPixel(x, y); 25 | if (y >= 10 && y <= 30) { pixel.l = 1; } 26 | else { pixel.l = 0; } 27 | } 28 | } 29 | return png; 30 | } 31 | 32 | 33 | 34 | TEST_CASE("createSpotlight", "[weight=1]") { 35 | PNG png = createRainbowPNG(); 36 | PNG result = createSpotlight(png, 100, 50); 37 | 38 | SECTION("Spotlight should not modify the center pixel") { 39 | REQUIRE( png.getPixel(100, 50).l == result.getPixel(100, 50).l ); 40 | } 41 | 42 | SECTION("Spotlight should create an 80% dark pixel >160 pixels away") { 43 | REQUIRE( png.getPixel(320, 50).l * 0.2 == Approx(result.getPixel(320, 50).l) ); 44 | } 45 | 46 | SECTION("Spotlight should be correct at 20 pixels away from center") { 47 | REQUIRE( png.getPixel(100, 50 + 20).l * 0.9 == Approx(result.getPixel(100, 50 + 20).l) ); 48 | } 49 | 50 | SECTION("Spotlight should be correct at 5 pixels away from center") { 51 | REQUIRE( png.getPixel(100 + 3, 50 + 4).l * 0.975 == Approx(result.getPixel(100 + 3, 50 + 4).l) ); 52 | } 53 | } 54 | 55 | 56 | TEST_CASE("illinify", "[weight=1]") { 57 | PNG png = createRainbowPNG(); 58 | PNG result = illinify(png); 59 | 60 | SECTION("After illinify, image should contain only orange and blue hues") { 61 | for (unsigned x = 0; x < result.width(); x++) { 62 | for (unsigned y = 0; y < result.height(); y++) { 63 | if (result.getPixel(x, y).h != 11 && result.getPixel(x, y).h != 216) { 64 | FAIL("The hue of (" << x << "," << y <<") is " << result.getPixel(x, y).h << ", not Illini orange or blue."); 65 | } 66 | } 67 | } 68 | } 69 | 70 | SECTION("Pixels closest to blue should become blue") { 71 | REQUIRE( result.getPixel(200, 4).h == 216 ); 72 | REQUIRE( result.getPixel(210, 12).h == 216 ); 73 | REQUIRE( result.getPixel(220, 23).h == 216 ); 74 | REQUIRE( result.getPixel(230, 44).h == 216 ); 75 | } 76 | 77 | SECTION("Pixels closest to orange should become orange") { 78 | REQUIRE( result.getPixel(10, 4).h == 11 ); 79 | REQUIRE( result.getPixel(30, 12).h == 11 ); 80 | REQUIRE( result.getPixel(40, 23).h == 11 ); 81 | REQUIRE( result.getPixel(40, 44).h == 11 ); 82 | } 83 | 84 | } 85 | 86 | TEST_CASE("illinify_edge_case", "[weight=1]") { 87 | PNG png = createRainbowPNG(); 88 | PNG result = illinify(png); 89 | 90 | SECTION("Reassigned hues should wrap around correctly: h=359 is closer to orange (11) than blue (216)") { 91 | REQUIRE( result.getPixel(330, 4).h == 11 ); 92 | REQUIRE( result.getPixel(340, 12).h == 11 ); 93 | REQUIRE( result.getPixel(350, 23).h == 11 ); 94 | } 95 | } 96 | 97 | TEST_CASE("watermark", "[weight=1]") { 98 | PNG png = createRainbowPNG(); 99 | PNG wm = createWatermark(); 100 | 101 | PNG result = watermark(png, wm); 102 | 103 | SECTION("Pixels without watermark should be unchanged") { 104 | REQUIRE( png.getPixel(100, 50).l == result.getPixel(100, 50).l ); 105 | REQUIRE( png.getPixel(200, 80).l == result.getPixel(200, 80).l ); 106 | } 107 | 108 | SECTION("Pixels with watermark should be changed") { 109 | REQUIRE( png.getPixel(100, 15).l + 0.2 == result.getPixel(100, 15).l ); 110 | REQUIRE( png.getPixel(200, 25).l + 0.2 == result.getPixel(200, 25).l ); 111 | } 112 | } 113 | -------------------------------------------------------------------------------- /Course_1_Object-Oriented Data Structures in Cpp/Week_4_Engineering Cpp software solution/Week4_Image_Project/Week4_Image_Project/uiuc/HSLAPixel.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * @file HSLAPixel.cpp 3 | * Implementation of the HSLAPixel class for use in with the PNG library. 4 | * 5 | * @author University of Illinois CS 225 Course Staff 6 | * @version 2018r1-lab1 - Updated for CS 400 7 | */ 8 | 9 | #include 10 | #include 11 | #include "HSLAPixel.h" 12 | using namespace std; 13 | 14 | namespace uiuc { 15 | 16 | // default constructor 17 | HSLAPixel::HSLAPixel():HSLAPixel(0.0, 0.0, 0.0, 0.0) 18 | { 19 | 20 | } 21 | 22 | // constructor with parameters hue, saturation, luminance, alpha 23 | HSLAPixel::HSLAPixel(double h_val, double s_val, double l_val, double a_val) 24 | { 25 | h = h_val; 26 | s = s_val; 27 | l = l_val; 28 | a = a_val; 29 | } 30 | 31 | 32 | HSLAPixel::~HSLAPixel() 33 | { 34 | 35 | } 36 | 37 | } 38 | //End of namespae uiuc -------------------------------------------------------------------------------- /Course_1_Object-Oriented Data Structures in Cpp/Week_4_Engineering Cpp software solution/Week4_Image_Project/Week4_Image_Project/uiuc/HSLAPixel.h: -------------------------------------------------------------------------------- 1 | /** 2 | * @file HSLAPixel.h 3 | * 4 | * @author University of Illinois CS 225 Course Staff 5 | * @version 2018r1-lab1 - Updated for CS 400 6 | */ 7 | 8 | #pragma once 9 | 10 | #include 11 | #include 12 | 13 | namespace uiuc { 14 | 15 | // Put your HSLAPixel class definition here. 16 | // (Remember to end it with a semicolon!) 17 | class HSLAPixel { 18 | 19 | public: 20 | 21 | HSLAPixel(); 22 | HSLAPixel(double hue,double saturation, double luminance, double alpha); 23 | ~HSLAPixel(); 24 | 25 | // hue 26 | double h; 27 | 28 | // saturation 29 | double s; 30 | 31 | // luminance 32 | double l; 33 | 34 | // alpha 35 | double a; 36 | }; 37 | //End of class definition of HSLAPixel 38 | 39 | } 40 | //End of namespae uiuc -------------------------------------------------------------------------------- /Course_1_Object-Oriented Data Structures in Cpp/Week_4_Engineering Cpp software solution/Week4_Image_Project/Week4_Image_Project/uiuc/PNG.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * @file PNG.cpp 3 | * Implementation of a simple PNG class using HSLAPixels and the lodepng PNG library. 4 | * 5 | * @author University of Illinois CS 225 Course Staff 6 | * @version 2018r1-lab1 - Updated for CS 400 7 | */ 8 | 9 | #include 10 | #include 11 | #include 12 | #include 13 | #include 14 | #include "lodepng/lodepng.h" 15 | #include "HSLAPixel.h" 16 | #include "PNG.h" 17 | #include "RGB_HSL.h" 18 | 19 | namespace uiuc { 20 | void PNG::_copy(PNG const & other) { 21 | // Clear self 22 | delete[] imageData_; 23 | 24 | // Copy `other` to self 25 | width_ = other.width_; 26 | height_ = other.height_; 27 | imageData_ = new HSLAPixel[width_ * height_]; 28 | for (unsigned i = 0; i < width_ * height_; i++) { 29 | imageData_[i] = other.imageData_[i]; 30 | } 31 | } 32 | 33 | PNG::PNG() { 34 | width_ = 0; 35 | height_ = 0; 36 | imageData_ = NULL; 37 | } 38 | 39 | PNG::PNG(unsigned int width, unsigned int height) { 40 | width_ = width; 41 | height_ = height; 42 | imageData_ = new HSLAPixel[width * height]; 43 | } 44 | 45 | PNG::PNG(PNG const & other) { 46 | imageData_ = NULL; 47 | _copy(other); 48 | } 49 | 50 | PNG::~PNG() { 51 | delete[] imageData_; 52 | } 53 | 54 | PNG const & PNG::operator=(PNG const & other) { 55 | if (this != &other) { _copy(other); } 56 | return *this; 57 | } 58 | 59 | bool PNG::operator==(PNG const & other) const { 60 | if (width_ != other.width_) { return false; } 61 | if (height_ != other.height_) { return false; } 62 | 63 | for (unsigned i = 0; i < width_ * height_; i++) { 64 | HSLAPixel & p1 = imageData_[i]; 65 | HSLAPixel & p2 = other.imageData_[i]; 66 | if (p1.h != p2.h || p1.s != p2.s || p1.l != p2.l || p1.a != p2.a) { return false; } 67 | } 68 | 69 | return true; 70 | } 71 | 72 | bool PNG::operator!=(PNG const & other) const { 73 | return !(*this == other); 74 | } 75 | 76 | HSLAPixel & PNG::getPixel(unsigned int x, unsigned int y) const { 77 | if (width_ == 0 || height_ == 0) { 78 | cerr << "ERROR: Call to uiuc::PNG::getPixel() made on an image with no pixels." << endl; 79 | assert(width_ > 0); 80 | assert(height_ > 0); 81 | } 82 | 83 | if (x >= width_) { 84 | cerr << "WARNING: Call to uiuc::PNG::getPixel(" << x << "," << y << ") tries to access x=" << x 85 | << ", which is outside of the image (image width: " << width_ << ")." << endl; 86 | cerr << " : Truncating x to " << (width_ - 1) << endl; 87 | x = width_ - 1; 88 | } 89 | 90 | if (y >= height_) { 91 | cerr << "WARNING: Call to uiuc::PNG::getPixel(" << x << "," << y << ") tries to access y=" << y 92 | << ", which is outside of the image (image height: " << height_ << ")." << endl; 93 | cerr << " : Truncating y to " << (height_ - 1) << endl; 94 | y = height_ - 1; 95 | } 96 | 97 | unsigned index = x + (y * width_); 98 | return imageData_[index]; 99 | } 100 | 101 | bool PNG::readFromFile(string const & fileName) { 102 | vector byteData; 103 | unsigned error = lodepng::decode(byteData, width_, height_, fileName); 104 | 105 | if (error) { 106 | cerr << "PNG decoder error " << error << ": " << lodepng_error_text(error) << endl; 107 | return false; 108 | } 109 | 110 | delete[] imageData_; 111 | imageData_ = new HSLAPixel[width_ * height_]; 112 | 113 | for (unsigned i = 0; i < byteData.size(); i += 4) { 114 | rgbaColor rgb; 115 | rgb.r = byteData[i]; 116 | rgb.g = byteData[i + 1]; 117 | rgb.b = byteData[i + 2]; 118 | rgb.a = byteData[i + 3]; 119 | 120 | hslaColor hsl = rgb2hsl(rgb); 121 | HSLAPixel & pixel = imageData_[i/4]; 122 | pixel.h = hsl.h; 123 | pixel.s = hsl.s; 124 | pixel.l = hsl.l; 125 | pixel.a = hsl.a; 126 | } 127 | 128 | return true; 129 | } 130 | 131 | bool PNG::writeToFile(string const & fileName) { 132 | unsigned char *byteData = new unsigned char[width_ * height_ * 4]; 133 | 134 | for (unsigned i = 0; i < width_ * height_; i++) { 135 | hslaColor hsl; 136 | hsl.h = imageData_[i].h; 137 | hsl.s = imageData_[i].s; 138 | hsl.l = imageData_[i].l; 139 | hsl.a = imageData_[i].a; 140 | 141 | rgbaColor rgb = hsl2rgb(hsl); 142 | 143 | byteData[(i * 4)] = rgb.r; 144 | byteData[(i * 4) + 1] = rgb.g; 145 | byteData[(i * 4) + 2] = rgb.b; 146 | byteData[(i * 4) + 3] = rgb.a; 147 | } 148 | 149 | unsigned error = lodepng::encode(fileName, byteData, width_, height_); 150 | if (error) { 151 | cerr << "PNG encoding error " << error << ": " << lodepng_error_text(error) << endl; 152 | } 153 | 154 | delete[] byteData; 155 | return (error == 0); 156 | } 157 | 158 | unsigned int PNG::width() const { 159 | return width_; 160 | } 161 | 162 | unsigned int PNG::height() const { 163 | return height_; 164 | } 165 | 166 | void PNG::resize(unsigned int newWidth, unsigned int newHeight) { 167 | // Create a new vector to store the image data for the new (resized) image 168 | HSLAPixel * newImageData = new HSLAPixel[newWidth * newHeight]; 169 | 170 | // Copy the current data to the new image data, using the existing pixel 171 | // for coordinates within the bounds of the old image size 172 | for (unsigned x = 0; x < newWidth; x++) { 173 | for (unsigned y = 0; y < newHeight; y++) { 174 | if (x < width_ && y < height_) { 175 | HSLAPixel & oldPixel = this->getPixel(x, y); 176 | HSLAPixel & newPixel = newImageData[ (x + (y * newWidth)) ]; 177 | newPixel = oldPixel; 178 | } 179 | } 180 | } 181 | 182 | // Clear the existing image 183 | delete[] imageData_; 184 | 185 | // Update the image to reflect the new image size and data 186 | width_ = newWidth; 187 | height_ = newHeight; 188 | imageData_ = newImageData; 189 | } 190 | 191 | std::size_t PNG::computeHash() const { 192 | std::hash hashFunction; 193 | std::size_t hash = 0; 194 | 195 | 196 | for (unsigned x = 0; x < this->width(); x++) { 197 | for (unsigned y = 0; y < this->height(); y++) { 198 | HSLAPixel & pixel = this->getPixel(x, y); 199 | hash = (hash << 1) + hash + hashFunction(pixel.h); 200 | hash = (hash << 1) + hash + hashFunction(pixel.s); 201 | hash = (hash << 1) + hash + hashFunction(pixel.l); 202 | hash = (hash << 1) + hash + hashFunction(pixel.a); 203 | } 204 | } 205 | 206 | return hash; 207 | } 208 | 209 | std::ostream & operator << ( std::ostream& os, PNG const& png ) { 210 | os << "PNG(w=" << png.width() << ", h=" << png.height() << ", hash=" << std::hex << png.computeHash() << std::dec << ")"; 211 | return os; 212 | } 213 | 214 | } 215 | -------------------------------------------------------------------------------- /Course_1_Object-Oriented Data Structures in Cpp/Week_4_Engineering Cpp software solution/Week4_Image_Project/Week4_Image_Project/uiuc/PNG.h: -------------------------------------------------------------------------------- 1 | /** 2 | * @file PNG.h 3 | * 4 | * @author University of Illinois CS 225 Course Staff 5 | * @version 2018r1 - Updated for CS 400 6 | */ 7 | 8 | #pragma once 9 | 10 | #include 11 | #include 12 | #include "HSLAPixel.h" 13 | 14 | using namespace std; 15 | 16 | namespace uiuc { 17 | class PNG { 18 | public: 19 | /** 20 | * Creates an empty PNG image. 21 | */ 22 | PNG(); 23 | 24 | /** 25 | * Creates a PNG image of the specified dimensions. 26 | * @param width Width of the new image. 27 | * @param height Height of the new image. 28 | */ 29 | PNG(unsigned int width, unsigned int height); 30 | 31 | /** 32 | * Copy constructor: creates a new PNG image that is a copy of 33 | * another. 34 | * @param other PNG to be copied. 35 | */ 36 | PNG(PNG const & other); 37 | 38 | /** 39 | * Destructor: frees all memory associated with a given PNG object. 40 | * Invoked by the system. 41 | */ 42 | ~PNG(); 43 | 44 | /** 45 | * Assignment operator for setting two PNGs equal to one another. 46 | * @param other Image to copy into the current image. 47 | * @return The current image for assignment chaining. 48 | */ 49 | PNG const & operator= (PNG const & other); 50 | 51 | /** 52 | * Equality operator: checks if two images are the same. 53 | * @param other Image to be checked. 54 | * @return Whether the current image is equal to the other image. 55 | */ 56 | bool operator== (PNG const & other) const; 57 | 58 | /** 59 | * Inequality operator: checks if two images are different. 60 | * @param other Image to be checked. 61 | * @return Whether the current image differs from the other image. 62 | */ 63 | bool operator!= (PNG const & other) const; 64 | 65 | 66 | /** 67 | * Reads in a PNG image from a file. 68 | * Overwrites any current image content in the PNG. 69 | * @param fileName Name of the file to be read from. 70 | * @return true, if the image was successfully read and loaded. 71 | */ 72 | bool readFromFile(string const & fileName); 73 | 74 | /** 75 | * Writes a PNG image to a file. 76 | * @param fileName Name of the file to be written. 77 | * @return true, if the image was successfully written. 78 | */ 79 | bool writeToFile(string const & fileName); 80 | 81 | /** 82 | * Pixel access operator. Gets a reference to the pixel at the given 83 | * coordinates in the image. (0,0) is the upper left corner. 84 | * This reference allows the image to be changed. 85 | * @param x X-coordinate for the pixel reference to be grabbed from. 86 | * @param y Y-coordinate for the pixel reference to be grabbed from. 87 | * @return A reference to the pixel at the given coordinates. 88 | */ 89 | HSLAPixel & getPixel(unsigned int x, unsigned int y) const; 90 | 91 | /** 92 | * Gets the width of this image. 93 | * @return Width of the image. 94 | */ 95 | unsigned int width() const; 96 | 97 | /** 98 | * Gets the height of this image. 99 | * @return Height of the image. 100 | */ 101 | unsigned int height() const; 102 | 103 | /** 104 | * Resizes the image to the given coordinates. Attempts to preserve 105 | * existing pixel data in the image when doing so, but will crop if 106 | * necessary. No pixel interpolation is done. 107 | * @param newWidth New width of the image. 108 | * @param newHeight New height of the image. 109 | */ 110 | void resize(unsigned int newWidth, unsigned int newHeight); 111 | 112 | /** 113 | * Computes a hash of the contents of the image. 114 | */ 115 | std::size_t computeHash() const; 116 | 117 | private: 118 | unsigned int width_; /*< Width of the image */ 119 | unsigned int height_; /*< Height of the image */ 120 | HSLAPixel *imageData_; /*< Array of pixels */ 121 | HSLAPixel defaultPixel_; /*< Default pixel, returned in cases of errors */ 122 | 123 | /** 124 | * Copeies the contents of `other` to self 125 | */ 126 | void _copy(PNG const & other); 127 | }; 128 | 129 | std::ostream & operator<<(std::ostream & out, PNG const & pixel); 130 | std::stringstream & operator<<(std::stringstream & out, PNG const & pixel); 131 | } 132 | 133 | -------------------------------------------------------------------------------- /Course_1_Object-Oriented Data Structures in Cpp/Week_4_Engineering Cpp software solution/Week4_Image_Project/Week4_Image_Project/uiuc/RGB_HSL.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include 4 | 5 | namespace uiuc { 6 | typedef struct { 7 | unsigned char r, g, b, a; // [0, 255] 8 | } rgbaColor; 9 | 10 | typedef struct { 11 | double h; // angle in degrees, [0, 360] 12 | double s; // [0, 1] 13 | double l; // [0, 1] 14 | double a; // [0, 1] 15 | } hslaColor; 16 | 17 | static hslaColor rgb2hsl(rgbaColor rgb) { 18 | hslaColor hsl; 19 | double r, g, b, min, max, chroma; 20 | 21 | // Change rgb into [0, 1] 22 | r = rgb.r / 255.0; 23 | g = rgb.g / 255.0; 24 | b = rgb.b / 255.0; 25 | 26 | // HSV Calculations -- formulas sourced from https://en.wikipedia.org/wiki/HSL_and_HSV 27 | // Compute constants 28 | min = (r < g) ? r : g; 29 | min = (min < b) ? min : b; 30 | 31 | max = (r > g) ? r : g; 32 | max = (max > b) ? max : b; 33 | 34 | chroma = max - min; 35 | 36 | // Compute A 37 | hsl.a = rgb.a / 255.0; 38 | 39 | // Compute L 40 | hsl.l = 0.5 * (max + min); 41 | 42 | // Check for black, white, and shades of gray, where H is undefined, 43 | // S is always 0, and L controls the shade of gray. Mathematically, this 44 | // is true when chroma == 0, but we'll use a near-zero value to account 45 | // for floating point errors. 46 | // 47 | // This check is required here, or division by zero will occur when 48 | // calculating S and H below. 49 | if (chroma < 0.0001 || max < 0.0001) { 50 | hsl.h = hsl.s = 0; 51 | return hsl; 52 | } 53 | 54 | // Compute S 55 | hsl.s = chroma / (1 - fabs((2 * hsl.l) - 1)); 56 | 57 | // Compute H 58 | if (max == r) { hsl.h = fmod((g - b) / chroma, 6); } 59 | else if (max == g) { hsl.h = ((b - r) / chroma) + 2; } 60 | else { hsl.h = ((r - g) / chroma) + 4; } 61 | 62 | hsl.h *= 60; 63 | if (hsl.h < 0) { hsl.h += 360; } 64 | 65 | // Return result 66 | return hsl; 67 | } 68 | 69 | static rgbaColor hsl2rgb(hslaColor hsl) { 70 | rgbaColor rgb; 71 | 72 | // HSV Calculations -- formulas sourced from https://en.wikipedia.org/wiki/HSL_and_HSV 73 | if (hsl.s <= 0.001) { 74 | rgb.r = rgb.g = rgb.b = round(hsl.l * 255); 75 | } else { 76 | double c = (1 - fabs((2 * hsl.l) - 1)) * hsl.s; 77 | double hh = hsl.h / 60; 78 | double x = c * (1 - fabs(fmod(hh, 2) - 1)); 79 | double r, g, b; 80 | 81 | if (hh <= 1) { r = c; g = x; b = 0; } 82 | else if (hh <= 2) { r = x; g = c; b = 0; } 83 | else if (hh <= 3) { r = 0; g = c; b = x; } 84 | else if (hh <= 4) { r = 0; g = x; b = c; } 85 | else if (hh <= 5) { r = x; g = 0; b = c; } 86 | else { r = c; g = 0; b = x; } 87 | 88 | double m = hsl.l - (0.5 * c); 89 | rgb.r = round((r + m) * 255); 90 | rgb.g = round((g + m) * 255); 91 | rgb.b = round((b + m) * 255); 92 | } 93 | 94 | rgb.a = round(hsl.a * 255); 95 | return rgb; 96 | } 97 | } -------------------------------------------------------------------------------- /Course_1_Object-Oriented Data Structures in Cpp/Week_4_Engineering Cpp software solution/Week4_Image_Project/Week4_Image_Project/uiuc/catch/catchmain.cpp: -------------------------------------------------------------------------------- 1 | #define CATCH_CONFIG_MAIN 2 | #include "catch.hpp" 3 | -------------------------------------------------------------------------------- /Course_1_Object-Oriented Data Structures in Cpp/Week_4_Engineering Cpp software solution/Week4_Image_Project/Week4_Image_Project/uiuc/make/uiuc.mk: -------------------------------------------------------------------------------- 1 | # Created by Wade Fagen-Ulmschneider 2 | # A few tweaks for CS 400 by Eric Huber 3 | 4 | ZIP_FILE = ImageTransform_submission.zip 5 | COLLECTED_FILES = uiuc/HSLAPixel.h uiuc/HSLAPixel.cpp ImageTransform.h ImageTransform.cpp 6 | 7 | # Add standard object files (HSLAPixel, PNG, and LodePNG) 8 | OBJS += uiuc/HSLAPixel.o uiuc/PNG.o uiuc/lodepng/lodepng.o 9 | 10 | # Use ./.objs to store all .o file (keeping the directory clean) 11 | OBJS_DIR = .objs 12 | 13 | # Use all .cpp files in /tests/ 14 | OBJS_TEST = $(filter-out $(EXE_OBJ), $(OBJS)) 15 | CPP_TEST = $(wildcard tests/*.cpp) 16 | CPP_TEST += uiuc/catch/catchmain.cpp 17 | OBJS_TEST += $(CPP_TEST:.cpp=.o) 18 | 19 | # Config 20 | CXX_CLANG = clang++ 21 | CXX_GNU = g++ 22 | CXX_WHICH = $(CXX_GNU) 23 | CXX = $(CXX_WHICH) 24 | LD = $(CXX_WHICH) 25 | # STDVERSION = -std=c++1y # deprecated nomenclature 26 | STDVERSION = -std=c++14 # proper but requires newer compiler versions (for better or worse) 27 | STDLIBVERSION_CLANG = -stdlib=libc++ # Clang's version; not present on default AWS Cloud9 instance 28 | STDLIBVERSION_GNU = # blank on purpose; default GNU library 29 | STDLIBVERSION = $(STDLIBVERSION_GNU) 30 | WARNINGS = -pedantic -Wall -Wfatal-errors -Wextra -Wno-unused-parameter -Wno-unused-variable 31 | CXXFLAGS = $(CS400) $(STDVERSION) $(STDLIBVERSION) -g -O0 $(WARNINGS) -MMD -MP -msse2 -c 32 | LDFLAGS = $(CS400) $(STDVERSION) $(STDLIBVERSION) -lpthread 33 | ASANFLAGS = -fsanitize=address -fno-omit-frame-pointer 34 | 35 | # Rules for first executable 36 | $(EXE): 37 | $(LD) $^ $(LDFLAGS) -o $@ 38 | @echo "" 39 | @echo " Built the main executable program file for the project: " $(EXE) 40 | @echo " (Make sure you try \"make test\" too!)" 41 | @echo "" 42 | 43 | # Rule for `all` 44 | all: $(EXE) $(TEST) 45 | 46 | # Pattern rules for object files 47 | $(OBJS_DIR): 48 | @mkdir -p $(OBJS_DIR) 49 | @mkdir -p $(OBJS_DIR)/uiuc 50 | @mkdir -p $(OBJS_DIR)/uiuc/catch 51 | @mkdir -p $(OBJS_DIR)/uiuc/lodepng 52 | @mkdir -p $(OBJS_DIR)/tests 53 | 54 | $(OBJS_DIR)/%.o: %.cpp | $(OBJS_DIR) 55 | $(CXX) $(CXXFLAGS) $< -o $@ 56 | 57 | # Rules for executables 58 | $(TEST): 59 | $(LD) $^ $(LDFLAGS) -o $@ 60 | @echo "" 61 | @echo " Built the test suite program: " $(TEST) 62 | @echo "" 63 | 64 | # Executable dependencies 65 | $(EXE): $(patsubst %.o, $(OBJS_DIR)/%.o, $(OBJS)) 66 | $(TEST): $(patsubst %.o, $(OBJS_DIR)/%.o, $(OBJS_TEST)) 67 | 68 | # Include automatically generated dependencies 69 | -include $(OBJS_DIR)/*.d 70 | -include $(OBJS_DIR)/uiuc/*.d 71 | -include $(OBJS_DIR)/uiuc/catch/*.d 72 | -include $(OBJS_DIR)/uiuc/lodepng/*.d 73 | -include $(OBJS_DIR)/tests/*.d 74 | 75 | clean: 76 | rm -rf $(EXE) $(TEST) $(OBJS_DIR) $(CLEAN_RM) $(ZIP_FILE) 77 | 78 | tidy: clean 79 | rm -rf doc 80 | 81 | zip: 82 | @echo "!!! Preparing submission zip with student code..." 83 | @echo "!!! Make sure you have already tried compiling and testing your code" 84 | @echo "!!! thoroughly before submitting the zip on Coursera!" 85 | @echo "" 86 | @echo "Removing any previous version of zip file..." 87 | rm -rf $(ZIP_FILE) 88 | @echo "Creating new file..." 89 | zip $(ZIP_FILE) $(COLLECTED_FILES) 90 | @echo "Created zip file: " $(ZIP_FILE) 91 | 92 | .PHONY: all tidy clean zip 93 | -------------------------------------------------------------------------------- /Course_1_Object-Oriented Data Structures in Cpp/Week_4_Engineering Cpp software solution/Week4_Image_Project_full implementation.zip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/brianchiang-tw/Accelerated_Computer_Science_Fundamentals_Specialization/ff5f477f10e514c46e417a8dab4d4e60100725d5/Course_1_Object-Oriented Data Structures in Cpp/Week_4_Engineering Cpp software solution/Week4_Image_Project_full implementation.zip -------------------------------------------------------------------------------- /Course_1_Object-Oriented Data Structures in Cpp/Week_4_Engineering Cpp software solution/Week_4_Challenge_and_Reference Solution.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/brianchiang-tw/Accelerated_Computer_Science_Fundamentals_Specialization/ff5f477f10e514c46e417a8dab4d4e60100725d5/Course_1_Object-Oriented Data Structures in Cpp/Week_4_Engineering Cpp software solution/Week_4_Challenge_and_Reference Solution.pdf -------------------------------------------------------------------------------- /Course_1_Object-Oriented Data Structures in Cpp/Week_4_Engineering Cpp software solution/Week_4_Challenge_implementation.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | /* Class Pair has already been 5 | * declared and defined with the 6 | * following constructor: 7 | * 8 | * Pair(int,int) 9 | * 10 | * that stores its two arguments in 11 | * two private member variables of Pair. 12 | * 13 | * Class sumPair has also already been 14 | * defined as follows: 15 | */ 16 | 17 | class Pair{ 18 | public: 19 | Pair(int num_1, int num_2): a(num_1), b(num_2) {} 20 | int a; 21 | int b; 22 | 23 | }; 24 | 25 | class sumPair : public Pair { 26 | public: 27 | int sum; 28 | sumPair(int,int); 29 | }; 30 | 31 | 32 | 33 | /* 34 | * Implement the constructor 35 | * sumPair(int,int) such that it 36 | * loads the two member variables of 37 | * the base Pair class with its 38 | * arguments, and initializes the 39 | * member variable sum with their sum. 40 | */ 41 | 42 | // constructor of sumPair 43 | sumPair::sumPair(int a, int b) : Pair( a, b) 44 | { 45 | sum = a + b; 46 | } 47 | 48 | 49 | 50 | /* Below is a main() function 51 | * you can use to test your 52 | * implementation of the 53 | * sumPair constructor. 54 | */ 55 | 56 | // expected output of main: 57 | /* 58 | sp(15,16).sum =31 59 | */ 60 | 61 | int main() { 62 | sumPair sp(15,16); 63 | std::cout << "sp(15,16).sum =" << sp.sum << std::endl; 64 | return 0; 65 | } -------------------------------------------------------------------------------- /Course_1_Object-Oriented Data Structures in Cpp/Week_4_Engineering Cpp software solution/Week_4_Challenge_implementation.exe: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/brianchiang-tw/Accelerated_Computer_Science_Fundamentals_Specialization/ff5f477f10e514c46e417a8dab4d4e60100725d5/Course_1_Object-Oriented Data Structures in Cpp/Week_4_Engineering Cpp software solution/Week_4_Challenge_implementation.exe -------------------------------------------------------------------------------- /Course_1_Object-Oriented Data Structures in Cpp/Week_4_Engineering Cpp software solution/Week_4_Image_Project_Description.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/brianchiang-tw/Accelerated_Computer_Science_Fundamentals_Specialization/ff5f477f10e514c46e417a8dab4d4e60100725d5/Course_1_Object-Oriented Data Structures in Cpp/Week_4_Engineering Cpp software solution/Week_4_Image_Project_Description.pdf -------------------------------------------------------------------------------- /Course_1_Object-Oriented Data Structures in Cpp/Week_4_Engineering Cpp software solution/Week_4_Image_Project_starter.zip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/brianchiang-tw/Accelerated_Computer_Science_Fundamentals_Specialization/ff5f477f10e514c46e417a8dab4d4e60100725d5/Course_1_Object-Oriented Data Structures in Cpp/Week_4_Engineering Cpp software solution/Week_4_Image_Project_starter.zip -------------------------------------------------------------------------------- /Course_1_Object-Oriented Data Structures in Cpp/Week_4_Engineering Cpp software solution/Week_4_Image_Project_submission.zip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/brianchiang-tw/Accelerated_Computer_Science_Fundamentals_Specialization/ff5f477f10e514c46e417a8dab4d4e60100725d5/Course_1_Object-Oriented Data Structures in Cpp/Week_4_Engineering Cpp software solution/Week_4_Image_Project_submission.zip -------------------------------------------------------------------------------- /Course_1_Object-Oriented Data Structures in Cpp/Week_4_Engineering Cpp software solution/Week_4_Quiz_and_Reference Manual.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/brianchiang-tw/Accelerated_Computer_Science_Fundamentals_Specialization/ff5f477f10e514c46e417a8dab4d4e60100725d5/Course_1_Object-Oriented Data Structures in Cpp/Week_4_Engineering Cpp software solution/Week_4_Quiz_and_Reference Manual.pdf -------------------------------------------------------------------------------- /Course_2_Ordered Data Structures/Week_1_Linear data structures/Week1_Challenge_implementation.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | std::stack reverse_stack(std::stack s) { 6 | std::stack reversed_s; 7 | 8 | // write code here that returns a stack whose elements are 9 | // in reverse order from those in stack s 10 | while( 0 != s.size() ) 11 | { 12 | int val = s.top(); 13 | s.pop(); 14 | reversed_s.push( val ); 15 | } 16 | 17 | 18 | return reversed_s; 19 | } 20 | 21 | std::queue reverse_queue(std::queue q) { 22 | std::queue reversed_q; 23 | std::stack stk; 24 | // write code here that returns a queue whose elements are 25 | // in reverse order from those in queue q 26 | 27 | while( 0 != q.size() ) 28 | { 29 | int val = q.front(); 30 | q.pop(); 31 | stk.push( val ); 32 | } 33 | 34 | while( 0 != stk.size() ) 35 | { 36 | int val = stk.top(); 37 | stk.pop(); 38 | reversed_q.push( val ); 39 | } 40 | 41 | return reversed_q; 42 | } 43 | 44 | void print_stack(std::string name, std::stack s) { 45 | std::cout << "stack " << name << ": "; 46 | while (!s.empty()) { 47 | std::cout << s.top() << " "; 48 | s.pop(); 49 | } 50 | std::cout << std::endl; 51 | } 52 | 53 | void print_queue(std::string name, std::queue q) { 54 | std::cout << "queue " << name << ": "; 55 | while (!q.empty()) { 56 | std::cout << q.front() << " "; 57 | q.pop(); 58 | } 59 | std::cout << std::endl; 60 | } 61 | 62 | 63 | 64 | // expected output 65 | /* 66 | 67 | stack s: 5 4 3 2 1 68 | stack reversed s: 1 2 3 4 5 69 | queue q: 1 2 3 4 5 70 | queue reversed q: 5 4 3 2 1 71 | 72 | */ 73 | int main() { 74 | std::stack s, rs; 75 | std::queue q, rq; 76 | 77 | s.push(1); s.push(2); s.push(3); s.push(4); s.push(5); 78 | 79 | print_stack("s",s); 80 | 81 | rs = reverse_stack(s); 82 | 83 | print_stack("reversed s",rs); 84 | 85 | q.push(1); q.push(2); q.push(3); q.push(4); q.push(5); 86 | 87 | print_queue("q",q); 88 | 89 | rq = reverse_queue(q); 90 | 91 | print_queue("reversed q",rq); 92 | 93 | return 0; 94 | } -------------------------------------------------------------------------------- /Course_2_Ordered Data Structures/Week_1_Linear data structures/Week1_Challenge_implementation.exe: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/brianchiang-tw/Accelerated_Computer_Science_Fundamentals_Specialization/ff5f477f10e514c46e417a8dab4d4e60100725d5/Course_2_Ordered Data Structures/Week_1_Linear data structures/Week1_Challenge_implementation.exe -------------------------------------------------------------------------------- /Course_2_Ordered Data Structures/Week_1_Linear data structures/Week1_Project_LinkedList_and_MergeSort/Makefile: -------------------------------------------------------------------------------- 1 | # Executable names: 2 | EXE = main 3 | TEST = test 4 | 5 | # Add all object files needed for compiling: 6 | EXE_OBJ = main.o 7 | OBJS = main.o 8 | 9 | # Generated files 10 | # (none) 11 | 12 | # Include the master templated makefile: 13 | include uiuc/make/uiuc.mk 14 | -------------------------------------------------------------------------------- /Course_2_Ordered Data Structures/Week_1_Linear data structures/Week1_Project_LinkedList_and_MergeSort/main.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * @file main.cpp 3 | * University of Illinois CS 400, MOOC 2, Week 1: Linked Lists 4 | * 5 | * @author Eric Huber 6 | **/ 7 | 8 | #include 9 | #include 10 | 11 | #include "LinkedList.h" 12 | #include "LinkedListExercises.h" 13 | 14 | // ----------------------------------------------------------------------- 15 | // Function prototypes: When global functions are defined later in the 16 | // compilation unit than they are called, then at least these function 17 | // prototype header lines must be written before the call. 18 | 19 | // Some informal unit tests. Defined at the bottom of main.cpp 20 | void informalTests(); 21 | // Helper function used by informalTests. Defined at the bottom of main.cpp 22 | void errorReaction(std::string msg); 23 | 24 | // ----------------------------------------------------------------------- 25 | 26 | // main program: You can do whatever you want to test your code here. 27 | // See also the test suite that you can build with "make test". 28 | int main() { 29 | informalTests(); 30 | return 0; 31 | } 32 | 33 | // ------------------------------------------------------------------------ 34 | 35 | // Choose what to do if an informal test has a big problem. 36 | void errorReaction(std::string msg) { 37 | // If you want to throw an exception and stop the program immediately: 38 | // throw std::runtime_error(msg); 39 | // If you want to display a warning and keep going: 40 | std::cout << std::endl << "WARNING: " << msg << std::endl << std::endl;; 41 | } 42 | 43 | // These tests aren't very exhaustive of the student exercise code. 44 | // They are more of a sanity check on the LinkedList class itself. 45 | void informalTests() { 46 | 47 | std::cout << "Running a few informal tests. Feel free to study these or edit them." << std::endl; 48 | std::cout << "The unit tests in the tests/ subdirectory are much more exhaustive!" << std::endl; 49 | std::cout << "You can run those by doing: make clean && make test && ./test" << std::endl; 50 | std::cout << "Remember that when you're ready to submit, you should do: make zip" << std::endl; 51 | std::cout << "That will package the zip file properly for submission." << std::endl; 52 | 53 | { 54 | std::cout << std::endl << "Testing splitHalves():" << std::endl; 55 | LinkedList l; 56 | l.pushBack(5); 57 | l.pushBack(6); 58 | l.pushBack(7); 59 | l.pushBack(8); 60 | l.pushBack(9); 61 | std::cout << "List: " << l << std::endl; 62 | std::cout << "Size: " << l.size() << std::endl; 63 | LinkedList> halves = l.splitHalves(); 64 | std::cout << "Front half: " << halves.front() 65 | << " Back half: " << halves.back() << std::endl; 66 | 67 | LinkedList expectedFrontHalf; 68 | expectedFrontHalf.pushBack(5); 69 | expectedFrontHalf.pushBack(6); 70 | expectedFrontHalf.pushBack(7); 71 | std::cout << "Expected front half: " << expectedFrontHalf << std::endl; 72 | if (expectedFrontHalf != halves.front()) errorReaction("front half is wrong"); 73 | LinkedList expectedBackHalf; 74 | expectedBackHalf.pushBack(8); 75 | expectedBackHalf.pushBack(9); 76 | std::cout << "Expected back half: " << expectedBackHalf << std::endl; 77 | if (expectedBackHalf != halves.back()) errorReaction("back half is wrong"); 78 | } 79 | 80 | { 81 | std::cout << std::endl << "Testing explode() and iterating with pointers:" << std::endl; 82 | LinkedList l; 83 | l.pushBack(5); 84 | l.pushBack(6); 85 | l.pushBack(7); 86 | l.pushBack(8); 87 | l.pushBack(9); 88 | std::cout << "Original list: " << l << std::endl; 89 | 90 | auto lists = l.explode(); 91 | std::cout << "Exploded list of lists:" << std::endl; 92 | std::cout << lists << std::endl; 93 | 94 | std::cout << "Iterating through lists using pointers:" << std::endl; 95 | auto nodePtr = lists.getHeadPtr(); 96 | while (nodePtr) { 97 | auto list = nodePtr->data; 98 | if (list.size() != 1) errorReaction("exploded list item should have size 1"); 99 | std::cout << "List: " << list << std::endl; 100 | // std::cout << "Size: " << list.size() << std::endl << std::endl; 101 | nodePtr = nodePtr->next; 102 | } 103 | 104 | // You can also avoid dealing with pointers entirely by using the 105 | // push and pop interface to cycle through the list contents. (This is somewhat 106 | // less efficient because it creates and destroys copies of the data throughout 107 | // the process of shuffling the list.) 108 | std::cout << "Fake iteration done by popping and pushing items:" << std::endl; 109 | for (int i=0; i expected; 122 | expected.pushBack(-1); 123 | expected.pushBack(4); 124 | expected.pushBack(5); 125 | expected.pushBack(6); 126 | expected.pushBack(7); 127 | expected.pushBack(8); 128 | expected.pushBack(9); 129 | expected.pushBack(10); 130 | 131 | LinkedList l; 132 | l.pushBack(5); 133 | l.pushBack(6); 134 | l.pushBack(8); 135 | l.pushBack(9); 136 | std::cout << "List: " << l << std::endl; 137 | l.insertOrdered(7); 138 | l.insertOrdered(4); 139 | l.insertOrdered(-1); 140 | l.insertOrdered(10); 141 | std::cout << "Inserting items now." << std::endl; 142 | std::cout << "List: " << l << std::endl; 143 | std::cout << "Expected: " << expected << std::endl; 144 | if (l != expected) errorReaction("wrong result"); 145 | 146 | std::cout << "Testing copy constructor:" << std::endl; 147 | LinkedList l2(l); 148 | std::cout << "Copy: " << l2 << std::endl; 149 | std::cout << "Expected: " << expected << std::endl; 150 | if (l2 != expected) errorReaction("wrong result"); 151 | 152 | std::cout << "Checking equivalency:" << std::boolalpha << (l == l2) << std::endl; 153 | } 154 | 155 | { 156 | std::cout << std::endl << "Testing insertionSort:" << std::endl; 157 | LinkedList l; 158 | l.pushBack(10); 159 | l.pushBack(4); 160 | l.pushBack(7); 161 | l.pushBack(5); 162 | l.pushBack(8); 163 | l.pushBack(6); 164 | l.pushBack(-1); 165 | l.pushBack(9); 166 | 167 | std::cout << "(Before) List: " << l << std::endl; 168 | auto l2 = l.insertionSort(); 169 | std::cout << "(After) List: " << l2 << std::endl; 170 | std::cout << "isSorted: " << std::boolalpha << l2.isSorted() << std::endl; 171 | 172 | LinkedList expected; 173 | expected.pushBack(-1); 174 | expected.pushBack(4); 175 | expected.pushBack(5); 176 | expected.pushBack(6); 177 | expected.pushBack(7); 178 | expected.pushBack(8); 179 | expected.pushBack(9); 180 | expected.pushBack(10); 181 | 182 | std::cout << "Expected: " << expected << std::endl; 183 | 184 | if (l2 != expected) errorReaction("Bug in insertionSort (check insertOrdered first)"); 185 | if (l2 == expected && !l2.isSorted()) errorReaction("Bug in isSorted"); 186 | } 187 | 188 | { 189 | std::cout << std::endl << "Testing merge():" << std::endl; 190 | LinkedList l; 191 | l.pushBack(1); 192 | l.pushBack(3); 193 | l.pushBack(5); 194 | LinkedList r; 195 | r.pushBack(-1); 196 | r.pushBack(2); 197 | r.pushBack(10); 198 | r.pushBack(20); 199 | 200 | LinkedList expected; 201 | expected.pushBack(-1); 202 | expected.pushBack(1); 203 | expected.pushBack(2); 204 | expected.pushBack(3); 205 | expected.pushBack(5); 206 | expected.pushBack(10); 207 | expected.pushBack(20); 208 | 209 | std::cout << "Left List: " << l << " "; 210 | std::cout << "Right List: " << r << std::endl; 211 | auto merged = l.merge(r); 212 | std::cout << "Merged: " << merged << std::endl; 213 | std::cout << "Expected: " << expected << std::endl; 214 | if (merged != expected) errorReaction("Bug in merge"); 215 | } 216 | 217 | { 218 | std::cout << std::endl << "Testing mergeSortRecursive:" << std::endl; 219 | LinkedList l; 220 | l.pushBack(10); 221 | l.pushBack(4); 222 | l.pushBack(7); 223 | l.pushBack(5); 224 | l.pushBack(8); 225 | l.pushBack(6); 226 | l.pushBack(-1); 227 | l.pushBack(9); 228 | 229 | LinkedList expected; 230 | expected.pushBack(-1); 231 | expected.pushBack(4); 232 | expected.pushBack(5); 233 | expected.pushBack(6); 234 | expected.pushBack(7); 235 | expected.pushBack(8); 236 | expected.pushBack(9); 237 | expected.pushBack(10); 238 | 239 | std::cout << "(Before) List: " << l << std::endl; 240 | l = l.mergeSortRecursive(); 241 | std::cout << "(After) List: " << l << std::endl; 242 | std::cout << "isSorted: " << std::boolalpha << l.isSorted() << std::endl; 243 | std::cout << "Expected: " << expected << std::endl; 244 | if (l != expected) errorReaction("Bug in mergeSortRecursive (check merge first)"); 245 | } 246 | 247 | { 248 | std::cout << std::endl << "Testing mergeSortIterative:" << std::endl; 249 | LinkedList l; 250 | l.pushBack(10); 251 | l.pushBack(4); 252 | l.pushBack(-1); 253 | l.pushBack(5); 254 | l.pushBack(8); 255 | l.pushBack(6); 256 | l.pushBack(7); 257 | l.pushBack(9); 258 | 259 | LinkedList expected; 260 | expected.pushBack(-1); 261 | expected.pushBack(4); 262 | expected.pushBack(5); 263 | expected.pushBack(6); 264 | expected.pushBack(7); 265 | expected.pushBack(8); 266 | expected.pushBack(9); 267 | expected.pushBack(10); 268 | 269 | std::cout << "(Before) List: " << l << std::endl; 270 | l = l.mergeSortIterative(); 271 | std::cout << "(After) List: " << l << std::endl; 272 | std::cout << "isSorted: " << std::boolalpha << l.isSorted() << std::endl; 273 | std::cout << "Expected: " << expected << std::endl; 274 | if (l != expected) errorReaction("Bug in mergeSortIterative (check merge first)"); 275 | } 276 | 277 | std::cout << "\n\nInformal tests finished without crashing, but the output may have been incorrect." 278 | << "\nPlease scroll to the top of the output to read the diagnostics." << std::endl; 279 | 280 | } 281 | 282 | -------------------------------------------------------------------------------- /Course_2_Ordered Data Structures/Week_1_Linear data structures/Week1_Project_LinkedList_and_MergeSort/uiuc/catch/catchmain.cpp: -------------------------------------------------------------------------------- 1 | #define CATCH_CONFIG_MAIN 2 | #include "catch.hpp" 3 | -------------------------------------------------------------------------------- /Course_2_Ordered Data Structures/Week_1_Linear data structures/Week1_Project_LinkedList_and_MergeSort/uiuc/make/uiuc.mk: -------------------------------------------------------------------------------- 1 | 2 | # University of Illinois 3 | # CS 400 - MOOC 2 - Week 1 4 | 5 | # Original Makefile created by Wade Fagen-Ulmschneider 6 | # A few tweaks for CS 400 by Eric Huber 7 | 8 | ZIP_FILE = LinkedList_submission.zip 9 | COLLECTED_FILES = LinkedListExercises.h 10 | 11 | # Add standard object files (HSLAPixel, PNG, and LodePNG) 12 | OBJS += 13 | 14 | # Use ./.objs to store all .o file (keeping the directory clean) 15 | OBJS_DIR = .objs 16 | 17 | # Use all .cpp files in /tests/ 18 | OBJS_TEST = $(filter-out $(EXE_OBJ), $(OBJS)) 19 | CPP_TEST = $(wildcard tests/*.cpp) 20 | CPP_TEST += uiuc/catch/catchmain.cpp 21 | OBJS_TEST += $(CPP_TEST:.cpp=.o) 22 | 23 | # Config 24 | CXX_CLANG = clang++ 25 | CXX_GCC = g++ 26 | CXX_WHICH = $(CXX_GCC) 27 | CXX = $(CXX_WHICH) 28 | LD = $(CXX_WHICH) 29 | # STDVERSION = -std=c++1y # deprecated nomenclature 30 | STDVERSION = -std=c++14 # proper but requires newer compiler versions (for better or worse) 31 | STDLIBVERSION_CLANG = -stdlib=libc++ # Clang's version; not present on default AWS Cloud9 instance 32 | STDLIBVERSION_GCC = # blank on purpose; default GNU library 33 | ifeq ($(CXX_WHICH),$(CXX_CLANG)) 34 | STDLIBVERSION = $(STDLIBVERSION_CLANG) 35 | else 36 | STDLIBVERSION = $(STDLIBVERSION_GCC) 37 | endif 38 | WARNINGS = -pedantic -Wall -Wfatal-errors -Wextra -Wno-unused-parameter -Wno-unused-variable 39 | # ASANFLAGS = -fsanitize=address -fno-omit-frame-pointer 40 | # NO_COPY_ELISION = -fno-elide-constructors 41 | CXXFLAGS = $(CS400) $(STDVERSION) $(STDLIBVERSION) -g -O0 $(WARNINGS) -MMD -MP -msse2 -c $(ASANFLAGS) $(NO_COPY_ELISION) 42 | LDFLAGS = $(CS400) $(STDVERSION) $(STDLIBVERSION) -lpthread $(ASANFLAGS) $(NO_COPY_ELISION) 43 | 44 | ifneq ($(strip $(ASANFLAGS)),) 45 | # This is displayed if ASANFLAGS is not blank. 46 | ASANWARNING = "\n >>>>>>>>>> Note: ASAN is in use. May not be supported on Cloud9. <<<<<<<<<<" 47 | endif 48 | 49 | # Rules for first executable 50 | $(EXE): 51 | $(LD) $^ $(LDFLAGS) -o $@ 52 | @echo 53 | @echo " Built the main executable program file for the project: " $(EXE) 54 | @echo " (Make sure you try \"make test\" too!)" 55 | @echo $(ASANWARNING) 56 | 57 | # Rule for `all` 58 | all: $(EXE) $(TEST) 59 | 60 | # Pattern rules for object files 61 | $(OBJS_DIR): 62 | @mkdir -p $(OBJS_DIR) 63 | @mkdir -p $(OBJS_DIR)/uiuc 64 | @mkdir -p $(OBJS_DIR)/uiuc/catch 65 | @mkdir -p $(OBJS_DIR)/tests 66 | 67 | $(OBJS_DIR)/%.o: %.cpp | $(OBJS_DIR) 68 | $(CXX) $(CXXFLAGS) $< -o $@ 69 | 70 | # Rules for executables 71 | $(TEST): 72 | $(LD) $^ $(LDFLAGS) -o $@ 73 | @echo 74 | @echo " Built the test suite program: " $(TEST) 75 | @echo $(ASANWARNING) 76 | 77 | # Executable dependencies 78 | $(EXE): $(patsubst %.o, $(OBJS_DIR)/%.o, $(OBJS)) 79 | $(TEST): $(patsubst %.o, $(OBJS_DIR)/%.o, $(OBJS_TEST)) 80 | 81 | # Include automatically generated dependencies 82 | -include $(OBJS_DIR)/*.d 83 | -include $(OBJS_DIR)/uiuc/*.d 84 | -include $(OBJS_DIR)/uiuc/catch/*.d 85 | -include $(OBJS_DIR)/tests/*.d 86 | 87 | clean: 88 | rm -rf $(EXE) $(TEST) $(OBJS_DIR) $(CLEAN_RM) 89 | 90 | tidy: clean 91 | rm -rf doc 92 | 93 | zip: 94 | @echo "!!! Preparing submission zip with student code..." 95 | @echo "!!! Make sure you have already tried compiling and testing your code" 96 | @echo "!!! thoroughly before submitting the zip on Coursera!" 97 | @echo "" 98 | @echo "Removing any previous version of zip file..." 99 | rm -rf $(ZIP_FILE) 100 | @echo "Creating new file..." 101 | zip $(ZIP_FILE) $(COLLECTED_FILES) 102 | @echo "Created zip file: " $(ZIP_FILE) 103 | 104 | .PHONY: all tidy clean zip 105 | -------------------------------------------------------------------------------- /Course_2_Ordered Data Structures/Week_1_Linear data structures/Week1_Project_LinkedList_and_MergeSort/version.txt: -------------------------------------------------------------------------------- 1 | 20191015a 2 | 3 | -------------------------------------------------------------------------------- /Course_2_Ordered Data Structures/Week_1_Linear data structures/Week1_Project_LinkedList_and_MergeSort_Description.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/brianchiang-tw/Accelerated_Computer_Science_Fundamentals_Specialization/ff5f477f10e514c46e417a8dab4d4e60100725d5/Course_2_Ordered Data Structures/Week_1_Linear data structures/Week1_Project_LinkedList_and_MergeSort_Description.pdf -------------------------------------------------------------------------------- /Course_2_Ordered Data Structures/Week_1_Linear data structures/Week1_Project_LinkedList_and_MergeSort_full implementation.zip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/brianchiang-tw/Accelerated_Computer_Science_Fundamentals_Specialization/ff5f477f10e514c46e417a8dab4d4e60100725d5/Course_2_Ordered Data Structures/Week_1_Linear data structures/Week1_Project_LinkedList_and_MergeSort_full implementation.zip -------------------------------------------------------------------------------- /Course_2_Ordered Data Structures/Week_1_Linear data structures/Week1_Project_LinkedList_and_MergeSort_starter_files_20191015a.zip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/brianchiang-tw/Accelerated_Computer_Science_Fundamentals_Specialization/ff5f477f10e514c46e417a8dab4d4e60100725d5/Course_2_Ordered Data Structures/Week_1_Linear data structures/Week1_Project_LinkedList_and_MergeSort_starter_files_20191015a.zip -------------------------------------------------------------------------------- /Course_2_Ordered Data Structures/Week_1_Linear data structures/Week1_Project_LinkedList_and_MergeSort_submission.zip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/brianchiang-tw/Accelerated_Computer_Science_Fundamentals_Specialization/ff5f477f10e514c46e417a8dab4d4e60100725d5/Course_2_Ordered Data Structures/Week_1_Linear data structures/Week1_Project_LinkedList_and_MergeSort_submission.zip -------------------------------------------------------------------------------- /Course_2_Ordered Data Structures/Week_1_Linear data structures/Week_1_Challenge_and_Reference Solution.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/brianchiang-tw/Accelerated_Computer_Science_Fundamentals_Specialization/ff5f477f10e514c46e417a8dab4d4e60100725d5/Course_2_Ordered Data Structures/Week_1_Linear data structures/Week_1_Challenge_and_Reference Solution.pdf -------------------------------------------------------------------------------- /Course_2_Ordered Data Structures/Week_1_Linear data structures/Week_1_Orientation Quiz_and_Reference Manual.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/brianchiang-tw/Accelerated_Computer_Science_Fundamentals_Specialization/ff5f477f10e514c46e417a8dab4d4e60100725d5/Course_2_Ordered Data Structures/Week_1_Linear data structures/Week_1_Orientation Quiz_and_Reference Manual.pdf -------------------------------------------------------------------------------- /Course_2_Ordered Data Structures/Week_1_Linear data structures/Week_1_Quiz_and_Reference Manual.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/brianchiang-tw/Accelerated_Computer_Science_Fundamentals_Specialization/ff5f477f10e514c46e417a8dab4d4e60100725d5/Course_2_Ordered Data Structures/Week_1_Linear data structures/Week_1_Quiz_and_Reference Manual.pdf -------------------------------------------------------------------------------- /Course_2_Ordered Data Structures/Week_2_Introduction to Tree structures/Week2_Challenge_implementation.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | 5 | // You may assume that the following Node class has already 6 | // been defined for you previously: 7 | 8 | class Node { 9 | public: 10 | Node *left, *right; 11 | Node() { left = right = nullptr; } 12 | ~Node() { 13 | delete left; 14 | left = nullptr; 15 | delete right; 16 | right = nullptr; 17 | } 18 | }; 19 | 20 | // You may also assume that iostream has already been included. 21 | 22 | // Implement the function "int count(Node *n)" below to return 23 | // an integer representing the number of nodes in the subtree 24 | // of Node n (including Node n itself). 25 | 26 | 27 | int count(Node *n) { 28 | 29 | // Implement count() here. 30 | 31 | if( nullptr == n ) 32 | { 33 | // if visit empty subtree, return 0 34 | return 0; 35 | } 36 | else 37 | { 38 | // node count of node n 39 | // = node count of left sub tree + node count of right sub tree + 1 (self) 40 | return count(n->left) + count( n->right ) + 1; 41 | } 42 | 43 | } 44 | //end of function count(Node *n) 45 | 46 | 47 | 48 | // expected output of main 49 | /* 50 | 6 51 | */ 52 | 53 | int main() { 54 | Node *n = new Node(); 55 | n->left = new Node(); 56 | n->right = new Node(); 57 | n->right->left = new Node(); 58 | n->right->right = new Node(); 59 | n->right->right->right = new Node(); 60 | 61 | // This should print a count of six nodes 62 | std::cout << count(n) << std::endl; 63 | 64 | // Deleting n is sufficient to delete the entire tree 65 | // because this will trigger the recursively-defined 66 | // destructor of the Node class. 67 | delete n; 68 | n = nullptr; 69 | 70 | return 0; 71 | } -------------------------------------------------------------------------------- /Course_2_Ordered Data Structures/Week_2_Introduction to Tree structures/Week2_Challenge_implementation.exe: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/brianchiang-tw/Accelerated_Computer_Science_Fundamentals_Specialization/ff5f477f10e514c46e417a8dab4d4e60100725d5/Course_2_Ordered Data Structures/Week_2_Introduction to Tree structures/Week2_Challenge_implementation.exe -------------------------------------------------------------------------------- /Course_2_Ordered Data Structures/Week_2_Introduction to Tree structures/Week_2_Challenge_and_Reference Solution.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/brianchiang-tw/Accelerated_Computer_Science_Fundamentals_Specialization/ff5f477f10e514c46e417a8dab4d4e60100725d5/Course_2_Ordered Data Structures/Week_2_Introduction to Tree structures/Week_2_Challenge_and_Reference Solution.pdf -------------------------------------------------------------------------------- /Course_2_Ordered Data Structures/Week_2_Introduction to Tree structures/Week_2_Quiz_and_Reference Manual.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/brianchiang-tw/Accelerated_Computer_Science_Fundamentals_Specialization/ff5f477f10e514c46e417a8dab4d4e60100725d5/Course_2_Ordered Data Structures/Week_2_Introduction to Tree structures/Week_2_Quiz_and_Reference Manual.pdf -------------------------------------------------------------------------------- /Course_2_Ordered Data Structures/Week_3_Advanced Tree Structures/Week3_Challenge_implementation.cpp: -------------------------------------------------------------------------------- 1 | 2 | // The height of a node is the number of edges in 3 | // its longest chain of descendants. 4 | 5 | // Implement computeHeight to compute the height 6 | // of the subtree rooted at the node n. Note that 7 | // this function does not return a value. You should 8 | // store the calculated height in that node's own 9 | // height member variable. Your function should also 10 | // do the same for EVERY node in the subtree rooted 11 | // at the current node. (This naturally lends itself 12 | // to a recursive solution!) 13 | 14 | // Assume that the following includes have already been 15 | // provided. You should not need any other includes 16 | // than these. 17 | 18 | #include 19 | #include 20 | #include 21 | #include 22 | using namespace std; 23 | 24 | // You have also the following class Node already defined. 25 | // You cannot change this class definition, so it is 26 | // shown here in a comment for your reference only: 27 | 28 | class Node { 29 | public: 30 | int height; // to be set by computeHeight() 31 | Node *left, *right; 32 | Node() { height = -1; left = right = nullptr; } 33 | ~Node() { 34 | delete left; 35 | left = nullptr; 36 | delete right; 37 | right = nullptr; 38 | } 39 | }; 40 | 41 | 42 | void computeHeight(Node *n) { 43 | if( nullptr == n ) 44 | { 45 | //std::cout << "null, empty" << std::endl; 46 | 47 | return; 48 | } 49 | else 50 | { 51 | 52 | //std::cout << "calcing left sub tree" << std::endl; 53 | 54 | Node *leftNode = n->left; 55 | computeHeight( leftNode ); 56 | 57 | //std::cout << "calcing right sub tree" << std::endl; 58 | 59 | Node *rightNode = n->right; 60 | computeHeight( rightNode ); 61 | 62 | 63 | 64 | if( nullptr == leftNode && nullptr == rightNode ) 65 | { 66 | // current node is leave node, height = 0 67 | n->height = 0; 68 | } 69 | else if( nullptr == leftNode && nullptr != rightNode ) 70 | { 71 | //current node adds right node's height 72 | n->height = 1 + rightNode->height; 73 | } 74 | else if( nullptr == rightNode && nullptr != leftNode ) 75 | { 76 | //current node adds left node's height 77 | n->height = 1 + leftNode->height; 78 | } 79 | else 80 | { 81 | //current node has two sub-tree 82 | //adds the one with longer height 83 | 84 | if( leftNode->height >= rightNode->height ) 85 | { 86 | n->height = 1 + leftNode->height; 87 | } 88 | else 89 | { 90 | n->height = 1 + rightNode->height; 91 | } 92 | } 93 | 94 | 95 | return; 96 | } 97 | //end of if( nullptr == n ) ... else ... 98 | 99 | } 100 | //end of function computeHeight 101 | 102 | // This function prints the tree in a nested linear format. 103 | void printTree(const Node *n) { 104 | if (!n) return; 105 | std::cout << n->height << "("; 106 | printTree(n->left); 107 | std::cout << ")("; 108 | printTree(n->right); 109 | std::cout << ")"; 110 | } 111 | 112 | // The printTreeVertical function gives you a verbose, 113 | // vertical printout of the tree, where the leftmost nodes 114 | // are displayed highest. This function has already been 115 | // defined in some hidden code. 116 | // It has this function prototype: void printTreeVertical(const Node* n); 117 | 118 | // This main() function is for your personal testing with 119 | // the Run button. When you're ready, click Submit to have 120 | // your work tested and graded. 121 | 122 | 123 | // expected output of main: 124 | /* 125 | 3(0()())(2(0()())(1()(0()()))) 126 | */ 127 | int main() { 128 | Node *n = new Node(); 129 | n->left = new Node(); 130 | n->right = new Node(); 131 | n->right->left = new Node(); 132 | n->right->right = new Node(); 133 | n->right->right->right = new Node(); 134 | 135 | computeHeight(n); 136 | 137 | printTree(n); 138 | std::cout << std::endl << std::endl; 139 | //printTreeVertical(n); 140 | 141 | // The Node destructor will recursively 142 | // delete its children nodes. 143 | delete n; 144 | n = nullptr; 145 | 146 | return 0; 147 | } 148 | -------------------------------------------------------------------------------- /Course_2_Ordered Data Structures/Week_3_Advanced Tree Structures/Week3_Challenge_implementation.exe: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/brianchiang-tw/Accelerated_Computer_Science_Fundamentals_Specialization/ff5f477f10e514c46e417a8dab4d4e60100725d5/Course_2_Ordered Data Structures/Week_3_Advanced Tree Structures/Week3_Challenge_implementation.exe -------------------------------------------------------------------------------- /Course_2_Ordered Data Structures/Week_3_Advanced Tree Structures/Week3_Project_GenericTree/GenericTree/Makefile: -------------------------------------------------------------------------------- 1 | # Executable names: 2 | EXE = main 3 | TEST = test 4 | 5 | # Add all object files needed for compiling: 6 | EXE_OBJ = main.o 7 | OBJS = main.o 8 | 9 | # Generated files 10 | # (none) 11 | 12 | # Include the master templated makefile: 13 | include uiuc/make/uiuc.mk 14 | -------------------------------------------------------------------------------- /Course_2_Ordered Data Structures/Week_3_Advanced Tree Structures/Week3_Project_GenericTree/GenericTree/main.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * @file main.cpp 3 | * University of Illinois CS 400, MOOC 2, Week 3: Generic Tree 4 | * 5 | * @author Eric Huber 6 | **/ 7 | 8 | #include 9 | #include 10 | 11 | #include "GenericTree.h" 12 | #include "GenericTreeExercises.h" 13 | 14 | // The exampleTree functions show some examples of how the GenericTree class 15 | // can be used to generate and display a tree. 16 | // Although these functions are defined in this file, listing the function 17 | // prototypes up here before we refer to them in main() allows us to move 18 | // the function bodies to the bottom of the file for clarity. 19 | void exampleTree1(); 20 | void exampleTree2(); 21 | 22 | // Main function: Shows some example output of the provided functions 23 | // and runs a few tests on the ones you implement in the exercises. 24 | int main() { 25 | 26 | exampleTree1(); 27 | 28 | exampleTree2(); 29 | 30 | treeFactoryTest(); 31 | 32 | traversalTest(); 33 | 34 | return 0; 35 | } 36 | 37 | void exampleTree1() { 38 | 39 | std::cout << std::endl; 40 | std::cout << "------------------------------" << std::endl; 41 | std::cout << "EXAMPLE TREE 1" << std::endl << std::endl; 42 | 43 | // Create a new tree with the root node containing "A". 44 | GenericTree tree("A"); 45 | 46 | // Get a pointer to the root node. Automatically detect the 47 | // type as a pointer to a node. 48 | auto nodeA = tree.getRootPtr(); 49 | 50 | // We could write out the entire templated type we expect to be returned, 51 | // but templated types and inner class types can have very long type 52 | // names, like this: 53 | // GenericTree::GenericTreeNode* nodeA = tree.getRootPtr(); 54 | // It's much easier to use "auto" in these situations, which will 55 | // automatically detect the type returned. 56 | 57 | // Remember that nodeA here is a pointer to a node. Also, addChild returns 58 | // a pointer to a node. The child nodes created have their pointers stored 59 | // in the tree itself, but we save copies of the pointers as variables here 60 | // when we need to refer to them again. For example, this is useful to 61 | // specify several children branching from the same parent. 62 | auto nodeB = nodeA->addChild("B"); 63 | nodeB->addChild("C"); 64 | nodeB->addChild("D"); 65 | auto nodeE = nodeA->addChild("E"); 66 | nodeE->addChild("F"); 67 | nodeE->addChild("G"); 68 | 69 | std::cout << "Here's a small example tree. (The leftmost branches are displayed\n" 70 | << " highest in the vertical display format for the terminal.)" << std::endl; 71 | std::cout << tree << std::endl; 72 | 73 | std::cout << "Debug display of the depth information per node:" << std::endl; 74 | tree.showDebugMessages = true; 75 | std::cout << tree << std::endl; 76 | 77 | std::cout << "Now, when the tree goes out of scope and is destroyed, you can see the order\n" 78 | << " in which the nodes are explored and destroyed for cleanup:" << std::endl; 79 | 80 | return; 81 | } 82 | 83 | void exampleTree2() { 84 | 85 | std::cout << std::endl; 86 | std::cout << "------------------------------" << std::endl; 87 | std::cout << "EXAMPLE TREE 2" << std::endl << std::endl; 88 | std::cout << "Here's a larger tree:" << std::endl << std::endl; 89 | 90 | GenericTree tree("X"); 91 | 92 | // It's possible to clear the entire tree. 93 | // As a demonstration, let's try clearing the tree and creating a 94 | // new root with "A" instead. 95 | tree.clear(); 96 | tree.createRoot("A"); 97 | 98 | auto A = tree.getRootPtr(); 99 | // Since addChild returns a pointer to a node, it's possible for us 100 | // to chain together function calls like this in succession: 101 | A->addChild("B")->addChild("C"); 102 | auto D = A->addChild("D"); 103 | auto E = D->addChild("E"); 104 | E->addChild("F"); 105 | E->addChild("G")->addChild("H"); 106 | D->addChild("I"); 107 | A->addChild("J"); 108 | auto L = A->addChild("K")->addChild("L"); 109 | L->addChild("M"); 110 | 111 | std::cout << tree << std::endl; 112 | 113 | std::cout << "Let's delete the subtrees rooted at D and at L:" << std::endl << std::endl; 114 | 115 | // After deleting the D subtree, the existing D and E pointers 116 | // won't be safe to dereference anymore. Reset them to nullptr. 117 | tree.deleteSubtree(D); 118 | D = E = nullptr; 119 | 120 | // Deleting the L subtree removes nodes L and M. 121 | // We saved a pointer to L so we need to set it to null for safety. 122 | tree.deleteSubtree(L); 123 | L = nullptr; 124 | 125 | std::cout << tree << std::endl; 126 | 127 | std::cout << "Let's try some helper functions to count how many null children are left" << std::endl 128 | << " over in the tree:" << std::endl << std::endl; 129 | 130 | int nullChildrenCount = countNullChildrenRecursive(tree.getRootPtr()); 131 | std::cout << "Null children counted recursively: " << nullChildrenCount << std::endl; 132 | 133 | nullChildrenCount = countNullChildrenIterative(tree.getRootPtr()); 134 | std::cout << "Null children counted iteratively: " << nullChildrenCount << std::endl; 135 | 136 | std::cout << std::endl; 137 | std::cout << "Now let's compress the tree to remove the null children pointers:" 138 | << std::endl << std::endl; 139 | 140 | tree.compress(); 141 | std::cout << "After compressing:" << std::endl; 142 | std::cout << tree << std::endl; 143 | nullChildrenCount = countNullChildrenIterative(tree.getRootPtr()); 144 | std::cout << "Null children remaining: " << nullChildrenCount << std::endl; 145 | 146 | return; 147 | } 148 | 149 | -------------------------------------------------------------------------------- /Course_2_Ordered Data Structures/Week_3_Advanced Tree Structures/Week3_Project_GenericTree/GenericTree/tests/week3_tests.cpp: -------------------------------------------------------------------------------- 1 | 2 | // University of Illinois CS 400, MOOC 2, Week 3: Generic Tree 3 | // Author: Eric Huber, University of Illinois staff 4 | // Autograder based on Zephyr test runner by Prof. Wade Fagen-Ulmschneider and the CS 225 Course Staff 5 | // Based on Catch2 unit testing framework 6 | 7 | #include 8 | #include 9 | 10 | #include "../uiuc/catch/catch.hpp" 11 | 12 | #include "../GenericTree.h" 13 | #include "../GenericTreeExercises.h" 14 | 15 | 16 | TEST_CASE("Displaying manual test output", "[weight=0]") { 17 | treeFactoryTest(); 18 | traversalTest(); 19 | } 20 | 21 | TEST_CASE("Testing treeFactory preliminaries", "[weight=1]") { 22 | GenericTree tree(9999); 23 | treeFactory(tree); 24 | auto root = tree.getRootPtr(); 25 | SECTION("Root should not be null") { 26 | REQUIRE(nullptr != root); 27 | } 28 | SECTION("Root data should remove the previous setting") { 29 | REQUIRE(root); 30 | REQUIRE(9999 != root->data); 31 | } 32 | SECTION("Root data should be 4") { 33 | REQUIRE(root); 34 | REQUIRE(4 == root->data); 35 | } 36 | SECTION("Deepest data should be 42") { 37 | REQUIRE(root); 38 | REQUIRE(root->childrenPtrs.at(0)); 39 | REQUIRE(root->childrenPtrs.at(0)->childrenPtrs.at(0)); 40 | REQUIRE(root->childrenPtrs.at(0)->childrenPtrs.at(0)->childrenPtrs.at(0)); 41 | REQUIRE(42 == root->childrenPtrs.at(0)->childrenPtrs.at(0)->childrenPtrs.at(0)->data); 42 | } 43 | } 44 | 45 | TEST_CASE("Testing treeFactory further", "[weight=1]") { 46 | 47 | std::string exemplarTreeStr = "4\n"; 48 | exemplarTreeStr += "|\n"; 49 | exemplarTreeStr += "|_ 8\n"; 50 | exemplarTreeStr += "| |\n"; 51 | exemplarTreeStr += "| |_ 16\n"; 52 | exemplarTreeStr += "| | |\n"; 53 | exemplarTreeStr += "| | |_ 42\n"; 54 | exemplarTreeStr += "| |\n"; 55 | exemplarTreeStr += "| |_ 23\n"; 56 | exemplarTreeStr += "|\n"; 57 | exemplarTreeStr += "|_ 15\n"; 58 | GenericTree tree(9999); 59 | treeFactory(tree); 60 | std::stringstream output; 61 | output << tree; 62 | SECTION("Trees should match") { 63 | REQUIRE(output.str() == exemplarTreeStr); 64 | } 65 | } 66 | 67 | TEST_CASE("Testing traverseLevels", "[weight=2]"){ 68 | // This is the tree from exampleTree2() in main.cpp 69 | // std::cout << "[Test 2] Expected output:" << std::endl 70 | // << "A B D J K C E I L F G M H" << std::endl; 71 | std::string expected_traversal = "A B D J K C E I L F G M H "; 72 | GenericTree tree2("A"); 73 | auto A = tree2.getRootPtr(); 74 | A->addChild("B")->addChild("C"); 75 | auto D = A->addChild("D"); 76 | auto E = D->addChild("E"); 77 | E->addChild("F"); 78 | E->addChild("G")->addChild("H"); 79 | D->addChild("I"); 80 | A->addChild("J"); 81 | auto L = A->addChild("K")->addChild("L"); 82 | L->addChild("M"); 83 | std::vector tree2_results = traverseLevels(tree2); 84 | // std::cout << "Your traverseLevels output:" << std::endl; 85 | std::stringstream outstream; 86 | for (auto result : tree2_results) { 87 | outstream << result << " "; 88 | } 89 | auto student_traversal = outstream.str(); 90 | SECTION("Should do correct traversal on tree from exampleTree2()") { 91 | REQUIRE(expected_traversal == student_traversal); 92 | } 93 | } 94 | 95 | -------------------------------------------------------------------------------- /Course_2_Ordered Data Structures/Week_3_Advanced Tree Structures/Week3_Project_GenericTree/GenericTree/uiuc/catch/catchmain.cpp: -------------------------------------------------------------------------------- 1 | #define CATCH_CONFIG_MAIN 2 | #include "catch.hpp" 3 | -------------------------------------------------------------------------------- /Course_2_Ordered Data Structures/Week_3_Advanced Tree Structures/Week3_Project_GenericTree/GenericTree/uiuc/make/uiuc.mk: -------------------------------------------------------------------------------- 1 | 2 | # University of Illinois 3 | # CS 400 - MOOC 2 - Week 3 4 | 5 | # Original Makefile created by Wade Fagen-Ulmschneider 6 | # A few tweaks for CS 400 by Eric Huber 7 | 8 | ZIP_FILE = GenericTree_submission.zip 9 | COLLECTED_FILES = GenericTreeExercises.h 10 | 11 | # Add standard object files (HSLAPixel, PNG, and LodePNG) 12 | OBJS += 13 | 14 | # Use ./.objs to store all .o file (keeping the directory clean) 15 | OBJS_DIR = .objs 16 | 17 | # Use all .cpp files in /tests/ 18 | OBJS_TEST = $(filter-out $(EXE_OBJ), $(OBJS)) 19 | CPP_TEST = $(wildcard tests/*.cpp) 20 | CPP_TEST += uiuc/catch/catchmain.cpp 21 | OBJS_TEST += $(CPP_TEST:.cpp=.o) 22 | 23 | # Config 24 | CXX_CLANG = clang++ 25 | CXX_GCC = g++ 26 | CXX_WHICH = $(CXX_GCC) 27 | CXX = $(CXX_WHICH) 28 | LD = $(CXX_WHICH) 29 | # STDVERSION = -std=c++1y # deprecated nomenclature 30 | STDVERSION = -std=c++14 # proper but requires newer compiler versions (for better or worse) 31 | STDLIBVERSION_CLANG = -stdlib=libc++ # Clang's version; not present on default AWS Cloud9 instance 32 | STDLIBVERSION_GCC = # blank on purpose; default GNU library 33 | ifeq ($(CXX_WHICH),$(CXX_CLANG)) 34 | STDLIBVERSION = $(STDLIBVERSION_CLANG) 35 | else 36 | STDLIBVERSION = $(STDLIBVERSION_GCC) 37 | endif 38 | WARNINGS = -pedantic -Wall -Wfatal-errors -Wextra -Wno-unused-parameter -Wno-unused-variable 39 | # ASANFLAGS = -fsanitize=address -fno-omit-frame-pointer 40 | CXXFLAGS = $(CS400) $(STDVERSION) $(STDLIBVERSION) -g -O0 $(WARNINGS) -MMD -MP -msse2 -c $(ASANFLAGS) 41 | LDFLAGS = $(CS400) $(STDVERSION) $(STDLIBVERSION) -lpthread $(ASANFLAGS) 42 | 43 | ifneq ($(strip $(ASANFLAGS)),) 44 | ASANWARNING = "\n *** ASAN is in use ***" 45 | endif 46 | 47 | # Rules for first executable 48 | $(EXE): 49 | $(LD) $^ $(LDFLAGS) -o $@ 50 | @echo 51 | @echo " Built the main executable program file for the project: " $(EXE) 52 | @echo " (Make sure you try \"make test\" too!)" 53 | @echo $(ASANWARNING) 54 | 55 | # Rule for `all` 56 | all: $(EXE) $(TEST) 57 | 58 | # Pattern rules for object files 59 | $(OBJS_DIR): 60 | @mkdir -p $(OBJS_DIR) 61 | @mkdir -p $(OBJS_DIR)/uiuc 62 | @mkdir -p $(OBJS_DIR)/uiuc/catch 63 | @mkdir -p $(OBJS_DIR)/tests 64 | 65 | $(OBJS_DIR)/%.o: %.cpp | $(OBJS_DIR) 66 | $(CXX) $(CXXFLAGS) $< -o $@ 67 | 68 | # Rules for executables 69 | $(TEST): 70 | $(LD) $^ $(LDFLAGS) -o $@ 71 | @echo 72 | @echo " Built the test suite program: " $(TEST) 73 | @echo $(ASANWARNING) 74 | 75 | # Executable dependencies 76 | $(EXE): $(patsubst %.o, $(OBJS_DIR)/%.o, $(OBJS)) 77 | $(TEST): $(patsubst %.o, $(OBJS_DIR)/%.o, $(OBJS_TEST)) 78 | 79 | # Include automatically generated dependencies 80 | -include $(OBJS_DIR)/*.d 81 | -include $(OBJS_DIR)/uiuc/*.d 82 | -include $(OBJS_DIR)/uiuc/catch/*.d 83 | -include $(OBJS_DIR)/tests/*.d 84 | 85 | clean: 86 | rm -rf $(EXE) $(TEST) $(OBJS_DIR) $(CLEAN_RM) 87 | 88 | tidy: clean 89 | rm -rf doc 90 | 91 | zip: 92 | @echo "!!! Preparing submission zip with student code..." 93 | @echo "!!! Make sure you have already tried compiling and testing your code" 94 | @echo "!!! thoroughly before submitting the zip on Coursera!" 95 | @echo "" 96 | @echo "Removing any previous version of zip file..." 97 | rm -rf $(ZIP_FILE) 98 | @echo "Creating new file..." 99 | zip $(ZIP_FILE) $(COLLECTED_FILES) 100 | @echo "Created zip file: " $(ZIP_FILE) 101 | 102 | .PHONY: all tidy clean zip 103 | -------------------------------------------------------------------------------- /Course_2_Ordered Data Structures/Week_3_Advanced Tree Structures/Week3_Project_GenericTree_Description.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/brianchiang-tw/Accelerated_Computer_Science_Fundamentals_Specialization/ff5f477f10e514c46e417a8dab4d4e60100725d5/Course_2_Ordered Data Structures/Week_3_Advanced Tree Structures/Week3_Project_GenericTree_Description.pdf -------------------------------------------------------------------------------- /Course_2_Ordered Data Structures/Week_3_Advanced Tree Structures/Week3_Project_GenericTree_full implementation.zip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/brianchiang-tw/Accelerated_Computer_Science_Fundamentals_Specialization/ff5f477f10e514c46e417a8dab4d4e60100725d5/Course_2_Ordered Data Structures/Week_3_Advanced Tree Structures/Week3_Project_GenericTree_full implementation.zip -------------------------------------------------------------------------------- /Course_2_Ordered Data Structures/Week_3_Advanced Tree Structures/Week3_Project_GenericTree_starter_files_20191015a.zip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/brianchiang-tw/Accelerated_Computer_Science_Fundamentals_Specialization/ff5f477f10e514c46e417a8dab4d4e60100725d5/Course_2_Ordered Data Structures/Week_3_Advanced Tree Structures/Week3_Project_GenericTree_starter_files_20191015a.zip -------------------------------------------------------------------------------- /Course_2_Ordered Data Structures/Week_3_Advanced Tree Structures/Week3_Project_GenericTree_submission.zip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/brianchiang-tw/Accelerated_Computer_Science_Fundamentals_Specialization/ff5f477f10e514c46e417a8dab4d4e60100725d5/Course_2_Ordered Data Structures/Week_3_Advanced Tree Structures/Week3_Project_GenericTree_submission.zip -------------------------------------------------------------------------------- /Course_2_Ordered Data Structures/Week_3_Advanced Tree Structures/Week_3_Challenge_and_Reference Solution.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/brianchiang-tw/Accelerated_Computer_Science_Fundamentals_Specialization/ff5f477f10e514c46e417a8dab4d4e60100725d5/Course_2_Ordered Data Structures/Week_3_Advanced Tree Structures/Week_3_Challenge_and_Reference Solution.pdf -------------------------------------------------------------------------------- /Course_2_Ordered Data Structures/Week_3_Advanced Tree Structures/Week_3_Quiz_and_Reference Manual.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/brianchiang-tw/Accelerated_Computer_Science_Fundamentals_Specialization/ff5f477f10e514c46e417a8dab4d4e60100725d5/Course_2_Ordered Data Structures/Week_3_Advanced Tree Structures/Week_3_Quiz_and_Reference Manual.pdf -------------------------------------------------------------------------------- /Course_2_Ordered Data Structures/Week_4_Heap Structures/Week4_Challenge_implementation.cpp: -------------------------------------------------------------------------------- 1 | 2 | 3 | // Implement below the downHeap procedure for a min heap. 4 | 5 | // Unlike the video lessons which demonstrated downHeap 6 | // implemented with an array implementation, this assignment 7 | // uses an ordinary binary tree with left and right child 8 | // pointers. This ordinary binary tree might not be complete 9 | // or balanced: any node might have only one child or the other, 10 | // or both, or neither. 11 | 12 | // Suppose you are given a tree where the left and right 13 | // subtrees are min heaps, but the root node does not 14 | // maintain the min heap property. Your code should 15 | // modify the tree rooted at Node* n so it is a min heap. 16 | // (This means you need to satisfy the min heap property: 17 | // it is okay for a node's value to be equal to one or both 18 | // of its children, but the node's value must not be greater 19 | // than either of its children. You do not have to try to 20 | // balance the tree or make it a complete tree.) 21 | 22 | // Tips: 23 | // If the root node exists, and if it has a left or right 24 | // child, and if one of the children has a smaller value 25 | // than the root node, then you should swap the root node 26 | // with the smaller child to move the large value down 27 | // into the tree. (This may need to be done recursively.) 28 | // Be careful to check whether pointers are null before 29 | // dereferencing them, as always; that includes using "->" 30 | // to access a class member through a pointer. In addition, 31 | // you must be careful not to accidentally compare "left" 32 | // and "right" pointers directly if you really intend to 33 | // compare the stored values "left->value" and "right->value". 34 | 35 | // Assume that these headers have already been included 36 | // for you: 37 | 38 | #include 39 | #include 40 | using namespace std; 41 | 42 | // You have the following class Node already defined. 43 | // You cannot change this class definition, so it is 44 | // shown here in a comment for your reference only: 45 | 46 | class Node { 47 | public: 48 | int value; 49 | Node *left, *right; 50 | Node(int val = 0) { value = val; left = right = nullptr; } 51 | ~Node() { 52 | delete left; 53 | left = nullptr; 54 | delete right; 55 | right = nullptr; 56 | } 57 | }; 58 | 59 | // This function has also previously been defined for you: 60 | 61 | // void printTreeVertical(const Node* n); 62 | 63 | // You can use it to print a verbose, vertical diagram of 64 | // a tree rooted at n. In this vertical format, a left child 65 | // is shown above a right child in the same column. If no 66 | // child exists, [null] is displayed. 67 | 68 | 69 | 70 | Node* smaller_children( Node *n) 71 | { 72 | if( nullptr != n->left && nullptr != n->right ) 73 | { 74 | if( n->left->value <= n->right->value ) 75 | { 76 | return n->left; 77 | } 78 | else 79 | { 80 | return n->right; 81 | } 82 | } 83 | else if( nullptr == n->left && nullptr != n->right) 84 | { 85 | return n->right; 86 | } 87 | else if( nullptr == n->right && nullptr != n->left ) 88 | { 89 | return n->left; 90 | } 91 | else 92 | { 93 | return nullptr; 94 | } 95 | 96 | } 97 | //end of function smaller_children 98 | 99 | void downHeap(Node *n) { 100 | 101 | // Implement downHeap() here. 102 | Node *smaller_node = smaller_children( n ); 103 | 104 | if( nullptr != smaller_node ) 105 | { 106 | if( smaller_node->value < n->value ) 107 | { 108 | //swap( smaller_node->value, n->value); 109 | 110 | int temp = smaller_node->value; 111 | smaller_node->value = n->value; 112 | n->value = temp; 113 | 114 | downHeap(smaller_node); 115 | } 116 | else 117 | { 118 | return; 119 | } 120 | 121 | } 122 | 123 | return; 124 | } 125 | //end of function downHeap 126 | 127 | // You can also use this compact printing function for debugging. 128 | void printTree(Node *n) { 129 | if (!n) return; 130 | std::cout << n->value << "("; 131 | printTree(n->left); 132 | std::cout << ")("; 133 | printTree(n->right); 134 | std::cout << ")"; 135 | } 136 | 137 | 138 | 139 | // expected output of main: 140 | /* 141 | Compact printout: 142 | 1(100()())(2(3()())(4()(5()()))) 143 | */ 144 | 145 | 146 | int main() { 147 | Node *n = new Node(100); 148 | n->left = new Node(1); 149 | n->right = new Node(2); 150 | n->right->left = new Node(3); 151 | n->right->right = new Node(4); 152 | n->right->right->right = new Node(5); 153 | 154 | downHeap(n); 155 | 156 | std::cout << "Compact printout:" << std::endl; 157 | printTree(n); 158 | //std::cout << std::endl << "Vertical printout:" << std::endl; 159 | //printTreeVertical(n); 160 | 161 | delete n; 162 | n = nullptr; 163 | 164 | return 0; 165 | } 166 | -------------------------------------------------------------------------------- /Course_2_Ordered Data Structures/Week_4_Heap Structures/Week4_Challenge_implementation.exe: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/brianchiang-tw/Accelerated_Computer_Science_Fundamentals_Specialization/ff5f477f10e514c46e417a8dab4d4e60100725d5/Course_2_Ordered Data Structures/Week_4_Heap Structures/Week4_Challenge_implementation.exe -------------------------------------------------------------------------------- /Course_2_Ordered Data Structures/Week_4_Heap Structures/Week_4_Challenge_and_Reference Solution.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/brianchiang-tw/Accelerated_Computer_Science_Fundamentals_Specialization/ff5f477f10e514c46e417a8dab4d4e60100725d5/Course_2_Ordered Data Structures/Week_4_Heap Structures/Week_4_Challenge_and_Reference Solution.pdf -------------------------------------------------------------------------------- /Course_2_Ordered Data Structures/Week_4_Heap Structures/Week_4_Quiz_and_Reference Manual.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/brianchiang-tw/Accelerated_Computer_Science_Fundamentals_Specialization/ff5f477f10e514c46e417a8dab4d4e60100725d5/Course_2_Ordered Data Structures/Week_4_Heap Structures/Week_4_Quiz_and_Reference Manual.pdf -------------------------------------------------------------------------------- /Course_3_Unorder Data Structures/Week_1_Hashing/Week_1_Challenge_and_Reference Solution.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/brianchiang-tw/Accelerated_Computer_Science_Fundamentals_Specialization/ff5f477f10e514c46e417a8dab4d4e60100725d5/Course_3_Unorder Data Structures/Week_1_Hashing/Week_1_Challenge_and_Reference Solution.pdf -------------------------------------------------------------------------------- /Course_3_Unorder Data Structures/Week_1_Hashing/Week_1_Challenge_imlementation.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | 7 | using namespace std; 8 | 9 | int insert(int value, std::vector &table) { 10 | // Code to insert value into a hashed location in table 11 | // where table is a vector of length 1000. 12 | // Returns the number of collisions encountered when 13 | // trying to insert value into table. 14 | int hash = value % 1000; 15 | int collisions = 0; 16 | 17 | if( -1 == table[hash] ) 18 | { 19 | // hash slot is available, update hash table with value 20 | table[hash] = value; 21 | } 22 | else 23 | { 24 | 25 | while( -1 != table[hash] ) 26 | { 27 | // hash collision occurrs 28 | collisions++; 29 | 30 | // linear probe 31 | hash++; 32 | } 33 | 34 | // probe a available slot, upte hash table with value 35 | table[hash] = value; 36 | 37 | } 38 | 39 | return collisions; 40 | } 41 | //end of function insert 42 | 43 | 44 | // expected output of main: 45 | /* 46 | 47 | Hashing value 23373 experienced 11 collisions. 48 | 49 | 0: 7000 19000 17002 1007 16008 50 | 10: 14011 13014 51 | 20: 7021 15022 9026 12029 52 | 30: 18032 10034 3036 21038 2039 53 | 40: 6039 41 2042 8042 21038 24045 20046 11048 54 | 50: 4050 2053 18056 11057 20059 55 | 60: 17060 23059 5069 56 | 70: 24070 19072 2075 3078 8078 57 | 80: 22078 15082 12084 20086 20088 58 | 90: 4090 5090 13090 9093 16094 24097 1098 14099 59 | 100: 15100 16099 1102 22102 1104 17106 108 2108 60 | 110: 7109 18110 12112 6113 11114 10119 61 | 120: 18120 9121 22121 23119 14125 21125 24126 62 | 130: 7131 19131 5135 63 | 140: 142 142 6144 14142 22146 23145 64 | 150: 8152 15153 24154 23155 4156 1157 12158 5159 65 | 160: 19164 18165 3166 66 | 170: 3172 8172 7177 24177 67 | 180: 2181 13182 7183 21185 11186 16187 17188 20187 68 | 190: 15192 6196 24197 21198 14199 69 | 200: 24199 11208 70 | 210: 211 3212 7213 9214 10212 15215 18214 20214 23212 71 | 220: 12220 22222 7226 72 | 230: 5231 4232 14231 19234 235 20239 73 | 240: 2245 6246 11246 1249 74 | 250: 3254 10255 75 | 260: 24261 9262 4263 14263 8268 16269 76 | 270: 17269 4271 13271 21272 10278 77 | 280: 20282 23282 24284 2286 8289 78 | 290: 7294 7294 6296 2297 15294 23297 79 | 300: 18300 5301 12306 20306 80 | 310: 313 17313 4315 18313 22316 3318 81 | 320: 19321 16324 20329 82 | 330: 5330 1331 14332 6337 8337 11338 83 | 340: 21342 9345 13346 84 | 350: 2350 1352 9352 4354 13358 13358 85 | 360: 16358 6361 10365 3366 1368 13368 86 | 370: 371 13371 9373 16372 16373 11376 22374 22376 10379 87 | 380: 4380 12381 10382 9383 23373 7385 1386 14386 18387 16389 88 | 390: 15390 24380 89 | 400: 9400 20401 23400 4403 5407 14407 17409 90 | 410: 18409 3412 9413 12414 21412 3417 2418 19418 91 | 420: 24417 6427 9427 92 | 430: 10430 10430 17431 433 8436 9436 19436 93 | 440: 4440 13440 23443 7447 21447 22447 94 | 450: 9452 11455 6457 95 | 460: 16460 17460 20462 6464 2465 96 | 470: 15477 4478 18477 97 | 480: 5480 1481 21480 12483 24478 9487 10488 98 | 490: 21491 18495 4496 497 14496 99 | 500: 13501 502 7502 8504 23501 10506 3507 15506 2509 100 | 510: 7512 19513 22513 101 | 520: 17521 12525 1528 102 | 530: 3536 9538 9538 103 | 540: 20543 11545 16546 547 20546 104 | 550: 21551 1554 6555 15555 17556 105 | 560: 6562 23565 12569 106 | 570: 2571 7571 14572 23574 24573 5577 4578 20578 107 | 580: 18582 20583 12585 10586 9587 8588 5589 108 | 590: 13589 13590 15592 18587 19586 7595 22591 24598 6599 109 | 600: 14601 11602 3606 4607 9606 16609 110 | 610: 17606 111 | 620: 16622 1625 628 2628 112 | 630: 7632 113 | 640: 18645 21647 4648 114 | 650: 655 3656 6656 15658 19656 115 | 660: 11660 23656 3662 1663 3663 2665 9662 12666 8669 116 | 670: 14669 5675 20676 16677 13679 117 | 680: 7680 4681 10682 17679 22684 118 | 690: 4696 119 | 700: 20701 8703 15707 120 | 710: 21714 716 19719 121 | 720: 2724 122 | 730: 1732 20732 13734 4735 18736 22735 18738 123 | 740: 23742 6743 1744 17745 2747 124 | 750: 11751 3756 8756 13757 13759 125 | 760: 9760 14761 16762 7763 9763 5765 11766 12764 18763 126 | 770: 127 | 780: 10780 12786 9787 2788 14786 128 | 790: 17789 19787 4793 9795 6796 4797 21799 129 | 800: 15800 3804 807 23807 130 | 810: 1811 16815 2817 22819 131 | 820: 20824 5826 4827 16827 132 | 830: 3833 16835 12837 22837 9839 133 | 840: 18840 14841 13844 9848 17848 134 | 850: 21849 11854 8855 3856 18854 7858 12858 135 | 860: 10861 5862 20866 16867 18868 136 | 870: 8873 14875 6879 137 | 880: 19879 20888 21889 138 | 890: 18892 23894 2895 15895 7899 139 | 900: 7901 902 22901 4904 140 | 910: 1910 2911 4910 8911 8911 11910 16912 5917 141 | 920: 22920 11921 11923 6924 14924 13926 16925 18926 142 | 930: 6933 9937 9939 143 | 940: 3940 17940 6942 944 1945 2946 144 | 950: 10950 7951 11957 12957 145 | 960: 19964 14965 19966 146 | 970: 971 22972 22972 20974 23971 14977 17979 147 | 980: 16981 4983 5984 21983 148 | 990: 15992 3994 8999 149 | 150 | */ 151 | 152 | int main() { 153 | int i, j, hit, max_hit = 0, max_value = -1; 154 | 155 | std::vector value(500); 156 | 157 | int old_value = 0; 158 | for (i = 0; i < 500; i++) { 159 | old_value += rand()%100; 160 | value[i] = old_value; 161 | } 162 | 163 | // create hash table of size 1000 initialized with -1 164 | std::vector table(1000,-1); 165 | 166 | for (i = 0; i < 500; i++) { 167 | hit = insert(value[i],table); 168 | if (hit > max_hit) { 169 | max_hit = hit; 170 | max_value = value[i]; 171 | } 172 | } 173 | 174 | std::cout << "Hashing value " << max_value << " experienced " << max_hit << " collisions." << std::endl < // for std::hash 13 | #include // for std::pair 14 | #include // for std::string 15 | 16 | // We don't have to define an entire IntPair class ourselves since 17 | // C++ provides a templated pair type already. 18 | // We define IntPair as a type alias for convenience. 19 | using IntPair = std::pair; 20 | 21 | // In the C++ standard library, classes like std::unordered_map and 22 | // std::unordered_set use the default hashing object std::hash internally. 23 | // However, std::hash doesn't natively support all possible types, 24 | // just a few of the primitive C++ types like int and std::string. 25 | // For more specific types, such as std::pair, or for custom 26 | // classes you make yourself, you need to specify a hashing function. 27 | // Since std::hash is templated, we can add new cases for it using 28 | // what is called "template specialization". 29 | 30 | // In addition, custom class types made by users will also need to define 31 | // their equivalence relation function, operator==, for this to work. 32 | // Fortunately, std::pair already gives us that automatically. 33 | 34 | // ------------------------------------------------------------------ 35 | 36 | // Reference: https://en.cppreference.com/w/cpp/utility/hash 37 | 38 | // We're adding more content to the standard namespace. 39 | // (This isn't normally something you should do casually.) 40 | namespace std { 41 | 42 | // A minor detail: std::hash is a struct, not a class. 43 | // In C++, a struct is very similar to a class, but it has public 44 | // members by default. 45 | 46 | // The "template <>" syntax indicates that we are specializing an existing 47 | // template for std::hash. 48 | 49 | template <> 50 | struct hash { 51 | 52 | // By overriding the () "operator", we can make an instance of a class 53 | // respond to similar syntax as if it were merely a function name. 54 | // The std::hash type is intended to work this way, as a "function object". 55 | // See also: https://en.cppreference.com/w/cpp/utility/functional 56 | 57 | // The () operator definition is where we will essentially define 58 | // our custom hashing function, and it returns the actual hash 59 | // as a std::size_t value (which is an integral type). 60 | std::size_t operator() (const IntPair& p) const { 61 | 62 | // We know that std::string has a well-defined hasher already, 63 | // so we'll turn our pair of ints into a unique string representation, 64 | // and then just hash that. We'll turn each integer into a string 65 | // and concatenate them with "##" in the middle, which should make 66 | // a unique string for any given pair of ints. 67 | std::string uniqueIntPairString = std::to_string(p.first) + "##" + std::to_string(p.second); 68 | 69 | // Get the default hashing function object for a std::string. 70 | std::hash stringHasher; 71 | // Use the string hasher on our unique string. 72 | return stringHasher(uniqueIntPairString); 73 | } 74 | }; 75 | 76 | } 77 | 78 | -------------------------------------------------------------------------------- /Course_3_Unorder Data Structures/Week_1_Hashing/Week_1_Project_UnorderedMap/UnorderedMap/Makefile: -------------------------------------------------------------------------------- 1 | # Executable names: 2 | EXE = main 3 | TEST = test 4 | 5 | # Add all object files needed for compiling: 6 | EXE_OBJ = main.o 7 | OBJS = main.o 8 | 9 | # Generated files 10 | # (none) 11 | 12 | # Include the master templated makefile: 13 | include uiuc/make/uiuc.mk 14 | -------------------------------------------------------------------------------- /Course_3_Unorder Data Structures/Week_1_Hashing/Week_1_Project_UnorderedMap/UnorderedMap/UnorderedMapCommon.h: -------------------------------------------------------------------------------- 1 | 2 | /** 3 | * @file UnorderedMapCommon.h 4 | * University of Illinois CS 400, MOOC 3, Week 1: Unordered Map 5 | * 6 | * @author Eric Huber 7 | * 8 | **/ 9 | 10 | // -------------------------------------------------------------- 11 | // This file has some common includes and helper functions 12 | // that are used by several other parts of the program. 13 | // -------------------------------------------------------------- 14 | 15 | // We use the pragma once directive to ensure that this header won't 16 | // be included multiple times per compilation unit by mistake. 17 | #pragma once 18 | 19 | #include // for std::string 20 | #include // for std::vector 21 | #include // for std::pair 22 | #include // for std::unordered_map 23 | #include // for std::chrono::high_resolution_clock 24 | 25 | // ------------------------------------------------------------------------ 26 | // About the timer code 27 | // ---------------------- 28 | // We use this timer code to help catch mistakes that could cause one 29 | // of the examples to infinite loop. You don't need to study how it works. 30 | 31 | // References for chrono library usage: 32 | // https://en.cppreference.com/w/cpp/chrono/high_resolution_clock/now 33 | // https://en.cppreference.com/w/cpp/chrono/duration/duration_cast 34 | using timeUnit = std::chrono::time_point; 35 | static inline timeUnit getTimeNow() noexcept { 36 | return std::chrono::high_resolution_clock::now(); 37 | } 38 | template 39 | static double getMilliDuration(T start_time, T stop_time) { 40 | std::chrono::duration dur_ms = stop_time - start_time; 41 | return dur_ms.count(); 42 | } 43 | // ------------------------------------------------------------------------ 44 | 45 | // ------------------------------------------------------------------------ 46 | // About std::pair 47 | // ----------------- 48 | // This "pair" type is a templated way to create a new type that pairs any 49 | // two other types together as a unit. 50 | // 51 | // When you want to construct a std::pair, there is a templated helper 52 | // function that can construct ANY variation of pair for us. For example: 53 | // 54 | // std::pair myPair = std::make_pair("hello", 7); 55 | // 56 | // When you do so, each pair has the members "first" and "second" that 57 | // correspond to the two parts. As we define below, our StringIntPair type 58 | // combines a string and an int. The "first" member is the string, and the 59 | // "second" member is the int. 60 | // 61 | // std::string str = myPair.first; // str == "hello" 62 | // int x = myPair.second; // x == 7 63 | // ------------------------------------------------------------------------ 64 | 65 | // Here are some convenient type aliases for word counting. 66 | // (We are just making alternative, shorter names for these STL types.) 67 | using StringVec = std::vector; 68 | using StringIntPair = std::pair; 69 | using StringIntMap = std::unordered_map; 70 | using StringIntPairVec = std::vector; 71 | 72 | // The palindrome exercise involves pairs of integer indices, and in particular, 73 | // we want to be able to put these in unordered_map or unordered_set as keys, 74 | // which requires hashing support. (We're going to need to specify how to hash 75 | // a pair of integers, because the standard library doesn't support this natively.) 76 | #include "IntPair.h" // for IntPair definition as well as custom hashing support 77 | 78 | // Type alias for the palindrome problem: 79 | // LengthMemo is a "memoization" table (please read the instructions PDF 80 | // for more explanation about that). It maps a pair of int indices to an int 81 | // palindrome length. This is meant to represent the maximum length of any 82 | // palindrome substring found between the given indices. 83 | using LengthMemo = std::unordered_map; 84 | 85 | // Load the whole book "Through the Looking-Glass" as vector of strings. 86 | // (This is handled for you.) 87 | // Only strings of at least min_word_length are included (default: 5) 88 | // and they will be converted to lowercase. Hyphens (-) and apostrophes (') 89 | // are included in words where they are found, so strings like "alice" and 90 | // "alice's" are counted separately as unique words. 91 | StringVec loadBookStrings(unsigned int min_word_length=5); 92 | 93 | // This helper function can be used to sort records of word counts 94 | // based on the count. This is used in sortWordCounts. 95 | bool wordCountComparator(const StringIntPair& x, const StringIntPair& y); 96 | 97 | // sortWordCounts produces a fresh vector containing sorted copies 98 | // of the word count records from wordcount_map. 99 | StringIntPairVec sortWordCounts(const StringIntMap& wordcount_map); 100 | 101 | // ------------------------------------------------------------------------- 102 | // makeWordCounts takes a vector of strings and counts the number of occurences 103 | // of each unique string. 104 | // NOTE: You will implement this function yourself in UnorderedMapExercises.cpp 105 | StringIntMap makeWordCounts(const StringVec& words); 106 | // ------------------------------------------------------------------------- 107 | 108 | // ------------------------------------------------------------------------- 109 | // lookupWithFallback is a wrapper function for safely performing read-only 110 | // lookups in a std::unordered_map object. 111 | // NOTE: You will implement this function yourself in UnorderedMapExercises.cpp 112 | int lookupWithFallback(const StringIntMap& wordcount_map, const std::string& key, int fallbackVal); 113 | // ------------------------------------------------------------------------- 114 | 115 | // These functions make lists (actually, std::vector) of the most common and least common 116 | // words found in the book. As input, these take the result of sortWordCounts. 117 | // (These don't try to combine variations of words like "alice" and "alice's" 118 | // in any way, so it's not entirely accurate.) 119 | StringIntPairVec getBottomWordCounts(const StringIntPairVec& sorted_wordcounts, unsigned int max_words=20); 120 | StringIntPairVec getTopWordCounts(const StringIntPairVec& sorted_wordcounts, unsigned int max_words=20); 121 | 122 | // longestPalindromeLength uses brute-force recursion to calculate the 123 | // longest palindrome substring within str, based on the left and right index 124 | // limits given. It also takes clock information to prevent running too long, 125 | // in some cases. 126 | int longestPalindromeLength(const std::string& str, int leftLimit, int rightLimit, timeUnit startTime, double maxDuration); 127 | 128 | // ------------------------------------------------------------------------- 129 | // This is a "memoized" version of the longestPalindromeLength function. 130 | // (Please read the instructions PDF for information about what "memoization" 131 | // is all about.) 132 | // NOTE: You will implement part of this function yourself in UnorderedMapExercises.cpp 133 | int memoizedLongestPalindromeLength(LengthMemo& memo, const std::string& str, int leftLimit, int rightLimit, timeUnit startTime, double maxDuration); 134 | // ------------------------------------------------------------------------- 135 | 136 | // reconstructPalindrome returns a copy of the longest palindrome within str, 137 | // based on the information provided by the memoization table that has been 138 | // previously calculated by memoizedLongestPalindromeLength. 139 | std::string reconstructPalindrome(const LengthMemo& memo, const std::string& str); 140 | 141 | // The timer code we use to prevent your functions from running too long by mistake 142 | // can throw this exception to show what has happened. The unit tests handle this 143 | // situation for you. 144 | class TooSlowException : public std::runtime_error { 145 | public: 146 | // import constructor from the base class 147 | using std::runtime_error::runtime_error; 148 | }; 149 | -------------------------------------------------------------------------------- /Course_3_Unorder Data Structures/Week_1_Hashing/Week_1_Project_UnorderedMap/UnorderedMap/tests/week1_tests.cpp: -------------------------------------------------------------------------------- 1 | 2 | // University of Illinois CS 400, MOOC 3, Week 1: Unordered Map 3 | // Author: Eric Huber, University of Illinois staff 4 | // Autograder based on Zephyr test runner by Prof. Wade Fagen-Ulmschneider and the CS 225 Course Staff 5 | // Based on Catch2 unit testing framework 6 | 7 | #include 8 | #include 9 | #include 10 | #include 11 | 12 | #include "../uiuc/catch/catch.hpp" 13 | 14 | #include "../UnorderedMapCommon.h" 15 | 16 | // May be useful in writing some tests 17 | template 18 | void assertPtr(T* ptr) { 19 | if (!ptr) { 20 | throw std::runtime_error("Would have dereferenced a null pointer"); 21 | } 22 | } 23 | 24 | template 25 | T& deref(T* ptr) { 26 | if (!ptr) { 27 | throw std::runtime_error("Would have dereferenced a null pointer"); 28 | } 29 | else { 30 | return *ptr; 31 | } 32 | } 33 | 34 | // ======================================================================== 35 | // Tests: makeWordCounts 36 | // ======================================================================== 37 | 38 | TEST_CASE("Testing makeWordCounts:", "[weight=1]") { 39 | 40 | constexpr int MIN_WORD_LENGTH = 5; 41 | StringVec bookstrings = loadBookStrings(MIN_WORD_LENGTH); 42 | StringIntMap wordcount_map = makeWordCounts(bookstrings); 43 | 44 | SECTION("Checking that map contains the right number of keys") { 45 | const int number_of_keys = wordcount_map.size(); 46 | const int number_of_keys_expected = 2181; 47 | REQUIRE(number_of_keys == number_of_keys_expected); 48 | } 49 | 50 | SECTION("Checking that \"bandersnatch\" was counted 3 times") { 51 | bool found_bandersnatch = wordcount_map.count("bandersnatch"); 52 | if (found_bandersnatch) { 53 | const int bandersnatch_count = wordcount_map["bandersnatch"]; 54 | const int bandersnatch_count_expected = 3; 55 | REQUIRE(bandersnatch_count == bandersnatch_count_expected); 56 | } 57 | else { 58 | REQUIRE(found_bandersnatch); 59 | } 60 | } 61 | 62 | SECTION("Checking that \"alice\" was recorded 434 times") { 63 | bool found_alice = wordcount_map.count("alice"); 64 | if (found_alice) { 65 | const int alice_count = wordcount_map["alice"]; 66 | const int alice_count_expected = 434; 67 | REQUIRE(alice_count == alice_count_expected); 68 | } 69 | else { 70 | REQUIRE(found_alice); 71 | } 72 | } 73 | 74 | SECTION("Checking that \"frabjous\" was recorded 1 time") { 75 | bool found_frabjous = wordcount_map.count("frabjous"); 76 | if (found_frabjous) { 77 | const int frabjous_count = wordcount_map["frabjous"]; 78 | const int frabjous_count_expected = 1; 79 | REQUIRE(frabjous_count == frabjous_count_expected); 80 | } 81 | else { 82 | REQUIRE(found_frabjous); 83 | } 84 | } 85 | 86 | } 87 | 88 | // ======================================================================== 89 | // Tests: lookupWithFallback (with no dependency on makeWordCounts) 90 | // ======================================================================== 91 | 92 | TEST_CASE("Testing lookupWithFallback: When the key exists", "[weight=1]") { 93 | 94 | StringIntMap wordcount_map; 95 | wordcount_map["bandersnatch"] = 3; 96 | 97 | SECTION("Should return the found value") { 98 | const int bandersnatch_count = lookupWithFallback(wordcount_map, "bandersnatch", 0); 99 | const int bandersnatch_count_expected = 3; 100 | REQUIRE(bandersnatch_count == bandersnatch_count_expected); 101 | } 102 | 103 | SECTION("Map should not be changed by lookup") { 104 | auto wordcount_map_backup = wordcount_map; 105 | const int bandersnatch_count = lookupWithFallback(wordcount_map, "bandersnatch", 0); 106 | REQUIRE(wordcount_map == wordcount_map_backup); 107 | } 108 | 109 | } 110 | 111 | TEST_CASE("Testing lookupWithFallback: When the key doesn't exist", "[weight=1]") { 112 | 113 | StringIntMap wordcount_map; 114 | 115 | SECTION("Should return the fallback value when key not found") { 116 | const int not_found_result = lookupWithFallback(wordcount_map, "cheshire", -7); 117 | const int not_found_result_expected = -7; 118 | REQUIRE(not_found_result == not_found_result_expected); 119 | } 120 | 121 | SECTION("Map should not be changed by lookup") { 122 | auto wordcount_map_backup = wordcount_map; 123 | const int cheshire_count = lookupWithFallback(wordcount_map, "cheshire", -7); 124 | REQUIRE(wordcount_map == wordcount_map_backup); 125 | } 126 | 127 | } 128 | 129 | // ======================================================================== 130 | // Tests: memoizedLongestPalindromeLength 131 | // ======================================================================== 132 | 133 | TEST_CASE("Testing memoizedLongestPalindromeLength: Should return correct length", "[weight=1]") { 134 | 135 | SECTION("Should return correct length") { 136 | LengthMemo memo; 137 | const std::string str_small = "abbbcdeeeefgABCBAz"; 138 | const double max_duration = 10000.0; // 10 seconds 139 | const auto start_time = getTimeNow(); 140 | const auto str = str_small; 141 | const int pal_result = memoizedLongestPalindromeLength(memo, str, 0, str.length()-1, start_time, max_duration); 142 | const int pal_result_expected = 5; 143 | const bool returned_correct_length = (pal_result == 5); 144 | REQUIRE(pal_result == pal_result_expected); 145 | } 146 | 147 | } 148 | 149 | TEST_CASE("Testing memoizedLongestPalindromeLength: Memoization table should be complete", "[weight=1]") { 150 | 151 | SECTION("Should be able to reconstruct correct palindrome from memoization table") { 152 | LengthMemo memo; 153 | const std::string str_small = "abbbcdeeeefgABCBAz"; 154 | const double max_duration = 10000.0; // 10 seconds 155 | const auto start_time = getTimeNow(); 156 | const auto str = str_small; 157 | const int pal_result = memoizedLongestPalindromeLength(memo, str, 0, str.length()-1, start_time, max_duration); 158 | const std::string reconstructed_palindrome = reconstructPalindrome(memo, str); 159 | const std::string reconstructed_palindrome_expected = "ABCBA"; 160 | REQUIRE(reconstructed_palindrome == reconstructed_palindrome_expected); 161 | } 162 | 163 | } 164 | -------------------------------------------------------------------------------- /Course_3_Unorder Data Structures/Week_1_Hashing/Week_1_Project_UnorderedMap/UnorderedMap/uiuc/catch/catchmain.cpp: -------------------------------------------------------------------------------- 1 | #define CATCH_CONFIG_MAIN 2 | #include "catch.hpp" 3 | -------------------------------------------------------------------------------- /Course_3_Unorder Data Structures/Week_1_Hashing/Week_1_Project_UnorderedMap/UnorderedMap/uiuc/make/uiuc.mk: -------------------------------------------------------------------------------- 1 | 2 | # University of Illinois 3 | # CS 400 - MOOC 3 - Week 1 - Unordered Map 4 | 5 | # Original Makefile created by Wade Fagen-Ulmschneider 6 | # Modified for CS 400 by Eric Huber 7 | 8 | ZIP_FILE = UnorderedMap_submission.zip 9 | COLLECTED_FILES = UnorderedMapExercises.cpp 10 | 11 | # Add standard object files (HSLAPixel, PNG, and LodePNG) 12 | OBJS += UnorderedMapCommon.o UnorderedMapExercises.o 13 | 14 | # Use ./.objs to store all .o file (keeping the directory clean) 15 | OBJS_DIR = .objs 16 | 17 | # Use all .cpp files in /tests/ 18 | OBJS_TEST = $(filter-out $(EXE_OBJ), $(OBJS)) 19 | CPP_TEST = $(wildcard tests/*.cpp) 20 | CPP_TEST += uiuc/catch/catchmain.cpp 21 | OBJS_TEST += $(CPP_TEST:.cpp=.o) 22 | 23 | # Config 24 | CXX_CLANG = clang++ 25 | CXX_GCC = g++ 26 | CXX_WHICH = $(CXX_GCC) 27 | CXX = $(CXX_WHICH) 28 | LD = $(CXX_WHICH) 29 | # STDVERSION = -std=c++1y # deprecated nomenclature 30 | STDVERSION = -std=c++14 # proper but requires newer compiler versions (for better or worse) 31 | STDLIBVERSION_CLANG = -stdlib=libc++ # Clang's version; not present on default AWS Cloud9 instance 32 | STDLIBVERSION_GCC = # blank on purpose; default GNU library 33 | ifeq ($(CXX_WHICH),$(CXX_CLANG)) 34 | STDLIBVERSION = $(STDLIBVERSION_CLANG) 35 | else 36 | STDLIBVERSION = $(STDLIBVERSION_GCC) 37 | endif 38 | WARNINGS = -pedantic -Wall -Wfatal-errors -Wextra -Wno-unused-parameter -Wno-unused-variable 39 | # ASANFLAGS = -fsanitize=address -fno-omit-frame-pointer 40 | # NO_COPY_ELISION = -fno-elide-constructors 41 | CXXFLAGS = $(CS400) $(STDVERSION) $(STDLIBVERSION) -g -O0 $(WARNINGS) -MMD -MP -msse2 -c $(ASANFLAGS) $(NO_COPY_ELISION) 42 | LDFLAGS = $(CS400) $(STDVERSION) $(STDLIBVERSION) -lpthread $(ASANFLAGS) $(NO_COPY_ELISION) 43 | 44 | ifneq ($(strip $(ASANFLAGS)),) 45 | # This is displayed if ASANFLAGS is not blank. 46 | ASANWARNING = "\n >>>>>>>>>> Note: ASAN is in use. May not be supported on Cloud9. <<<<<<<<<<" 47 | endif 48 | 49 | # Rules for first executable 50 | $(EXE): 51 | $(LD) $^ $(LDFLAGS) -o $@ 52 | @echo 53 | @echo " Built the main executable program file for the project: " $(EXE) 54 | @echo " (Make sure you try \"make test\" too!)" 55 | @echo $(ASANWARNING) 56 | 57 | # Rule for `all` 58 | all: $(EXE) $(TEST) 59 | 60 | # Pattern rules for object files 61 | $(OBJS_DIR): 62 | @mkdir -p $(OBJS_DIR) 63 | @mkdir -p $(OBJS_DIR)/uiuc 64 | @mkdir -p $(OBJS_DIR)/uiuc/catch 65 | @mkdir -p $(OBJS_DIR)/tests 66 | 67 | $(OBJS_DIR)/%.o: %.cpp | $(OBJS_DIR) 68 | $(CXX) $(CXXFLAGS) $< -o $@ 69 | 70 | # Rules for executables 71 | $(TEST): 72 | $(LD) $^ $(LDFLAGS) -o $@ 73 | @echo 74 | @echo " Built the test suite program: " $(TEST) 75 | @echo $(ASANWARNING) 76 | 77 | # Executable dependencies 78 | $(EXE): $(patsubst %.o, $(OBJS_DIR)/%.o, $(OBJS)) 79 | $(TEST): $(patsubst %.o, $(OBJS_DIR)/%.o, $(OBJS_TEST)) 80 | 81 | # some explicit dependencies for efficient recompilation on this assignment 82 | $(OBJS_DIR)/UnorderedMapCommon.o: IntPair.h UnorderedMapCommon.h UnorderedMapCommon.cpp 83 | $(OBJS_DIR)/UnorderedMapExercises.o: IntPair.h UnorderedMapCommon.h UnorderedMapExercises.cpp 84 | $(OBJS_DIR)/main.o: IntPair.h 85 | 86 | # Include automatically generated dependencies 87 | -include $(OBJS_DIR)/*.d 88 | -include $(OBJS_DIR)/uiuc/*.d 89 | -include $(OBJS_DIR)/uiuc/catch/*.d 90 | -include $(OBJS_DIR)/tests/*.d 91 | 92 | clean: 93 | rm -rf $(EXE) $(TEST) $(OBJS_DIR) $(CLEAN_RM) 94 | 95 | tidy: clean 96 | rm -rf doc 97 | 98 | zip: 99 | @echo "!!! Preparing submission zip with student code..." 100 | @echo "!!! Make sure you have already tried compiling and testing your code" 101 | @echo "!!! thoroughly before submitting the zip on Coursera!" 102 | @echo "" 103 | @echo "Removing any previous version of zip file..." 104 | rm -rf $(ZIP_FILE) 105 | @echo "Creating new file..." 106 | zip $(ZIP_FILE) $(COLLECTED_FILES) 107 | @echo "Created zip file: " $(ZIP_FILE) 108 | 109 | .PHONY: all tidy clean zip 110 | -------------------------------------------------------------------------------- /Course_3_Unorder Data Structures/Week_1_Hashing/Week_1_Project_UnorderedMap/UnorderedMap/v20190502a.txt: -------------------------------------------------------------------------------- 1 | Release version 20190502a 2 | 3 | -------------------------------------------------------------------------------- /Course_3_Unorder Data Structures/Week_1_Hashing/Week_1_Project_UnorderedMap_Description.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/brianchiang-tw/Accelerated_Computer_Science_Fundamentals_Specialization/ff5f477f10e514c46e417a8dab4d4e60100725d5/Course_3_Unorder Data Structures/Week_1_Hashing/Week_1_Project_UnorderedMap_Description.pdf -------------------------------------------------------------------------------- /Course_3_Unorder Data Structures/Week_1_Hashing/Week_1_Project_UnorderedMap_full implementation.zip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/brianchiang-tw/Accelerated_Computer_Science_Fundamentals_Specialization/ff5f477f10e514c46e417a8dab4d4e60100725d5/Course_3_Unorder Data Structures/Week_1_Hashing/Week_1_Project_UnorderedMap_full implementation.zip -------------------------------------------------------------------------------- /Course_3_Unorder Data Structures/Week_1_Hashing/Week_1_Project_UnorderedMap_starter_files.zip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/brianchiang-tw/Accelerated_Computer_Science_Fundamentals_Specialization/ff5f477f10e514c46e417a8dab4d4e60100725d5/Course_3_Unorder Data Structures/Week_1_Hashing/Week_1_Project_UnorderedMap_starter_files.zip -------------------------------------------------------------------------------- /Course_3_Unorder Data Structures/Week_1_Hashing/Week_1_Quiz_and_Reference Manual.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/brianchiang-tw/Accelerated_Computer_Science_Fundamentals_Specialization/ff5f477f10e514c46e417a8dab4d4e60100725d5/Course_3_Unorder Data Structures/Week_1_Hashing/Week_1_Quiz_and_Reference Manual.pdf -------------------------------------------------------------------------------- /Course_3_Unorder Data Structures/Week_1_Hashing/Week_1_UnorderedMap_submission.zip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/brianchiang-tw/Accelerated_Computer_Science_Fundamentals_Specialization/ff5f477f10e514c46e417a8dab4d4e60100725d5/Course_3_Unorder Data Structures/Week_1_Hashing/Week_1_UnorderedMap_submission.zip -------------------------------------------------------------------------------- /Course_3_Unorder Data Structures/Week_2_Disjoint-sets/Week2_Challenge_implementation.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | //vector traversal_path; 5 | 6 | 7 | class DisjointSets { 8 | public: 9 | int s[256]; 10 | 11 | DisjointSets() { for (int i = 0; i < 256; i++) s[i] = -1; } 12 | 13 | int find(int i); 14 | }; 15 | 16 | /* Modify the find() method below 17 | * to implement path compression 18 | * so that element i and all of 19 | * its ancestors in the up-tree 20 | * point to directly to the root 21 | * after find() completes. 22 | */ 23 | 24 | /* 25 | int DisjointSets::find(int i) { 26 | if ( s[i] < 0 ) { 27 | return i; 28 | } else { 29 | return find(s[i]); 30 | } 31 | } 32 | */ 33 | 34 | int DisjointSets::find( int i) 35 | { 36 | 37 | static std::vector traversal_path; 38 | 39 | if( s[i] < 0 ) 40 | { 41 | for( auto iter = traversal_path.begin() ; iter != traversal_path.end() ; iter++) 42 | { 43 | // path compression from i to root node 44 | int node = *iter; 45 | s[ node ] = i; 46 | 47 | } 48 | 49 | // return the name(i.e., array index) of Disjoint set 50 | return i; 51 | } 52 | else 53 | { 54 | //add currnet node into traversal path 55 | traversal_path.push_back( i ); 56 | return find( s[i] ); 57 | } 58 | 59 | } 60 | //end of function int DisjointSet::find( int i) 61 | 62 | 63 | // expected output of main: 64 | 65 | /* 66 | 67 | d.find(3) = 7 68 | d.s(1) = 3 69 | d.s(3) = 7 70 | d.s(5) = 7 71 | d.s(7) = -1 72 | 73 | */ 74 | 75 | 76 | int main() { 77 | DisjointSets d; 78 | 79 | d.s[1] = 3; 80 | d.s[3] = 5; 81 | d.s[5] = 7; 82 | d.s[7] = -1; 83 | 84 | std::cout << "d.find(3) = " << d.find(3) << std::endl; 85 | std::cout << "d.s(1) = " << d.s[1] << std::endl; 86 | std::cout << "d.s(3) = " << d.s[3] << std::endl; 87 | std::cout << "d.s(5) = " << d.s[5] << std::endl; 88 | std::cout << "d.s(7) = " << d.s[7] << std::endl; 89 | 90 | return 0; 91 | } -------------------------------------------------------------------------------- /Course_3_Unorder Data Structures/Week_2_Disjoint-sets/Week2_Challenge_implementation.exe: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/brianchiang-tw/Accelerated_Computer_Science_Fundamentals_Specialization/ff5f477f10e514c46e417a8dab4d4e60100725d5/Course_3_Unorder Data Structures/Week_2_Disjoint-sets/Week2_Challenge_implementation.exe -------------------------------------------------------------------------------- /Course_3_Unorder Data Structures/Week_2_Disjoint-sets/Week_2_Challenge_and_Reference Solution.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/brianchiang-tw/Accelerated_Computer_Science_Fundamentals_Specialization/ff5f477f10e514c46e417a8dab4d4e60100725d5/Course_3_Unorder Data Structures/Week_2_Disjoint-sets/Week_2_Challenge_and_Reference Solution.pdf -------------------------------------------------------------------------------- /Course_3_Unorder Data Structures/Week_2_Disjoint-sets/Week_2_Quiz_and_Reference Manual.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/brianchiang-tw/Accelerated_Computer_Science_Fundamentals_Specialization/ff5f477f10e514c46e417a8dab4d4e60100725d5/Course_3_Unorder Data Structures/Week_2_Disjoint-sets/Week_2_Quiz_and_Reference Manual.pdf -------------------------------------------------------------------------------- /Course_3_Unorder Data Structures/Week_3_Graph/Graph implementation.PNG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/brianchiang-tw/Accelerated_Computer_Science_Fundamentals_Specialization/ff5f477f10e514c46e417a8dab4d4e60100725d5/Course_3_Unorder Data Structures/Week_3_Graph/Graph implementation.PNG -------------------------------------------------------------------------------- /Course_3_Unorder Data Structures/Week_3_Graph/Week_3_Challenge_and_Reference Solution.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/brianchiang-tw/Accelerated_Computer_Science_Fundamentals_Specialization/ff5f477f10e514c46e417a8dab4d4e60100725d5/Course_3_Unorder Data Structures/Week_3_Graph/Week_3_Challenge_and_Reference Solution.pdf -------------------------------------------------------------------------------- /Course_3_Unorder Data Structures/Week_3_Graph/Week_3_Challenge_implementation.cpp: -------------------------------------------------------------------------------- 1 | 2 | #include 3 | 4 | // You are provided this version of a DisjointSets class. 5 | // See below for the tasks to complete. 6 | // (Please note: You may not edit the primary class definition here.) 7 | class DisjointSets { 8 | public: 9 | // We'll statically allocate space for at most 256 nodes. 10 | // (We could easily make this extensible by using STL containers 11 | // instead of static arrays.) 12 | static constexpr int MAX_NODES = 256; 13 | 14 | // For a given vertex of index i, leader[i] is -1 if that vertex "leads" 15 | // the set, and otherwise, leader[i] is the vertex index that refers back 16 | // to the eventual leader, recursively. (See the function "find_leader".) 17 | // In this problem we'll interpret sets to represent connected components, 18 | // once the sets have been unioned as much as possible. 19 | int leader[MAX_NODES]; 20 | 21 | // For a given vertex of index i, has_cycle[i] should be "true" if that 22 | // vertex is part of a connected component that has a cycle, and otherwise 23 | // "false". (However, this is only required to be accurate for a current 24 | // set leader, so that the function query_cycle can return the correct 25 | // value.) 26 | bool has_cycle[MAX_NODES]; 27 | 28 | // The number of components found. 29 | int num_components; 30 | 31 | DisjointSets() { 32 | // Initialize leaders to -1 33 | for (int i = 0; i < MAX_NODES; i++) leader[i] = -1; 34 | // Initialize cycle detection to false 35 | for (int i = 0; i < MAX_NODES; i++) has_cycle[i] = false; 36 | // The components will need to be counted. 37 | num_components = 0; 38 | } 39 | 40 | // If the leader for vertex i is set to -1, then report vertex i as its 41 | // own leader. Otherwise, keep looking for the leader recursively. 42 | int find_leader(int i) { 43 | if (leader[i] < 0) return i; 44 | else return find_leader(leader[i]); 45 | } 46 | 47 | // query_cycle(i) returns true if vertex i is part of a connected component 48 | // that has a cycle. Otherwise, it returns false. This relies on the 49 | // has_cycle array being maintained correctly for leader vertices. 50 | bool query_cycle(int i) { 51 | int root_i = find_leader(i); 52 | return has_cycle[root_i]; 53 | } 54 | 55 | // Please see the descriptions of the next two functions below. 56 | // (Do not edit these functions here; edit them below.) 57 | void dsunion(int i, int j); 58 | void count_comps(int n); 59 | }; 60 | 61 | // TASK 1: 62 | // dsunion performs disjoint set union. The reported leader of vertex j 63 | // will become the leader of vertex i as well. 64 | // Assuming it is only called once per pair of vertices i and j, 65 | // it can detect when a set is including an edge that completes a cycle. 66 | // This is evident when a vertex is assigned a leader that is the same 67 | // as the one it was already assigned previously. 68 | // Also, if you join two sets where either set already was known to 69 | // have a cycle, then the joined set still has a cycle. 70 | // Modify the implementation of dsunion below to properly adjust the 71 | // has_cycle array so that query_cycle(root_j) accurately reports 72 | // whether the connected component of root_j contains a cycle. 73 | void DisjointSets::dsunion(int i, int j) { 74 | 75 | bool i_had_cycle = query_cycle(i); 76 | bool j_had_cycle = query_cycle(j); 77 | 78 | int root_i = find_leader(i); 79 | int root_j = find_leader(j); 80 | 81 | if (root_i != root_j) { 82 | 83 | //assign j as i's root 84 | leader[root_i] = root_j; 85 | root_i = root_j; 86 | } 87 | else { 88 | // A cycle is detected when dsunion is performed on an edge 89 | // where both vertices already report the same set leader. 90 | 91 | // update cycle property, make disjoint led by j has cycle 92 | has_cycle[ root_j ] = true; 93 | // TODO: Your work here! Update has_cycle accordingly. 94 | } 95 | 96 | // Also, if either one of the original sets was known to have a cycle 97 | // already, then the newly joined set still has a cycle. 98 | // TODO: Your work here! 99 | 100 | if( i_had_cycle || j_had_cycle ) 101 | { 102 | has_cycle[ root_j ] = true; 103 | } 104 | 105 | return; 106 | } 107 | //end of function DisjointSets::dsunion(int i, int j) 108 | 109 | // TASK 2: 110 | // count_comps should count how many connected components there are in 111 | // the graph, and it should set the num_components member variable 112 | // to that value. The input n is the number of vertices in the graph. 113 | // (Remember, the vertices are numbered with indices 0 through n-1.) 114 | void DisjointSets::count_comps(int n) { 115 | 116 | // Insert code here to count the number of connected components 117 | // and store it in the "num_components" member variable. 118 | // Hint: If you've already performed set union on all the apparent edges, 119 | // what information can you get from the leaders now? 120 | // TODO: Your work here! 121 | 122 | int num_of_connect_component = 0; 123 | 124 | for( int i = 0 ; i < n ; i ++ ) 125 | { 126 | if( leader[i] < 0 ) 127 | { 128 | num_of_connect_component++; 129 | } 130 | } 131 | 132 | num_components = num_of_connect_component; 133 | 134 | return; 135 | } 136 | //end of function DisjointSets::count_comps 137 | 138 | 139 | 140 | // expected output of main 141 | 142 | /* 143 | 144 | For edge list: (0,1),(1,2),(3,4),(4,5),(5,6),(6,7),(7,3),(3,5),(4,6) 145 | You counted num_components: 2 146 | Cycle reported for these vertices (if any): 147 | 3 4 5 6 7 148 | 149 | */ 150 | 151 | 152 | int main() { 153 | 154 | constexpr int NUM_EDGES = 9; 155 | constexpr int NUM_VERTS = 8; 156 | 157 | int edges[NUM_EDGES][2] = {{0,1},{1,2},{3,4},{4,5},{5,6},{6,7},{7,3},{3,5},{4,6}}; 158 | 159 | DisjointSets d; 160 | 161 | // The union operations below should also maintain information 162 | // about whether leaders are part of connected components that 163 | // contain cycles. (See TASK 1 above where dsunion is defined.) 164 | for (int i = 0; i < NUM_EDGES; i++) 165 | d.dsunion(edges[i][0],edges[i][1]); 166 | 167 | // The count_comps call below should count the number of components. 168 | // (See TASK 2 above where count_comps is defined.) 169 | d.count_comps(NUM_VERTS); 170 | 171 | std::cout << "For edge list: "; 172 | for (int i = 0; i < NUM_EDGES; i++) { 173 | std::cout << "(" << edges[i][0] << "," 174 | << edges[i][1] << ")" 175 | // This avoids displaying a comma at the end of the list. 176 | << ((i < NUM_EDGES-1) ? "," : "\n"); 177 | } 178 | 179 | std::cout << "You counted num_components: " << d.num_components << std::endl; 180 | 181 | // The output for the above set of edges should be: 182 | // You counted num_components: 2 183 | 184 | std::cout << "Cycle reported for these vertices (if any):" << std::endl; 185 | for (int i=0; i // for std::string 15 | #include // for std::vector 16 | #include 17 | #include 18 | #include // for std::pair 19 | #include // for std::unordered_map 20 | 21 | // For simple test randomization: 22 | // (This is the old way of doing randomization, as it was done in C and in 23 | // earlier C++ versions. C++11 introduced more advanced random number 24 | // generators in the standard library, with better statistical properties, 25 | // but it's beyond the scope of this course.) 26 | #include // for srand(), rand() 27 | #include // for time() 28 | 29 | // We're going to need to specify how to hash a pair of integers, 30 | // because the standard library doesn't support this natively. 31 | // This defines IntPair and IntPairPair, as well as std::hash support. 32 | #include "IntPair2.h" 33 | 34 | // The simple GridGraph class for 2D grid diagrams, where points must have 35 | // integer coordinates, and edges may only connect two points that are one 36 | // space apart. This implements a very simple version of an "adjacency list" 37 | // graph data structure using std::unordered_map. 38 | #include "GridGraph.h" 39 | 40 | // Each PuzzleState represents one current state of the "8 puzzle", a sliding 41 | // tile puzzle which is played on a 3x3 grid containing 8 square tiles (so the 42 | // 9th space is blank), where any tile adjacent to the blank space can slide 43 | // into the blank space. 44 | #include "PuzzleState.h" 45 | 46 | // This function is defined in GraphSearchExercises.cpp 47 | std::list graphBFS(const IntPair& start, const IntPair& goal, const GridGraph& graph); 48 | 49 | // This function is defined in GraphSearchExercises.cpp 50 | std::list puzzleBFS(const PuzzleState& start, const PuzzleState& goal); 51 | 52 | -------------------------------------------------------------------------------- /Course_3_Unorder Data Structures/Week_3_Graph/Week_3_Project_GraphSearch/GridGraph.cpp: -------------------------------------------------------------------------------- 1 | 2 | /** 3 | * @file GridGraph.cpp 4 | * University of Illinois CS 400, MOOC 3, Week 3: Graph Search 5 | * 6 | * @author Eric Huber 7 | * 8 | **/ 9 | 10 | #include "GridGraph.h" 11 | 12 | // Additional definitions for GridGraph 13 | 14 | // ======================================================================== 15 | 16 | // Instantiating static class member variables 17 | 18 | // In the class header file, we declared these static member variables, but 19 | // declaring that they belong to the class didn't create them. These are like 20 | // global variables; a single instance of these variables exists for the 21 | // entire running program. We can't instantiate them in the class header file 22 | // because then we'd get multiple object instances among the various cpp files 23 | // that include our class header, which is a linker error. We also can't use 24 | // namespace tricks (or anything else) to restrict the instance of the variable 25 | // to a single .o file, because we do want all of the generated .o files to 26 | // link with this single, global instance of the variable. We have to 27 | // "instantiate" and initialize these static class members at global scope in 28 | // a cpp file so they can be shared globally. 29 | 30 | // You can also have static const members of a class, and those are easier 31 | // to deal with, since they can just be defined and initialized in the class 32 | // definition itself. For best results with that, use "static constexpr" and 33 | // make sure the initializer is something that can be calculated at compile 34 | // time. 35 | 36 | // ------------------------------------------------------------------------- 37 | 38 | // Instantiating this static class member variable at global scope. 39 | // This works like a global variable throughout the program (in any source 40 | // code file), but technically it's part of the GridGraph class. 41 | // See notes in GridGraph.h. 42 | bool GridGraph::allowPlotting = true; 43 | 44 | // See notes on GridGraph::allowPlotting in GridGraph.h 45 | bool GridGraph::allowVerboseTextDescription = true; 46 | 47 | // ======================================================================== 48 | 49 | // Additional GridGraph member function definitions 50 | 51 | // These were declared in GridGraph.h but we're defining them here separately 52 | // because of their size and complexity. 53 | 54 | // ------------------------------------------------------------------------- 55 | 56 | // Allow a GridGraph to be plotted graphically in the terminal. 57 | // For more accessible printouts, use printDetails instead. 58 | std::ostream& GridGraph::plot(std::ostream& os) const { 59 | 60 | // If plotting is deactivated, do nothing. 61 | if (!GridGraph::allowPlotting) return os; 62 | 63 | if (adjacencyMap.empty()) { 64 | return os << "[Empty graph plot]" << std::endl; 65 | } 66 | 67 | // For printing, we'll assume (0,0) is the upper left of the plot, 68 | // the first coordinate increases as we go lower, 69 | // and the second coordinate increases as we go to the right. 70 | 71 | // Identify the min and max row and col in use by any point (or 0 for an empty graph). 72 | int minRow = 0; 73 | int minCol = 0; 74 | int maxRow = 0; 75 | int maxCol = 0; 76 | if (adjacencyMap.size() > 0) { 77 | // begin() returns an iterator. We use "->" as if it were a pointer. 78 | auto firstPointKey = adjacencyMap.begin()->first; 79 | maxRow = minRow = firstPointKey.first; 80 | maxCol = minCol = firstPointKey.second; 81 | // Loop over all the key-value pairs in the adjacency map. 82 | for (const auto& kv : adjacencyMap) { 83 | const auto& pointKey = kv.first; 84 | auto pointRow = pointKey.first; 85 | auto pointCol = pointKey.second; 86 | minRow = std::min(minRow, pointRow); 87 | minCol = std::min(minCol, pointCol); 88 | maxRow = std::max(maxRow, pointRow); 89 | maxCol = std::max(maxCol, pointCol); 90 | } 91 | } 92 | 93 | // We will plot the GridGraph starting from minRow, where minCol will be 94 | // on the left side of the terminal output. (This part is a bit complicated.) 95 | for (int row = minRow; row <= maxRow; row++) { 96 | // A string stream lets us do stream operations with "<<" to prepare a string. 97 | // We'll do this to prepare the decorations in the line below the current line 98 | // we are printing. 99 | std::stringstream understream; 100 | for (int col = minCol; col <= maxCol; col++) { 101 | // pos is the position at {row,col} in the grid, which may not actually 102 | // be a point in the graph 103 | IntPair pos = {row, col}; 104 | // If this point is in the graph, put a point marker. 105 | if (hasPoint(pos)) { 106 | // Output the point (expected to be padded to 7 characters): " (1,2) ", "(12,34)" 107 | os << pos; 108 | } 109 | // If the point isn't in the graph, put padding spaces. 110 | else { 111 | os << " "; 112 | } 113 | // posRight is the position to the right 114 | IntPair posRight = {row, col+1}; 115 | // If there's an edge to the right, print a horizontal line 116 | if (hasEdge(pos,posRight)) { 117 | os << "----"; 118 | } 119 | // If there's no edge to the right, and this isn't the rightmost column, 120 | // then put padding spaces 121 | else if (col < maxCol) { 122 | os << " "; 123 | } 124 | // We'll prepare the understream if this isn't the bottom row. 125 | if (row < maxRow) { 126 | // pos_down is the position below the current position 127 | IntPair posDown = {row+1, col}; 128 | // If there's an edge beneath this point, then draw a vertical line 129 | if (hasEdge(pos,posDown)) { 130 | understream << " | "; 131 | } 132 | // If there's no edge below, just draw spaces. 133 | else { 134 | understream << " "; 135 | } 136 | // If it's not the rightmost column, then we need to put padding 137 | // spaces to the right for the understream also 138 | if (col < maxCol) { 139 | understream << " "; 140 | } 141 | } 142 | } 143 | 144 | // We're done processing this row, so cap this line of os with an endline 145 | os << std::endl; 146 | 147 | // If it's the last row, we're leaving understream blank. 148 | // Otherwise, cap understream with an endline too. 149 | if (row < maxRow) understream << std::endl; 150 | 151 | // Now dump the contents of the understream to os, twice. 152 | os << understream.str() << understream.str(); 153 | } 154 | 155 | return os; 156 | } 157 | 158 | // Print a list of the internal contents of a GridGraph structure in an accessible way. 159 | std::ostream& GridGraph::printDetails(std::ostream& os) const { 160 | 161 | if (adjacencyMap.empty()) { 162 | return os << "The graph is empty." << std::endl; 163 | } 164 | 165 | if (!allowVerboseTextDescription) { 166 | return os << "Omitting verbose text description of graph." << std::endl; 167 | } 168 | 169 | // Please see the definition of plotGraph for more information on how 170 | // this function works, as they are similar. 171 | 172 | std::unordered_set edgeSet; 173 | std::unordered_set isolatedPointSet; 174 | 175 | // Loop over key-value pairs 176 | for (const auto& kv : adjacencyMap) { 177 | // key: point 178 | const auto& p1 = kv.first; 179 | // value: neighbor point set 180 | const auto& p1_neighbors = kv.second; 181 | 182 | // Points that have no adjacencies are isolated points, with no incident edges. 183 | if (p1_neighbors.empty()) { 184 | isolatedPointSet.insert(p1); 185 | } 186 | // Otherwise, insert all the edges found into the set of edges. 187 | // std::unordered_set only stores one element per key inserted, 188 | // so inserting the same key multiple times does nothing. You could 189 | // count the number of unique edges this way. Since we're interpreting 190 | // IntPairPair (a pair of IntPair) as an undirected edge here, we need 191 | // to be careful to ensure unique representation: For any points A and B, 192 | // the edge (A,B) is the same as the edge (B,A). To keep an edge key 193 | // consistent regardless of which direction it is viewed from, an ordering 194 | // is imposed on the endpoints using the "<" operator. Note that we can 195 | // compare two IntPair with "<" because STL gives us an implementation 196 | // of "<" for std::pair by default. 197 | else { 198 | for (const auto& p2 : p1_neighbors) { 199 | IntPairPair edge; 200 | if (p1 < p2) { 201 | edge = std::make_pair(p1,p2); 202 | } 203 | else { 204 | // If the edge key looks "backwards," then flip it for uniformity. 205 | // That is, the same undirected edge (A,B) and (B,A) will always be 206 | // recorded as (A,B). 207 | edge = std::make_pair(p2,p1); 208 | } 209 | edgeSet.insert(edge); 210 | } 211 | } 212 | } 213 | 214 | // You can initialize a vector with an unordered set's contents 215 | // if you use this constructor that takes begin and end iterators. 216 | std::vector edgeVec(edgeSet.begin(), edgeSet.end()); 217 | std::vector isolatedPointVec(isolatedPointSet.begin(), isolatedPointSet.end()); 218 | 219 | // We'll sort these just for appearance. 220 | // Temporarily make a sorted array of the point coordinates using 221 | // std::vector and std::sort. This works because IntPair is defined 222 | // as a std::pair and it already has ordering relationships defined 223 | // by how the operator "<" is defined for the std::pair template: 224 | // The first coordinate is compared, and if equal, then the second 225 | // is compared. 226 | // e.g., (2,7) < (7,2) and (2,7) < (2,9) 227 | 228 | std::sort(edgeVec.begin(), edgeVec.end()); 229 | std::sort(isolatedPointVec.begin(), isolatedPointVec.end()); 230 | 231 | os << "Edges: "; 232 | if (edgeVec.empty()) os << "None." << std::endl; 233 | else { 234 | for (IntPairPair edge : edgeVec) { 235 | auto p1 = edge.first; 236 | auto p2 = edge.second; 237 | os << "[(" << p1.first << "," << p1.second << ") to (" << p2.first << "," << p2.second << ")] "; 238 | } 239 | os << std::endl; 240 | } 241 | 242 | os << "Isolated points: "; 243 | if (isolatedPointVec.empty()) os << "None." << std::endl; 244 | else { 245 | for (IntPair p : isolatedPointVec) { 246 | os << p << " "; 247 | } 248 | os << std::endl; 249 | } 250 | 251 | return os; 252 | } 253 | 254 | 255 | -------------------------------------------------------------------------------- /Course_3_Unorder Data Structures/Week_3_Graph/Week_3_Project_GraphSearch/GridGraph.h: -------------------------------------------------------------------------------- 1 | 2 | /** 3 | * @file GridGraph.h 4 | * University of Illinois CS 400, MOOC 3, Week 3: Graph Search 5 | * 6 | * @author Eric Huber 7 | * 8 | **/ 9 | 10 | #pragma once 11 | 12 | #include 13 | #include 14 | #include 15 | #include 16 | #include // for std::sort 17 | #include 18 | #include 19 | #include // for std::stringstream 20 | 21 | #include "IntPair2.h" // for IntPair and point printing support 22 | 23 | // This implements a very simple version of an adjacency list graph, 24 | // where each vertex must be a point with 2D integer coordinates. 25 | // For simplicity, we'll assume points are in (row, column) format, 26 | // and they have integer coordinates between 0 and 99, inclusive. 27 | class GridGraph { 28 | public: 29 | // We use the concept of adjacency lists for our graph implementation. 30 | // However, each vertex's list of adjacent vertices will actually be a set. 31 | // For convenience, we make a type alias for a set of coordinate pairs. 32 | using NeighborSet = std::unordered_set; 33 | 34 | // adjacencyMap records both the vertices and (implicitly) the edges. 35 | // The keys are of type IntPair, which we mean to be grid point coordinates. 36 | // Each key entry in the map represents a vertex that exists in the graph. 37 | // The values are of type NeighborSet. Thus, each key is associated with a set of 38 | // coordinates that are the adjacent points (those connected by an edge). 39 | std::unordered_map adjacencyMap; 40 | 41 | // For better accessibility with screen readers, you can set this to false 42 | // here to prevent GridGraph plotting diagrams from being displayed 43 | // verbosely in the terminal. This class member variable is "static"; the 44 | // static keyword in C++ can mean several different things, but in this 45 | // case, that means it's shared among all instances of the class, and 46 | // referred to globally as GridGraph::allowPlotting. We initialize this 47 | // setting as true in GridGraph.cpp. You can override this in your main 48 | // program like this: 49 | // GridGraph::allowPlotting = false; 50 | // We've already mentioned a place in informalTests(), in main.cpp, where it 51 | // would be possible to do that. 52 | static bool allowPlotting; 53 | 54 | // See the discussion of allowPlotting above. When plotting is not allowed, 55 | // verbose text output will be used instead. This can be set to false in your 56 | // main program setup to also prevent that output, in case there are very 57 | // many edges and points to list. 58 | static bool allowVerboseTextDescription; 59 | 60 | // This sanity check ensures that we are defining a valid graph, since 61 | // we only want edges to join points that are exactly 1 unit apart. 62 | bool checkUnitDistance(const IntPair& p1, const IntPair& p2) const { 63 | int dist_x = p1.first - p2.first; 64 | int dist_y = p1.second - p2.second; 65 | // Compute the squared Euclidean distance. 66 | int dist2 = dist_x*dist_x + dist_y*dist_y; 67 | // We require the squared distance to be 1. 68 | // (No need to take the square root, because 1*1 == 1. It's very good 69 | // that we can do this entirely with integer arithmetic, too.) 70 | return (dist2 == 1); 71 | } 72 | 73 | // Insert an isolated point to the graph (if it doesn't already exist). 74 | // If the point already exists, this basically does nothing. 75 | void insertPoint(const IntPair& p) { 76 | // Just by referring to given key with [], it is inserted to the 77 | // unordered_map if not already present. 78 | adjacencyMap[p]; 79 | } 80 | 81 | // Implicitly insert an edge by creating a pair of associated vertices. 82 | // This inserts points p1 and p2 (if they don't already exist), and it 83 | // marks them as adjacent to each other. 84 | void insertEdge(const IntPair& p1, const IntPair& p2) { 85 | 86 | if (!checkUnitDistance(p1, p2)) { 87 | std::cerr << "Error: Can't add edge from " << p1 << " to " << p2 << std::endl; 88 | std::cerr << "Points must be 1 unit apart." << std::endl; 89 | throw std::runtime_error("Requested an invalid edge insertion"); 90 | } 91 | 92 | // Ensure that p1 exists in the adjacency map, 93 | // and mark p2 as adjacent in its own adjacency set. 94 | adjacencyMap[p1].insert(p2); 95 | 96 | // To clarify about the syntax: 97 | // adjacencyMap[p1] creates an entry with key p1 in the map if necessary, 98 | // or otherwise it looks up the existing one, and then it returns a 99 | // reference to p1's associated NeighborSet. (If it was just created now by 100 | // this usage of [], then that set will be empty.) 101 | // Then, .insert(p2) calls the NeighborSet's insert() function to insert p2. 102 | 103 | // Now, do the same for p2 with respect to p1. 104 | adjacencyMap[p2].insert(p1); 105 | } 106 | 107 | // If the edge exists, remove it by having both points mark each other 108 | // as not adjacent. 109 | void removeEdge(const IntPair& p1, const IntPair& p2) { 110 | if (hasEdge(p1,p2)) { 111 | adjacencyMap[p1].erase(p2); 112 | adjacencyMap[p2].erase(p1); 113 | } 114 | } 115 | 116 | // Remove the point from the graph, if it exists, after removing all 117 | // the edges that connected to it. 118 | // (To be defined in GraphSearchExercises.cpp) 119 | void removePoint(const IntPair& p1); 120 | 121 | // Report whether the graph contains this point. 122 | bool hasPoint(const IntPair& p) const { 123 | return adjacencyMap.count(p); 124 | } 125 | 126 | // Can be used for convenience to see if two points are adjacent. 127 | bool hasEdge(const IntPair& p1, const IntPair& p2) const { 128 | 129 | // We'll check if the points are adjacent (i.e., there is an edge) 130 | // but we'll also do a sanity check in the process, to make sure 131 | // the graph setup doesn't have an inconsistency. 132 | int directions = 0; 133 | 134 | // "Short circuiting" in C++ ensures that if the first boolean 135 | // is false here, then the second one after "&&" will not be 136 | // evaluated. That's important because otherwise, the .at() call 137 | // could throw an exception we don't want. 138 | if (adjacencyMap.count(p1) && adjacencyMap.at(p1).count(p2)) { 139 | // If p1 is a point in the graph, and if it's marked adjacent to p2, 140 | // then we've seen one "direction" for this edge. An undirected 141 | // graph should not have unidirectional edges, so both endpoints 142 | // should be marked adjacent to each other if everything has been 143 | // set up correctly. 144 | directions++; 145 | } 146 | 147 | if (adjacencyMap.count(p2) && adjacencyMap.at(p2).count(p1)) { 148 | directions++; 149 | } 150 | 151 | if (directions == 0) { 152 | return false; 153 | } 154 | else if (directions == 2) { 155 | return true; 156 | } 157 | else { 158 | // This means one endpoint refers to the other, but not the other way 159 | // around. Both ends should be recorded as adjacent to each other. 160 | // Most likely this means there is either a bug in insertEdge, 161 | // or the programmer tried to insert an edge manually and made a mistake, 162 | // or an endpoint was deleted but maintenance was not performed on its 163 | // neighboring points' adjacency lists. 164 | throw std::runtime_error("hasEdge: edge found, but only in one direction"); 165 | } 166 | } 167 | 168 | // Returns the number of vertices in the GridGraph currently. 169 | int countVertices() const { 170 | // Each key in the adjacencyMap represents one point in the graph, 171 | // so we just return the size of the std::unordered_map, which is 172 | // the number of keys it has. 173 | return adjacencyMap.size(); 174 | } 175 | 176 | // Returns the number of edges in the GridGraph. 177 | // You'll implement this yourself in an exercise. 178 | int countEdges() const; 179 | 180 | // Check for equality between two GridGraph objects by comparing their 181 | // adjacency maps directly 182 | bool operator==(const GridGraph& other) const { 183 | return (adjacencyMap == other.adjacencyMap); 184 | } 185 | 186 | // Check for inequality of two GridGraph objects by delegating to the 187 | // implementation of operator==. Remember that "this" is a pointer to the 188 | // current instance of the class, so "*this" is the current GridGraph itself. 189 | bool operator!=(const GridGraph& other) const { 190 | return !(*this == other); 191 | } 192 | 193 | // Plot a GridGraph diagram in the terminal, graphically. 194 | // For more accessible printouts, use printDetails instead. 195 | // (The function body is defined in GridGraph.cpp) 196 | std::ostream& plot(std::ostream& os) const; 197 | 198 | // Print a list of the internal contents of a GridGraph structure in an accessible way. 199 | // (The function body is defined in GridGraph.cpp) 200 | std::ostream& printDetails(std::ostream& os) const; 201 | 202 | // Let the constructors and destructor just be the defaults! 203 | // Note that since all of the class's data is contained in STL 204 | // data structure types (unordered_map, unordered_set, pair), 205 | // these will use the appropriate memory management and destructors 206 | // that have already been defined for them by the standard library. 207 | 208 | }; 209 | 210 | // Some of the member function bodies are defined in GridGraph.cpp, so please look there too. 211 | 212 | // Adds << support for plotting a GridGraph. 213 | static inline std::ostream& operator<<(std::ostream& os, const GridGraph& graph) { 214 | if (GridGraph::allowPlotting) { 215 | return graph.plot(os); 216 | } 217 | else { 218 | return graph.printDetails(os); 219 | } 220 | } 221 | -------------------------------------------------------------------------------- /Course_3_Unorder Data Structures/Week_3_Graph/Week_3_Project_GraphSearch/IntPair2.h: -------------------------------------------------------------------------------- 1 | 2 | /** 3 | * @file IntPair2.h 4 | * University of Illinois CS 400, MOOC 3, Week 3: Graph Search 5 | * 6 | * @author Eric Huber 7 | * 8 | **/ 9 | 10 | // This file has more content than the IntPair.h that was originally released 11 | // with the Week 1 assignment, Unordered Map. It includes operator<< support 12 | // for IntPair, as well as a definition of IntPairPair (with hashing support). 13 | 14 | #pragma once 15 | 16 | #include // for std::hash 17 | #include // for std::pair 18 | #include // for std::string 19 | #include // for std:ostream 20 | 21 | // We don't have to define an entire IntPair class ourselves since 22 | // C++ provides a templated pair type already. 23 | // We define IntPair as a type alias for convenience. 24 | using IntPair = std::pair; 25 | 26 | // In the C++ standard library, classes like std::unordered_map and 27 | // std::unordered_set use the default hashing object std::hash internally. 28 | // However, std::hash doesn't natively support all possible types, 29 | // just a few of the primitive C++ types like int and std::string. 30 | // For more specific types, such as std::pair, or for custom 31 | // classes you make yourself, you need to specify a hashing function. 32 | // Since std::hash is templated, we can add new cases for it using 33 | // what is called "template specialization". 34 | 35 | // In addition, custom class types made by users will also need to define 36 | // their equivalence relation function, operator==, for this to work. 37 | // Fortunately, std::pair already gives us that automatically. 38 | 39 | // ------------------------------------------------------------------ 40 | 41 | // Reference: https://en.cppreference.com/w/cpp/utility/hash 42 | 43 | // We're adding more content to the standard namespace. 44 | // (This isn't normally something you should do casually.) 45 | namespace std { 46 | 47 | // A minor detail: std::hash is a struct, not a class. 48 | // In C++, a struct is very similar to a class, but it has public 49 | // members by default. 50 | 51 | // The "template <>" syntax indicates that we are specializing an existing 52 | // template for std::hash. 53 | 54 | template <> 55 | struct hash { 56 | 57 | // By overriding the () "operator", we can make an instance of a class 58 | // respond to similar syntax as if it were merely a function name. 59 | // The std::hash type is intended to work this way, as a "function object". 60 | // See also: https://en.cppreference.com/w/cpp/utility/functional 61 | 62 | // The () operator definition is where we will essentially define 63 | // our custom hashing function, and it returns the actual hash 64 | // as a std::size_t value (which is an integral type). 65 | std::size_t operator() (const IntPair& p) const { 66 | 67 | // We know that std::string has a well-defined hasher already, 68 | // so we'll turn our pair of ints into a unique string representation, 69 | // and then just hash that. We'll turn each integer into a string 70 | // and concatenate them with "##" in the middle, which should make 71 | // a unique string for any given pair of ints. 72 | std::string uniqueIntPairString = std::to_string(p.first) + "##" + std::to_string(p.second); 73 | 74 | // Get the default hashing function object for a std::string. 75 | std::hash stringHasher; 76 | // Use the string hasher on our unique string. 77 | return stringHasher(uniqueIntPairString); 78 | } 79 | }; 80 | 81 | } 82 | 83 | // Allow IntPair to be printed using std::cout << ... 84 | static inline std::ostream& operator<<(std::ostream& os, const IntPair& point) { 85 | // For simplicity, we'll insert padding spaces according to the assumption 86 | // that point coordinates are only one or two digits each, and that they 87 | // are nonnegative. That is, they are between 0 and 99, inclusive. 88 | // Examples: " (2,3) " and " (4,56)". 89 | // THe padding space is necessary to make sure the grid lines leading 90 | // to and from the vertex stay aligned. 91 | if (point.first < 10 && point.first >= 0) os << " "; // optional padding space 92 | os << "("; 93 | os << point.first; 94 | os << ","; 95 | os << point.second; 96 | os << ")"; 97 | if (point.second < 10 && point.second >= 0) os << " "; // optional padding space 98 | return os; 99 | } 100 | 101 | // Here we do the same hashing trick again for a pair of IntPair. 102 | // In a few cases this could be useful for making a set of edges. 103 | // However, with adjacency lists, we don't usually need to explicitly 104 | // create a set of edges. 105 | using IntPairPair = std::pair; 106 | 107 | namespace std { 108 | 109 | template <> 110 | struct hash { 111 | 112 | std::size_t operator() (const IntPairPair& twoPairs) const { 113 | auto p1 = twoPairs.first; 114 | auto p2 = twoPairs.second; 115 | std::string uniqueString; 116 | 117 | // Note that this hashing scheme does NOT reorder the pair of pairs 118 | // to ensure that (A,B) and (B,A) hash to the same bucket, although 119 | // that may be desirable for some use cases. 120 | // For example, we use IntPairPair to represent an undirected GridGraph 121 | // edge in this project, but there are certain lines of code in GridGraph.h 122 | // that manually ensure that ((1,2),(2,2)) and ((2,2),(1,2)) will be 123 | // considered equal when inserting to std::unordered_set. 124 | // We could take this further by making a new derived class based on 125 | // IntPairPair, explicitly intended for representing undirected edges only, 126 | // and then defining new equivalence operators and hashing support for it. 127 | // But this time, we will just let IntPairPair be generic, and manually 128 | // take care of the edge flipping in GridGraph.h. 129 | uniqueString = 130 | std::to_string(p1.first) + "##" + std::to_string(p1.second) 131 | + "##" 132 | + std::to_string(p2.first) + "##" + std::to_string(p2.second); 133 | 134 | // Get the default hashing function object for a std::string. 135 | std::hash stringHasher; 136 | // Use the string hasher on our unique string. 137 | return stringHasher(uniqueString); 138 | } 139 | }; 140 | 141 | } 142 | 143 | // Allow IntPairPair to be printed using std::cout << ... 144 | static inline std::ostream& operator<<(std::ostream& os, const IntPairPair& points) { 145 | os << "("; 146 | os << points.first; 147 | os << ","; 148 | os << points.second; 149 | os << ")"; 150 | return os; 151 | } 152 | -------------------------------------------------------------------------------- /Course_3_Unorder Data Structures/Week_3_Graph/Week_3_Project_GraphSearch/Makefile: -------------------------------------------------------------------------------- 1 | # Executable names: 2 | EXE = main 3 | TEST = test 4 | 5 | # Add all object files needed for compiling: 6 | EXE_OBJ = main.o 7 | OBJS = main.o 8 | 9 | # Generated files 10 | # (none) 11 | 12 | # Include the master templated makefile: 13 | include uiuc/make/uiuc.mk 14 | -------------------------------------------------------------------------------- /Course_3_Unorder Data Structures/Week_3_Graph/Week_3_Project_GraphSearch/PuzzleState.cpp: -------------------------------------------------------------------------------- 1 | 2 | /** 3 | * @file PuzzleState.cpp 4 | * University of Illinois CS 400, MOOC 3, Week 3: Graph Search 5 | * 6 | * @author Eric Huber 7 | * 8 | **/ 9 | 10 | #include "PuzzleState.h" 11 | 12 | // There are some notes in GridGraph.cpp about what it means to instantiate 13 | // a static class member variable. 14 | 15 | // Instantiating this static class member variable at global scope. 16 | // This works like a global variable throughout the program (in any source 17 | // code file), but technically it's part of the PuzzleState class. 18 | // See notes in PuzzleState.h. 19 | bool PuzzleState::allowPlotting = true; 20 | 21 | -------------------------------------------------------------------------------- /Course_3_Unorder Data Structures/Week_3_Graph/Week_3_Project_GraphSearch/uiuc/catch/catchmain.cpp: -------------------------------------------------------------------------------- 1 | #define CATCH_CONFIG_MAIN 2 | #include "catch.hpp" 3 | -------------------------------------------------------------------------------- /Course_3_Unorder Data Structures/Week_3_Graph/Week_3_Project_GraphSearch/uiuc/make/uiuc.mk: -------------------------------------------------------------------------------- 1 | 2 | # University of Illinois 3 | # CS 400 - MOOC 3 - Week 3 - Graph Search 4 | 5 | # Original Makefile created by Wade Fagen-Ulmschneider 6 | # Modified for CS 400 by Eric Huber 7 | 8 | ZIP_FILE = graph_search_submission.zip 9 | COLLECTED_FILES = GraphSearchExercises.cpp 10 | 11 | # Add standard object files (HSLAPixel, PNG, and LodePNG) 12 | OBJS += GraphSearchExercises.o PuzzleState.o GridGraph.o 13 | 14 | # Use ./.objs to store all .o file (keeping the directory clean) 15 | OBJS_DIR = .objs 16 | 17 | # Use all .cpp files in /tests/ 18 | OBJS_TEST = $(filter-out $(EXE_OBJ), $(OBJS)) 19 | CPP_TEST = $(wildcard tests/*.cpp) 20 | CPP_TEST += uiuc/catch/catchmain.cpp 21 | OBJS_TEST += $(CPP_TEST:.cpp=.o) 22 | 23 | # Config 24 | CXX_CLANG = clang++ 25 | CXX_GCC = g++ 26 | CXX_WHICH = $(CXX_GCC) 27 | CXX = $(CXX_WHICH) 28 | LD = $(CXX_WHICH) 29 | # STDVERSION = -std=c++1y # deprecated nomenclature 30 | STDVERSION = -std=c++14 # proper but requires newer compiler versions (for better or worse) 31 | STDLIBVERSION_CLANG = -stdlib=libc++ # Clang's version; not present on default AWS Cloud9 instance 32 | STDLIBVERSION_GCC = # blank on purpose; default GNU library 33 | ifeq ($(CXX_WHICH),$(CXX_CLANG)) 34 | STDLIBVERSION = $(STDLIBVERSION_CLANG) 35 | else 36 | STDLIBVERSION = $(STDLIBVERSION_GCC) 37 | endif 38 | WARNINGS = -pedantic -Wall -Wfatal-errors -Wextra -Wno-unused-parameter -Wno-unused-variable 39 | # ASANFLAGS = -fsanitize=address -fno-omit-frame-pointer 40 | # NO_COPY_ELISION = -fno-elide-constructors 41 | CXXFLAGS = $(CS400) $(STDVERSION) $(STDLIBVERSION) -g -O0 $(WARNINGS) -MMD -MP -msse2 -c $(ASANFLAGS) $(NO_COPY_ELISION) 42 | LDFLAGS = $(CS400) $(STDVERSION) $(STDLIBVERSION) -lpthread $(ASANFLAGS) $(NO_COPY_ELISION) 43 | 44 | ifneq ($(strip $(ASANFLAGS)),) 45 | # This is displayed if ASANFLAGS is not blank. 46 | ASANWARNING = "\n >>>>>>>>>> Note: ASAN is in use. May not be supported on Cloud9. <<<<<<<<<<" 47 | endif 48 | 49 | # Rules for first executable 50 | $(EXE): 51 | $(LD) $^ $(LDFLAGS) -o $@ 52 | @echo 53 | @echo " Built the main executable program file for the project: " $(EXE) 54 | @echo " (Make sure you try \"make test\" too!)" 55 | @echo $(ASANWARNING) 56 | 57 | # Rule for `all` 58 | all: $(EXE) $(TEST) 59 | 60 | # Pattern rules for object files 61 | $(OBJS_DIR): 62 | @mkdir -p $(OBJS_DIR) 63 | @mkdir -p $(OBJS_DIR)/uiuc 64 | @mkdir -p $(OBJS_DIR)/uiuc/catch 65 | @mkdir -p $(OBJS_DIR)/tests 66 | 67 | $(OBJS_DIR)/%.o: %.cpp | $(OBJS_DIR) 68 | $(CXX) $(CXXFLAGS) $< -o $@ 69 | 70 | # Rules for executables 71 | $(TEST): 72 | $(LD) $^ $(LDFLAGS) -o $@ 73 | @echo 74 | @echo " Built the test suite program: " $(TEST) 75 | @echo $(ASANWARNING) 76 | 77 | # Executable dependencies 78 | $(EXE): $(patsubst %.o, $(OBJS_DIR)/%.o, $(OBJS)) 79 | $(TEST): $(patsubst %.o, $(OBJS_DIR)/%.o, $(OBJS_TEST)) 80 | 81 | # some explicit dependencies for efficient recompilation on this assignment 82 | $(OBJS_DIR)/GraphSearchExercises.o: IntPair2.h GridGraph.h PuzzleState.h GraphSearchCommon.h GraphSearchExercises.cpp 83 | $(OBJS_DIR)/GridGraph.o: GridGraph.cpp GridGraph.h IntPair2.h 84 | $(OBJS_DIR)/PuzzleState.o: PuzzleState.cpp PuzzleState.h 85 | 86 | # Include automatically generated dependencies 87 | -include $(OBJS_DIR)/*.d 88 | -include $(OBJS_DIR)/uiuc/*.d 89 | -include $(OBJS_DIR)/uiuc/catch/*.d 90 | -include $(OBJS_DIR)/tests/*.d 91 | 92 | clean: 93 | rm -rf $(EXE) $(TEST) $(OBJS_DIR) $(CLEAN_RM) 94 | 95 | tidy: clean 96 | rm -rf doc 97 | 98 | zip: 99 | @echo "!!! Preparing submission zip with student code..." 100 | @echo "!!! Make sure you have already tried compiling and testing your code" 101 | @echo "!!! thoroughly before submitting the zip on Coursera!" 102 | @echo "" 103 | @echo "Removing any previous version of zip file..." 104 | rm -rf $(ZIP_FILE) 105 | @echo "Creating new file..." 106 | zip $(ZIP_FILE) $(COLLECTED_FILES) 107 | @echo "Created zip file: " $(ZIP_FILE) 108 | 109 | .PHONY: all tidy clean zip 110 | -------------------------------------------------------------------------------- /Course_3_Unorder Data Structures/Week_3_Graph/Week_3_Project_GraphSearch/version.txt: -------------------------------------------------------------------------------- 1 | 20190531a 2 | 3 | -------------------------------------------------------------------------------- /Course_3_Unorder Data Structures/Week_3_Graph/Week_3_Project_GraphSearch_Description.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/brianchiang-tw/Accelerated_Computer_Science_Fundamentals_Specialization/ff5f477f10e514c46e417a8dab4d4e60100725d5/Course_3_Unorder Data Structures/Week_3_Graph/Week_3_Project_GraphSearch_Description.pdf -------------------------------------------------------------------------------- /Course_3_Unorder Data Structures/Week_3_Graph/Week_3_Project_GraphSearch_full implementation.zip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/brianchiang-tw/Accelerated_Computer_Science_Fundamentals_Specialization/ff5f477f10e514c46e417a8dab4d4e60100725d5/Course_3_Unorder Data Structures/Week_3_Graph/Week_3_Project_GraphSearch_full implementation.zip -------------------------------------------------------------------------------- /Course_3_Unorder Data Structures/Week_3_Graph/Week_3_Project_GraphSearch_starter_files.zip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/brianchiang-tw/Accelerated_Computer_Science_Fundamentals_Specialization/ff5f477f10e514c46e417a8dab4d4e60100725d5/Course_3_Unorder Data Structures/Week_3_Graph/Week_3_Project_GraphSearch_starter_files.zip -------------------------------------------------------------------------------- /Course_3_Unorder Data Structures/Week_3_Graph/Week_3_Project_GraphSearch_submission.zip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/brianchiang-tw/Accelerated_Computer_Science_Fundamentals_Specialization/ff5f477f10e514c46e417a8dab4d4e60100725d5/Course_3_Unorder Data Structures/Week_3_Graph/Week_3_Project_GraphSearch_submission.zip -------------------------------------------------------------------------------- /Course_3_Unorder Data Structures/Week_3_Graph/Week_3_Quiz_and_Reference Manual.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/brianchiang-tw/Accelerated_Computer_Science_Fundamentals_Specialization/ff5f477f10e514c46e417a8dab4d4e60100725d5/Course_3_Unorder Data Structures/Week_3_Graph/Week_3_Quiz_and_Reference Manual.pdf -------------------------------------------------------------------------------- /Course_3_Unorder Data Structures/Week_4_Graph-algorithm/Week4_Challenge_implementation.cpp: -------------------------------------------------------------------------------- 1 | 2 | #include 3 | #include 4 | 5 | // Note: You must not change the definition of DisjointSets here. 6 | class DisjointSets { 7 | public: 8 | int s[256]; 9 | int distance[256]; 10 | 11 | DisjointSets() { 12 | for (int i = 0; i < 256; i++) s[i] = distance[i] = -1; 13 | } 14 | 15 | int find(int i) { return s[i] < 0 ? i : find(s[i]); } 16 | 17 | void dsunion(int i, int j) { 18 | int root_i = find(i); 19 | int root_j = find(j); 20 | if (root_i != root_j) { 21 | s[root_i] = root_j; 22 | } 23 | } 24 | 25 | void bfs(int i, int n, int m, int edges[][2]); 26 | }; 27 | 28 | 29 | /* 30 | * Below are two conditions that need to be programmed 31 | * to allow this procedure to perform a breadth first 32 | * traversal and mark the edge distance of the graph's 33 | * vertices from vertex i. 34 | */ 35 | 36 | void DisjointSets::bfs(int i, int n, int m, int edges[][2]) { 37 | 38 | distance[i] = 0; 39 | 40 | // no need to iterate more than m times 41 | // but loop terminates when no new 42 | // vertices added to the frontier. 43 | 44 | for (int d = 1; d < m; d++) { 45 | 46 | // f is the index of the first 47 | // vertex added to the frontier 48 | int f = -1; 49 | 50 | // rooti is the name of the set 51 | // holding all of the vertices 52 | // that have already been assigned 53 | // distances 54 | 55 | int rooti = find(i); 56 | 57 | // loop through all of the edges 58 | // (this could be much more efficient 59 | // if an adjacency list was used 60 | // instead of a simple edge list) 61 | 62 | for (int j = 0; j < m; j++) { 63 | 64 | // root0 and root1 are the names of 65 | // the sets that the edge's two 66 | // vertices belong to 67 | 68 | int root0 = find(edges[j][0]); 69 | int root1 = find(edges[j][1]); 70 | 71 | if ( root0 == rooti && root1 != rooti) { 72 | 73 | // add the [1] vertex of the edge 74 | // to the frontier, either by 75 | // setting f to that vertex if it 76 | // is the first frontier vertex 77 | // found so far, or by unioning 78 | // it with the f vertex that was 79 | // already found. 80 | 81 | if (f == -1) 82 | f = edges[j][1]; 83 | else 84 | dsunion(f,edges[j][1]); 85 | 86 | // set the distance of this frontier 87 | // vertex to d 88 | 89 | distance[edges[j][1]] = d; 90 | 91 | } else if ( root0 != rooti && root1 == rooti ) { 92 | if (f == -1) 93 | f = edges[j][0]; 94 | else 95 | dsunion(f,edges[j][0]); 96 | distance[edges[j][0]] = d; 97 | } 98 | } 99 | 100 | // if no vertices added to the frontier 101 | // then we have run out of vertices and 102 | // are done, otherwise union the frontier 103 | // set with the set of vertices that have 104 | // already been processed. 105 | 106 | if (f == -1) 107 | break; 108 | else 109 | dsunion(f,i); 110 | } 111 | } 112 | 113 | 114 | // expected output of main: 115 | 116 | /* 117 | 118 | // Distance to vertex 0 is 3 119 | // Distance to vertex 1 is 2 120 | // Distance to vertex 2 is 1 121 | // Distance to vertex 3 is 0 122 | // Distance to vertex 4 is 1 123 | // Distance to vertex 5 is 2 124 | // Distance to vertex 6 is 2 125 | // Distance to vertex 7 is 1 126 | 127 | */ 128 | 129 | 130 | int main() { 131 | 132 | int edges[8][2] = {{0,1},{1,2},{2,3},{3,4},{4,5},{5,6},{6,7},{7,3}}; 133 | 134 | DisjointSets d; 135 | 136 | d.bfs(3,8,8,edges); 137 | 138 | for (int i = 0; i < 8; i++) 139 | std::cout << "Distance to vertex " << i 140 | << " is " << d.distance[i] << std::endl; 141 | 142 | return 0; 143 | } 144 | -------------------------------------------------------------------------------- /Course_3_Unorder Data Structures/Week_4_Graph-algorithm/Week4_Challenge_implementation.exe: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/brianchiang-tw/Accelerated_Computer_Science_Fundamentals_Specialization/ff5f477f10e514c46e417a8dab4d4e60100725d5/Course_3_Unorder Data Structures/Week_4_Graph-algorithm/Week4_Challenge_implementation.exe -------------------------------------------------------------------------------- /Course_3_Unorder Data Structures/Week_4_Graph-algorithm/Week_4_Challenge_and_Reference Solution.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/brianchiang-tw/Accelerated_Computer_Science_Fundamentals_Specialization/ff5f477f10e514c46e417a8dab4d4e60100725d5/Course_3_Unorder Data Structures/Week_4_Graph-algorithm/Week_4_Challenge_and_Reference Solution.pdf -------------------------------------------------------------------------------- /Course_3_Unorder Data Structures/Week_4_Graph-algorithm/Week_4_Quiz_and_Reference Manual.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/brianchiang-tw/Accelerated_Computer_Science_Fundamentals_Specialization/ff5f477f10e514c46e417a8dab4d4e60100725d5/Course_3_Unorder Data Structures/Week_4_Graph-algorithm/Week_4_Quiz_and_Reference Manual.pdf -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2019 Brian Chiang 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ## Accelerated_Computer_Science_Fundamentals_Specialization 2 | A set of practice and demo code of Accelerated Computer Science Fundamentals Specialization on Coursera 3 | 4 | ## Course website: 5 | 6 | https://www.coursera.org/specializations/cs-fundamentals 7 | 8 | ## Course title: 9 | 10 | Accelerated Computer Science Fundamentals Specialization 11 | Data Structures and Algorithms in C++. 12 | 13 | Learn fundamentals of computer science while implementing efficient data structures in C++. 14 | 15 | 16 | 17 | ## Table of content 18 | 19 | # Course_#1 :Object-Oriented Data Structures in Cpp 20 | 21 | 1. Week_1_Orientation_Write_a_cpp_program 22 | * Introduction 23 | * Local development environment, toolchain, and IDE installation 24 | * Cloud development environment configuration 25 | * C++ Standard Library 26 | * C++ Classes 27 | 28 | 2. Week_2_Understanding Cpp memory model 29 | * Variable, pointer, and memory 30 | * Stack 31 | * Heap 32 | * New, delete, and memory management 33 | * Basic control flow 34 | * Header file and source file 35 | * Project: Hello world 36 | 37 | 3. Week_3_Developing Cpp Classes 38 | * Classes 39 | * Constructor / Destructor 40 | * Copy assignment operator 41 | * Variable storage 42 | * Introduction to un-initialized pointer, segmentation Fault, and un-defined behavoir 43 | * Range-based loop 44 | 45 | 4. Week_4_Engineering Cpp software solution 46 | * Recursive with implementation of Tower of Hanoi 47 | * Template type and template classes 48 | * Inheritance 49 | * Project: Image processing 50 | 51 | # Course_#2 :Ordered Data Structures 52 | 53 | 1. Week_1_Orientation_Linear data structures 54 | * Introduction 55 | * Array 56 | * Linked-list 57 | * Time and space complexity analysis of Array and Linked-list 58 | * Operation of Array and Linked-list 59 | * Queue 60 | * Stack 61 | * Project: Linked list and Merge sort 62 | 63 | 2. Week_2_Introduction to Tree structures 64 | * Tree terminology 65 | * Tree Traversal 66 | * Binary Tree 67 | * Binary Search Tree 68 | * Time and space complexity analysis of Tree search operation 69 | 70 | 3. Week_3_Advanced Tree Structures 71 | * Balanced Binary Search Tree 72 | * AVL Tree adn its analysis 73 | * B-Tree introduction 74 | * B-Tree operation: insert and search 75 | * Project: Generic Tree and Tree Traversal 76 | 77 | 4. Week_4_Heap Structures 78 | * Heap introduction 79 | * Heap and priority-queue 80 | * Heap variation: min-heap, max-heap 81 | * Heap operation: insert, extract-min, build heap, heapify adjustment 82 | * Time and space complexity analysis of Heap 83 | 84 | # Course_#3 :Un-ordered Data Structures 85 | 86 | 1. Week_1_Orientation_Hashing 87 | * Hashing introduction 88 | * Hashing function with examples 89 | * Collision handling: separate chaining 90 | * Collision handling: probing and double-hashing 91 | * Time and space complexity analysis of Hashing 92 | * Project: Unordered-map 93 | 94 | 2. Week_2_Disjoint-sets 95 | * Disjoint-sets introduction 96 | * Disjoint-sets teminology 97 | * Naive implementation 98 | * Up-tree, a better implementation 99 | * Smart union & Path-compression 100 | * Time and space complexity analysis of Disjoint-sets 101 | 102 | 3. Week_3_Graph 103 | * Graph introduction 104 | * Week_3_Graph terminology 105 | * Graph representation: edge list 106 | * Graph representation: adjacency matrix 107 | * Graph representation: adjacency list 108 | * Time and space complexity analysis of graph operation 109 | * Project: Graph search 110 | 111 | 4. Week_4_Graph algorithm 112 | * Graph traversal algorithm 113 | * Breadth First Search (i.e., BFS ) Traversal 114 | * Time and space complexity analysis of BFS 115 | * Depth First Search (i.e., DFS) Traversal 116 | * Time and space complexity analysis of DFS 117 | * Minimal spanning tree (i.e., MST ) algorithm 118 | * Kruskal algorithm 119 | * Prim algorithm 120 | * Shortest path algorithm 121 | * Dijkstra algorithm 122 | * Dijkstra algorithm's edge case 123 | * Time and space complexity of Dijkstra algortithm 124 | * Landmark path problem --------------------------------------------------------------------------------