From b51994f16881812478bd9f8d084530a8a8d88c63 Mon Sep 17 00:00:00 2001 From: Xiulan Shi Date: Tue, 12 Jan 2016 17:34:26 -0500 Subject: [PATCH 01/31] Finished HW1-09-16 --- .DS_Store | Bin 0 -> 6148 bytes .../Contents.swift | 82 ++++++++++++++++-- 2 files changed, 77 insertions(+), 5 deletions(-) create mode 100644 .DS_Store diff --git a/.DS_Store b/.DS_Store new file mode 100644 index 0000000000000000000000000000000000000000..81fa06bdc3139749cd57815a44115583f854156a GIT binary patch literal 6148 zcmeHKu}T9$5PcH^CfKC3^BN%*38oS3&X|aSsE`!48iPTIM#LaCav$gi_&4X9oh6u@ zf|W>^fth!=J2SiYcDdOFAnp0M1=IjksEVa3%{QX`ss$;jv ze`G+{ZWpJx#4Voib^RJ#$ph3e#0&1&`-~nQXw_>EZ)oBXQ(WT}lh8J2@3=Re-HfKQ z5wq%+I-%C7lIOI*PGO`L_loWp8>`KcCb(e!-(-Jh#(EwkWZy)eb38^D=bUwSc`h@xTTmguBj10nOJ@{!%5;2XK8M22W7D}{GiB}AkK#p%M5JTYfbBa_vicna*)3{1J1x&F(Bp6u+!!z#oAi)!Q2ZbeXmH~U{3!#U6QfJ1 literal 0 HcmV?d00001 diff --git a/HWfrom1-09-16(SwiftIntro).playground/Contents.swift b/HWfrom1-09-16(SwiftIntro).playground/Contents.swift index 488e9ed..e607a45 100644 --- a/HWfrom1-09-16(SwiftIntro).playground/Contents.swift +++ b/HWfrom1-09-16(SwiftIntro).playground/Contents.swift @@ -10,14 +10,86 @@ Use the link here to get the questions. Then code your solutions below. If it https://docs.google.com/document/d/1DQ2aCJ_yUZtazzCfb0PaS81bg61V2ZOSxpABh981xSo/edit +*/ -1) -2) +//1)Given an integer N, there is a list of size N-1 that is missing one number from 1 - N(inclusive). Find that number. + +func findMissingNumber1(N:Int, list:[Int]) -> Int { + var totalSumOfNArray = 0 + var totalSumOfList = 0 + for i in 1...N { + totalSumOfNArray += i + } + for i in list { + totalSumOfList += i + } + return totalSumOfNArray - totalSumOfList +} + +let arr = [1, 4, 6, 3, 2] +let N = arr.count + 1 + +findMissingNumber1(N, list: arr) + +//2)Given a list of size N containing numbers 1 - N (inclusive). return true if there are duplicates, false if not + +func hasDuplicates(arr4: [Int]) -> Bool { + + for i in 0..(arr) +// let result = Array(mySet) +// if result.count != arr.count { +// return true +// } +// return false +//} + +let arr4 = [1, 2, 3, 5] +hasDuplicates(arr4) + + + +//3)Given two lists, find the smallest value that exists in both lists. + +func smallestCommonNum(list1: [Int], list2: [Int]) -> Int? { + let set1 = Set(list1) + let set2 = Set(list2) + return set1.intersect(set2).minElement() +} + +let list1 = [3, 6, 9] +let list2 = [9, 12, 28] + +smallestCommonNum(list1, list2: list2) + + + +//4)Check to see if an integer is a palindrome don’t use casting +func isPalindrome(var num: Int) -> Bool { + let originalNum = num + var finalNum = 0 + while(num > 0) { + finalNum *= 10 + finalNum += num % 10 + num /= 10 + } + return finalNum == originalNum +} + +let num = 12021 +isPalindrome(num) -3) -4) -*/ From 531b8a70f83cbd5ce66c7ea208ac1cd29cf3ecf8 Mon Sep 17 00:00:00 2001 From: Xiulan Shi Date: Tue, 12 Jan 2016 17:44:41 -0500 Subject: [PATCH 02/31] Added questions --- .DS_Store | Bin 6148 -> 6148 bytes .../Contents.swift | 87 ++++++++++++++++-- 2 files changed, 80 insertions(+), 7 deletions(-) diff --git a/.DS_Store b/.DS_Store index 81fa06bdc3139749cd57815a44115583f854156a..260e031dd29b9a2871f2599b9e9116d49dce6626 100644 GIT binary patch delta 242 zcmZoMXfc=|#>B!ku~2NHo+2an#(>?7ivyUMSh*P(7*r+;Fd0u?%p@w3lWrKCoS$0& z6a)g*??3_}nVaw8l2Tfd%)oGIw*fy`1+rucPDz1+3}j;y7$);Dot|9DWG{efpHb%I zGA1WJWP6MpCYLa|@S_?~F!?gmxy|ex{2V|ZZFXe-&ODi4#F2xMfq@C+s?8B1YnTBr C*E>`I delta 70 zcmZoMXfc=|#>B)qu~2NHo+2a5#(>?7j4YFDSWi#3Wk0o9frFi8Vnh69b`E|HpsLM+ Y9N(EI^NTogFaQA~0|U$E2$40+0HU}NF8}}l diff --git a/HWfrom1-10-016(BigO).playground/Contents.swift b/HWfrom1-10-016(BigO).playground/Contents.swift index 2040d38..c17d31d 100644 --- a/HWfrom1-10-016(BigO).playground/Contents.swift +++ b/HWfrom1-10-016(BigO).playground/Contents.swift @@ -10,21 +10,94 @@ Use the link here to get the questions. Then code your solutions below. If it https://docs.google.com/document/d/1aF1imJUVahCSJAuN1OEm5lQXwpSFaAmVmAETKMM6PLQ/edit#heading=h.za36ai6n5fth +*/ + +/*1)With my new top of the line XJ452 supercomputer, memory access takes 1 picosecond, math operations take 3 picoseconds, and storing data in memory takes 10 picoseconds. My friend wrote a filter that makes a pixel more awesome, and takes 200 picoseconds to run. +a) How long would my computer take to execute the following code if the input image is 1000px wide by 2000px tall? What if it’s n by m? + + +Pixel **awesomeFilter(Pixel image[][], int width, int height) { + for (int i = 0; i < width; i++) { + for (int j = 0; j < height; j++) { + [image[i][j] makeMoreAwesome]; + } + } + return image; +} + + +b) What is the time complexity of this method, expressed in big O notation? Assume the image is square, and both dimensions are ‘n’. + +c) My friend sends me an improved version of his algorithm, makeEvenMoreAwesome, that takes into account the pixels around the image. He says it’s O(n2) in the amount of pixels in the image. What is the new time complexity of the method? +*/ + +/*2)If foo(xs) is a function with time complexity n (where n is the size of the input array), and bar(xs) is a function with time complexity n2, what is the time complexity of each of the following snippets of code or algorithms? + + +a) for (int i = 0; i < n; i++) { + for (int j = 0; j < n; j++) { + foo(xs); + } +} +for (int i = 0; i < n; i++) { + for (int j = 0; j < n; j++) { + bar(xs); + } +} +for (int i = 0; i < n; i++) { + for (int j = 0; j < n; j++) { + // do cool stuff + } +} + + +b) int frobnicate(ys, m) { + if (m == 0) { + return 0; + } + return ys[m] + frobnicate(ys, m - 1); +} +frobnicate(xs, n); + +Tip: Write down a table with n from 0 to 5 and trace through to find out how many times frobnicate is called with each value of n. + + +c) An algorithm that takes as its input a list of friends of length n, filters out duplicates using a method similar to our hasDuplicates method, sorts the list using merge sort (see bigocheatsheet.com), then prints each item to the screen. -1) -2) +d) An algorithm that searches the now-sorted list of friends for a specific friend (not including the time it takes to sort). +*/ + +/*3)Look at the complexities for some common data structures at bigocheatsheet.com. Pick a good data structure for each of the following scenarios (there are sometimes multiple answers): + + +a) You get a large dataset of points of interest from an API when your app first runs. You build it once at the beginning, and then have to search it many times while the user pans around a map. + + +b) You get a small dataset of points of interest from an API every time the user pans the map. You construct the data set many times and only render it once, then you discard it and do another API search. + +Tip: Constructing a dataset of size n means you have to call the data structure’s insert method n times. So if the data structure has an insert method that takes O(n2), the time to build it all from scratch is O(n3). + -3) +c) You used a linked list for your music app’s playlist feature, but now when people search their playlist, there’s a noticeable lag before loading results. Your competitor’s app is buttery smooth when searching, even showing results as you type. What data structure would allow you to more quickly search without compromising too much on the speed of inserting and deleting tracks, even in the worst case? -4) +*/ + +/*4)Write an algorithm using one of the methods from exercise 1 (your choice) to calculate the factorial of a number n. What is the time complexity of your method in terms of the input value? +*/ + +/*5)Write an Objective C or Swift function to multiply two numbers without using the * operator. Use the grade school method of multiplying by doing repeated addition. For instance, 5 * 8 = 5 + 5 + 5 + 5 + 5 + 5 + 5 + 5 = 40. Find the big O of your function in terms of n and m (the two operands). +*/ -5) +/*6)Look up Russian Peasant Multiplication. It’s a faster way to multiply numbers, especially on a binary computer (like yours!). Implement a new multiplication function using this technique and find the big O of your method. If you have trouble with implementing this, write a flow chart and find the big O based on that. (But it’s more satisfying to implement it and run it) -6) +Tip: Run through the method by hand a few times to see how it works and verify to yourself that it does. It’s a non-intuitive algorithm. This will hopefully also make the time complexity more clear. -7) +*/ +/*7)Using the technique from exercise 4, profile the built in sorting method in objective C (use an NSMutableArray and google how to sort an array of numbers in objective C). Graph the result. Use spreadsheet formulas to add graph lines for n, n2, and n*log(n). (You’ll have to modify the factors to make them fit in the graph window and to be close to the graph of method execution time). Show that the sort method best fits n * log(n). */ + + From 1b43c879f5f181e11a6f8b9f0b561d413378d452 Mon Sep 17 00:00:00 2001 From: Xiulan Shi Date: Tue, 12 Jan 2016 18:18:26 -0500 Subject: [PATCH 03/31] Updated --- .DS_Store | Bin 6148 -> 8196 bytes .../Contents.swift | 18 ++++++++++++++---- 2 files changed, 14 insertions(+), 4 deletions(-) diff --git a/.DS_Store b/.DS_Store index 260e031dd29b9a2871f2599b9e9116d49dce6626..2981a46531803d1c41121e8edfacd19d2c222a47 100644 GIT binary patch delta 352 zcmZoMXmOBWU|?W$DortDU;r^WfEYvza8E20o2aMA$h$FMH}hr%jz7$c**Q2SHn1@A zPF7&`*&M-gfpKyK3m=owoXIcPLK%%FzhSdeW6)zLW=LYtWiVqfVlZS#V@L+V6tGA+ zLm`6~gF8bGgYRSwHhG8!E8;Zdq#Fh&=jRpx9R>tOQ$PgBJ|eZ}=DWD0l$InjFkISg znFBF{6z6KOmu`L{qQE?{fk%)TteruE8%Vo?!fCT0$9Lw*{34!{{dqVz7$HH(usNP* G4l@Ax{6=U1 delta 180 zcmZp1XfcprU|?W$DortDU=RQ@Ie-{Mvv5r;6q~50$jH4hU^g=(_hbb@pUn{h7Z@j> z666;=15}~$9}Ivj1_t@beL{AVHH7$CGhsZD+ Date: Wed, 13 Jan 2016 19:30:21 -0500 Subject: [PATCH 04/31] Updated --- .DS_Store | Bin 8196 -> 8196 bytes .../Contents.swift | 11 ++++++----- 2 files changed, 6 insertions(+), 5 deletions(-) diff --git a/.DS_Store b/.DS_Store index 2981a46531803d1c41121e8edfacd19d2c222a47..df04fa4736b1713fb3abff2ca6de310631596821 100644 GIT binary patch delta 85 zcmZp1XmOa}&&aniU^hP_-(&?rpUn{h_ZZoXl^GZqR05a1WlmGw# delta 56 zcmV-80LTA?K!iY$PXP_FP`eKS4U-@dOtV-J-T?+OoB#j-ACuq`KC{dcVFHun92v2A O69cmc81@9Qcn1UfkP+ Date: Wed, 13 Jan 2016 20:55:07 -0500 Subject: [PATCH 05/31] Updated --- .DS_Store | Bin 8196 -> 8196 bytes .../Contents.swift | 42 +++++++++++++++--- 2 files changed, 35 insertions(+), 7 deletions(-) diff --git a/.DS_Store b/.DS_Store index df04fa4736b1713fb3abff2ca6de310631596821..cc5751ce047c6cc09bcc4bfd834021c6a7d5e643 100644 GIT binary patch delta 93 zcmZp1XmOa}&&azmU^hP_?_>o*pUn{h6B#Eb3r9(tGo&$?FoZA^GGyhX8wMxm=N2%4 kfwAu71mRe2B>Bx}gsfR7Hn44Gm-xoAnOT&DnHi`O0F31p=Kufz delta 88 zcmZp1XmOa}&&aniU^hP_-(&?rpUn{h6B!xhC&vlfO^y)YV>4D}U|;}qMRN09TvAF) jk{K8-?U@k;6oyJn&JpC>d__o?bu+ufH Date: Thu, 14 Jan 2016 14:52:53 -0500 Subject: [PATCH 06/31] Updated --- .DS_Store | Bin 8196 -> 6148 bytes .../Contents.swift | 67 ++++++++++++++++-- 2 files changed, 61 insertions(+), 6 deletions(-) diff --git a/.DS_Store b/.DS_Store index cc5751ce047c6cc09bcc4bfd834021c6a7d5e643..dcb74dca756c51a5f20eff7c4eef4d9c5fb73f20 100644 GIT binary patch delta 121 zcmZp1XfcprU|?W$DortDU=RQ@Ie-{MGjUEV6q~50$jG)aU^gQp+hhenpUn{h>WrI@ zia0TEY;a>-%+A3f$P82p1OnVZ!WE=zW8rt^$^0^oAY&OA85meVG!w*Ju-N8!o;l0_ D=lc@C literal 8196 zcmeHM!EVz)5Pb`kXoV0Qd-Q=y=^<5JP*HCtIE5k#QiH^`Bo+bW;7}S>y;S}P{)S)R z#HoM6F}#^wp*T)1sEJTJ8|^%2cV=hjt-a1{0JzpDi-C0jtE_?#?o!Ms(l51EZiSY6 zL`Qp|zyL9t*v4K>+Zv1kW55_N28;n?;D2C%?`$cnbKd*D*Q7CE4BSWtWPgZQ1(SfK zN8LIoGzB28uvrVQnFpv%6fg-`dQ?-6>9YqHOkGGZoHu8GB@tS*7ySggwh;y4 Int { +if N == 1 { +return 1 +} else { +return N * factorial(N - 1) +} +} + +o(n!) + */ /*5)Write an Objective C or Swift function to multiply two numbers without using the * operator. Use the grade school method of multiplying by doing repeated addition. For instance, 5 * 8 = 5 + 5 + 5 + 5 + 5 + 5 + 5 + 5 = 40. Find the big O of your function in terms of n and m (the two operands). + +http://www.geeksforgeeks.org/multiply-two-numbers-without-using-multiply-division-bitwise-operators-and-no-loops/ +/* function to multiply two numbers x and y*/ +int multiply(int x, int y) +{ +/* 0 multiplied with anything gives 0 */ +if(y == 0) +return 0; + +/* Add x one by one */ +if(y > 0 ) +return (x + multiply(x, y-1)); + +/* the case where y is negative */ +if(y < 0 ) +return -multiply(x, -y); +} + +int main() +{ +printf("\n %d", multiply(5, -11)); +getchar(); +return 0; +} + +Read more: http://www.noexit4u.com/2013/03/c-program-to-multiply-two-numbers.html + + { + int num1,num2,i,prod=0; + clrscr(); + printf("Enter 1st number: "); + scanf("%d",&num1); + printf("Enter 2nd number: "); + scanf("%d",&num2); + for(i=1;i<=num2;i++) + { + prod+=num1; + } + printf("\n\n\nProduct of %d and %d is %d",num1,num2,prod); + getch(); +} */ /*6)Look up Russian Peasant Multiplication. It’s a faster way to multiply numbers, especially on a binary computer (like yours!). Implement a new multiplication function using this technique and find the big O of your method. If you have trouble with implementing this, write a flow chart and find the big O based on that. (But it’s more satisfying to implement it and run it) From 23c4dc80e4e9c3fd69362a4197b6547e5823e077 Mon Sep 17 00:00:00 2001 From: Xiulan Shi Date: Thu, 14 Jan 2016 15:33:27 -0500 Subject: [PATCH 07/31] Updated --- .../Contents.swift | 67 +++++++++++++++---- 1 file changed, 54 insertions(+), 13 deletions(-) diff --git a/HWfrom1-10-016(BigO).playground/Contents.swift b/HWfrom1-10-016(BigO).playground/Contents.swift index 094ef54..19a610b 100644 --- a/HWfrom1-10-016(BigO).playground/Contents.swift +++ b/HWfrom1-10-016(BigO).playground/Contents.swift @@ -142,20 +142,20 @@ o(n!) /*5)Write an Objective C or Swift function to multiply two numbers without using the * operator. Use the grade school method of multiplying by doing repeated addition. For instance, 5 * 8 = 5 + 5 + 5 + 5 + 5 + 5 + 5 + 5 = 40. Find the big O of your function in terms of n and m (the two operands). http://www.geeksforgeeks.org/multiply-two-numbers-without-using-multiply-division-bitwise-operators-and-no-loops/ -/* function to multiply two numbers x and y*/ -int multiply(int x, int y) +/* function to multiply two numbers n and m*/ +int multiply(int n, int m) { /* 0 multiplied with anything gives 0 */ -if(y == 0) +if(m == 0) return 0; -/* Add x one by one */ -if(y > 0 ) -return (x + multiply(x, y-1)); +/* Add n one by one */ +if(m > 0 ) +return (n + multiply(n, m-1)); -/* the case where y is negative */ -if(y < 0 ) -return -multiply(x, -y); +/* the case where m is negative */ +if(m < 0 ) +return -multiply(n, -m+1); } int main() @@ -168,29 +168,70 @@ return 0; Read more: http://www.noexit4u.com/2013/03/c-program-to-multiply-two-numbers.html { - int num1,num2,i,prod=0; + int n,m,i,prod=0; clrscr(); printf("Enter 1st number: "); scanf("%d",&num1); printf("Enter 2nd number: "); scanf("%d",&num2); - for(i=1;i<=num2;i++) + for(i=1;i<=m;i++) { - prod+=num1; + prod+=n; } - printf("\n\n\nProduct of %d and %d is %d",num1,num2,prod); + printf("\n\n\nProduct of %d and %d is %d",n,m,prod); getch(); } + +O(m) + */ /*6)Look up Russian Peasant Multiplication. It’s a faster way to multiply numbers, especially on a binary computer (like yours!). Implement a new multiplication function using this technique and find the big O of your method. If you have trouble with implementing this, write a flow chart and find the big O based on that. (But it’s more satisfying to implement it and run it) +// an Example below: http://www.cut-the-knot.org/Curriculum/Algebra/PeasantMultiplication.shtml +This is true in general: if tasked with applying the algorithm to finding the product of two numbers a and b, make the smaller number first, the larger one second. + +Now, let's see why the algorithm works. Since halving and doubling play such an important role in the algorithm, it should not come as a great surprise that its real foundation lies in the binary system. To obtain the binary representation of a number, the number is to be repeatedly divided by two, the remainders recorded and then written in the reverse order. Check now the "Show binary" box: + + +We see two additional columns: the first indicates the step (and a power of 2), the second contains the binary digits of 85 written from the bottom upwards: + +85 = 10101012, +which essentially means that + + +85 = 10101012 += 1·26 + 0·25 + 1·24 + 0·23 + 1·22 + 0·21 + 1·20 += 64 + 16 + 4 + 1. +Note that a binary digit is the remainder of division by 2: it is 1 for odd numbers and 0 for even numbers. Which bring forth the connection between the binary digits of the first multiplicand, 85 in our case, and the parity of the number in the column beneath it. The numbers are odd exactly when the remainder that appears to their left is 1. This makes the algorithm tick: + + +85×18 = (64 + 16 + 4 + 1)×18 += 1152 + 288 + 72 + 18 += 1530. +For the product 18×85 we get: + + +18 = 100102 += 1·24 + 0·23 + 0·22 + 1·21 + 0·20 += 16 + 2. +and subsequently + + +18×85 = (16 + 2)×85 += 1360 + 170 += 1530. + + Tip: Run through the method by hand a few times to see how it works and verify to yourself that it does. It’s a non-intuitive algorithm. This will hopefully also make the time complexity more clear. */ /*7)Using the technique from exercise 4, profile the built in sorting method in objective C (use an NSMutableArray and google how to sort an array of numbers in objective C). Graph the result. Use spreadsheet formulas to add graph lines for n, n2, and n*log(n). (You’ll have to modify the factors to make them fit in the graph window and to be close to the graph of method execution time). Show that the sort method best fits n * log(n). + +Not sure how to do this one. I did check the graph in http://bigocheatsheet.com though, still no idea at all. :( + */ From e3fa232d18c16e5f4a64ef3d702a03c7b1c9e9c2 Mon Sep 17 00:00:00 2001 From: Xiulan Shi Date: Thu, 14 Jan 2016 15:44:18 -0500 Subject: [PATCH 08/31] Added different sort methods --- .../Contents.swift | 80 ++++++++++++++++++- 1 file changed, 79 insertions(+), 1 deletion(-) diff --git a/HWfrom1-10-016(BigO).playground/Contents.swift b/HWfrom1-10-016(BigO).playground/Contents.swift index 19a610b..77fd2fa 100644 --- a/HWfrom1-10-016(BigO).playground/Contents.swift +++ b/HWfrom1-10-016(BigO).playground/Contents.swift @@ -232,7 +232,85 @@ Tip: Run through the method by hand a few times to see how it works and verify t Not sure how to do this one. I did check the graph in http://bigocheatsheet.com though, still no idea at all. :( -*/ +//----Bubble sort---- +do +swapped = false +for i = 1 to indexOfLastUnsortedElement +if leftElement > rightElement +swap(leftElement, rightElement) +swapped = true +while swapped + + +//----Select sort---- +repeat (numOfElements - 1) times +set the first unsorted element as the minimum +for each of the unsorted elements +if element < currentMinimum +set element as new minimum +swap minimum with first unsorted position + + +//----Insert sort---- +mark first element as sorted +for each unsorted element +'extract' the element +for i = lastSortedIndex to 0 +if currentSortedElement > extractedElement +move sorted element to the right by 1 +else: insert extracted element + + +//----Merge sort---- +split each element into partitions of size 1 +recursively merge adjancent partitions +for i = leftPartStartIndex to rightPartLastIndex inclusive +if leftPartHeadValue <= rightPartHeadValue +copy leftPartHeadValue +else: copy rightPartHeadValue +copy elements back to original array + + +//----Quick sort---- +for each (unsorted) partition +set first element as pivot +storeIndex = pivotIndex + 1 +for i = pivotIndex + 1 to rightmostIndex +if element[i] < element[pivot] +swap(i, storeIndex); storeIndex++ +swap(pivot, storeIndex - 1) + + +//----R-Quick sort---- +for each (unsorted) partition +randomly select pivot, swap with first element +storeIndex = pivotIndex + 1 +for i = pivotIndex + 1 to rightmostIndex +if element[i] < element[pivot] +swap(i, storeIndex); storeIndex++ +swap(pivot, storeIndex - 1) + + +//----Count sort---- +create key (counting) array +for each element in list +increase the respective counter by 1 +for each counter, starting from smallest key +while counter is non-zero +restore element to list +decrease counter by 1 + + +//----Radix sort---- +create 10 buckets (queues) for each digit (0 to 9) +for each digit placing +for each element in list +move element into respective bucket +for each bucket, starting from smallest digit +while bucket is non-empty +restore element to list + +*/ From 2b280f1fc0968e59e37483df9b63c3fe8a32de58 Mon Sep 17 00:00:00 2001 From: Xiulan Shi Date: Thu, 14 Jan 2016 19:14:11 -0500 Subject: [PATCH 09/31] Updated --- HWfrom1-10-016(BigO).playground/Contents.swift | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/HWfrom1-10-016(BigO).playground/Contents.swift b/HWfrom1-10-016(BigO).playground/Contents.swift index 77fd2fa..c865f7d 100644 --- a/HWfrom1-10-016(BigO).playground/Contents.swift +++ b/HWfrom1-10-016(BigO).playground/Contents.swift @@ -33,7 +33,7 @@ O(n^2) c) My friend sends me an improved version of his algorithm, makeEvenMoreAwesome, that takes into account the pixels around the image. He says it’s O(n2) in the amount of pixels in the image. What is the new time complexity of the method? -O(n^2) +O(n^4) since makeEvenMoreAwesome is O(n^2) */ From c6995392c7aa461d700533854d8ce08991dc5222 Mon Sep 17 00:00:00 2001 From: Xiulan Shi Date: Thu, 14 Jan 2016 19:33:21 -0500 Subject: [PATCH 10/31] Updated --- HWfrom1-10-016(BigO).playground/Contents.swift | 18 ++++++++++++------ 1 file changed, 12 insertions(+), 6 deletions(-) diff --git a/HWfrom1-10-016(BigO).playground/Contents.swift b/HWfrom1-10-016(BigO).playground/Contents.swift index c865f7d..86e6ef2 100644 --- a/HWfrom1-10-016(BigO).playground/Contents.swift +++ b/HWfrom1-10-016(BigO).playground/Contents.swift @@ -61,6 +61,7 @@ for (int i = 0; i < n; i++) { } O(n^2) +Final: O(n^4) b) int frobnicate(ys, m) { if (m == 0) { @@ -69,9 +70,9 @@ b) int frobnicate(ys, m) { return ys[m] + frobnicate(ys, m - 1); } frobnicate(xs, n); +O(n) - -O(n!) +//O(n!) X Tip: Write down a table with n from 0 to 5 and trace through to find out how many times frobnicate is called with each value of n. @@ -103,7 +104,7 @@ O(n(logn)) d) An algorithm that searches the now-sorted list of friends for a specific friend (not including the time it takes to sort). -O(n) +O(logn) Binary search */ @@ -111,18 +112,22 @@ O(n) a) You get a large dataset of points of interest from an API when your app first runs. You build it once at the beginning, and then have to search it many times while the user pans around a map. + Tree----A quad tree is a data structure comprising nodes which store a bucket of points and a bounding box. Any point which is contained within the node’s bounding box is added to its bucket. Once the bucket gets filled up, the node splits itself into four nodes, each with a bounding box corresponding to a quadrant of its parents bounding box. All points which would have gone into the parent’s bucket now go into one of its children’s buckets. https://robots.thoughtbot.com/how-to-handle-large-amounts-of-data-on-maps b) You get a small dataset of points of interest from an API every time the user pans the map. You construct the data set many times and only render it once, then you discard it and do another API search. -Hash Table + +Set or Array Tip: Constructing a dataset of size n means you have to call the data structure’s insert method n times. So if the data structure has an insert method that takes O(n2), the time to build it all from scratch is O(n3). c) You used a linked list for your music app’s playlist feature, but now when people search their playlist, there’s a noticeable lag before loading results. Your competitor’s app is buttery smooth when searching, even showing results as you type. What data structure would allow you to more quickly search without compromising too much on the speed of inserting and deleting tracks, even in the worst case? -Binary Tree + +Tree + */ /*4)Write an algorithm using one of the methods from exercise 1 (your choice) to calculate the factorial of a number n. What is the time complexity of your method in terms of the input value? @@ -135,7 +140,7 @@ return N * factorial(N - 1) } } -o(n!) +O(n!) */ @@ -222,6 +227,7 @@ and subsequently = 1360 + 170 = 1530. +O(logn) Tip: Run through the method by hand a few times to see how it works and verify to yourself that it does. It’s a non-intuitive algorithm. This will hopefully also make the time complexity more clear. From f69b01b6cef5f559f83fba8f29c53e19befe5dbf Mon Sep 17 00:00:00 2001 From: Xiulan Shi Date: Fri, 15 Jan 2016 10:02:12 -0500 Subject: [PATCH 11/31] new homework --- .DS_Store | Bin 6148 -> 10244 bytes .../Contents.swift | 29 ++++++++++++++++++ .../contents.xcplayground | 4 +++ .../contents.xcworkspacedata | 7 +++++ .../timeline.xctimeline | 6 ++++ 5 files changed, 46 insertions(+) create mode 100644 HWfrom1-14-16(Logic+Discrete_Math).playground/Contents.swift create mode 100644 HWfrom1-14-16(Logic+Discrete_Math).playground/contents.xcplayground create mode 100644 HWfrom1-14-16(Logic+Discrete_Math).playground/playground.xcworkspace/contents.xcworkspacedata create mode 100644 HWfrom1-14-16(Logic+Discrete_Math).playground/timeline.xctimeline diff --git a/.DS_Store b/.DS_Store index dcb74dca756c51a5f20eff7c4eef4d9c5fb73f20..ae5da97cfc4cfb1667ead7a80cf232a11a8cb92a 100644 GIT binary patch literal 10244 zcmeHM!EO^V5PhbVC;|yCoY?~vK`2#Hs-oVOkN~Y3kQyY8lw?Z^O4!gQs(PvRBlrP+ zf=dKnz=;!I!IfipV_VT~6QrumMyMJ`_S@JVkNswCYi0qM${;EO0e~fD!CN<2Oi9u% zc_Ll$HMfa|@<5C($|$0Qjfvh`p$sSk%78MU3@8Kt0|UIXB`sZdsHHNX3@8I*2IPDQ zm<2sIu&^!wago(F@tJ;rl?gnC9utRFlw&&Y!FW;QT@2&I*&axDV(2k(=)_^1 zIE>e9yoX|}cFF~|J51$#fQap^%h1p3FSF*o|;3J^VQGu(wo``!;Q}T);q=4#VPOh z8sAlSLTvN2Z}XIB;Q^||Lp~i~kN3bH-k{DKppX5togWKdxXv84r8xcm^_S%|S8d}v zV-DJ~b_->3SFz0-`3Y)x!8^K^-A!hPJ<_}B8g|(8F>P2Ut}sp?ostm7(h{OWlQN(T zCzr9utSGVVe8LfN=~${r@~Y@+`aR|DQjSGJF63 EFQ{D^k^lez delta 117 zcmZn(XfcprU|?W$DortDU=RQ@Ie-{MGjUEV6q~50$jG)aU^gQp+hhenpUn{h>WrI@ zig&OqX6N7#WCkh&0s(Fy;R@2RvG6 + + + \ No newline at end of file diff --git a/HWfrom1-14-16(Logic+Discrete_Math).playground/playground.xcworkspace/contents.xcworkspacedata b/HWfrom1-14-16(Logic+Discrete_Math).playground/playground.xcworkspace/contents.xcworkspacedata new file mode 100644 index 0000000..919434a --- /dev/null +++ b/HWfrom1-14-16(Logic+Discrete_Math).playground/playground.xcworkspace/contents.xcworkspacedata @@ -0,0 +1,7 @@ + + + + + diff --git a/HWfrom1-14-16(Logic+Discrete_Math).playground/timeline.xctimeline b/HWfrom1-14-16(Logic+Discrete_Math).playground/timeline.xctimeline new file mode 100644 index 0000000..bf468af --- /dev/null +++ b/HWfrom1-14-16(Logic+Discrete_Math).playground/timeline.xctimeline @@ -0,0 +1,6 @@ + + + + + From bf69c7b2219c9ef89bb58a7b10287736d5d67650 Mon Sep 17 00:00:00 2001 From: Xiulan Shi Date: Fri, 15 Jan 2016 23:17:21 -0500 Subject: [PATCH 12/31] Finished 1 and 2 --- .DS_Store | Bin 10244 -> 10244 bytes .../Contents.swift | 22 +++++++++++++++--- 2 files changed, 19 insertions(+), 3 deletions(-) diff --git a/.DS_Store b/.DS_Store index ae5da97cfc4cfb1667ead7a80cf232a11a8cb92a..d6b077214991f6159ff4d0b95924280849dfa483 100644 GIT binary patch delta 452 zcmZn(XbG6$&nUMsU^hRb+++nopUn{ha%@aWdnR*<#Z9gf;%3=jvX5ahr&#=CIblAw z1O^~*n9L^@HMu}oT0WhjoS}>%l_874J15;RI5|JJ0HlC{LD3ONU{zO;fvhe8q!^*j z2WVO$gCUUgM>UU87MHr*d>5CL(voBbhD-Z%VnN1XH!n9og(!8X?o$Anrw8<}>*URX z;*%o;_}Jtp1OWJ{ BY90Up delta 135 zcmZn(XbG6$&nUVvU^hRb=wt;!pUFDXe4En*1lZV^7cwv~=uU2sh?+b{T9^^S5)kC( l+_&upPzEL^C(Os_u(?~NhIwPdDVELb3i+gIo!l+s3;^kVB;)`9 diff --git a/HWfrom1-14-16(Logic+Discrete_Math).playground/Contents.swift b/HWfrom1-14-16(Logic+Discrete_Math).playground/Contents.swift index bc0df91..f7ac8ce 100644 --- a/HWfrom1-14-16(Logic+Discrete_Math).playground/Contents.swift +++ b/HWfrom1-14-16(Logic+Discrete_Math).playground/Contents.swift @@ -9,15 +9,31 @@ var str = "Hello, playground" Question 1: https://www.hackerrank.com/challenges/minimum-draws -Copy and paste your code: +Copy and paste your code: -What is the big O runtime of your code?: +let firstLine = Int(readLine(stripNewline: true)!)! +for _ in 1...firstLine{ +let totalPairOfSocks = Int(readLine(stripNewline: true)!)! +print(totalPairOfSocks+1) +} + +//In its worst case scenario, n+1 socks (x) should Jim remove from his drawer until he finds a matching pair if there are n pairs socks in total. + +What is the big O runtime of your code?: O(n) Question 2: https://www.hackerrank.com/challenges/handshake Copy and paste your code: -What is the big O runtime of your code?: +let firstLine = Int(readLine(stripNewline: true)!)! +for _ in 1...firstLine{ +let numberOfPeople = Int(readLine(stripNewline: true)!)! +print(numberOfPeople*(numberOfPeople - 1)/2) +} + +// n*(n-1)/2 which is simplified from C(n, 2) + +What is the big O runtime of your code?: O(n^2) Question 3: https://www.hackerrank.com/challenges/connecting-towns From 383aea6f5411b80007a9c5df264ee490b015e6db Mon Sep 17 00:00:00 2001 From: Xiulan Shi Date: Sat, 16 Jan 2016 00:48:41 -0500 Subject: [PATCH 13/31] Updated --- .DS_Store | Bin 10244 -> 10244 bytes .../Contents.swift | 6 +++--- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/.DS_Store b/.DS_Store index d6b077214991f6159ff4d0b95924280849dfa483..c15119abe16e024e5fb01f1efa893d09724983de 100644 GIT binary patch delta 80 zcmZn(XbG6$&nUYwU^hRb>|_N&pUFDXe4En*1ld?GFfcIaPHvEhnk*;GH@Qlpdh=Ov UD~^c`d7If43b05|J}bTy0K)_reE Date: Sat, 16 Jan 2016 17:59:36 -0500 Subject: [PATCH 14/31] Added solution to 3 --- .../Contents.swift | 105 +++++++++++++++++- 1 file changed, 103 insertions(+), 2 deletions(-) diff --git a/HWfrom1-14-16(Logic+Discrete_Math).playground/Contents.swift b/HWfrom1-14-16(Logic+Discrete_Math).playground/Contents.swift index 6b359c2..78c83ae 100644 --- a/HWfrom1-14-16(Logic+Discrete_Math).playground/Contents.swift +++ b/HWfrom1-14-16(Logic+Discrete_Math).playground/Contents.swift @@ -37,9 +37,110 @@ What is the big O runtime of your code?: O(n^2) Question 3: https://www.hackerrank.com/challenges/connecting-towns -Copy and paste your code: Combination +Copy and paste your code: -What is the big O runtime of your code?: O(n^2) +// ask user how many cases they want to test +let testCases = Int(readLine(stripNewline: true)!)! + + +// ask user for how many towns or nodes are in each case (in order) +for var x in 0.. Date: Tue, 19 Jan 2016 17:29:26 -0500 Subject: [PATCH 15/31] Updated --- .DS_Store | Bin 8196 -> 10244 bytes .../Contents.swift | 77 +++++++++++++++++- 2 files changed, 73 insertions(+), 4 deletions(-) diff --git a/.DS_Store b/.DS_Store index 5dc9a4144404341a56ecabc49f7f87364e26f957..8b1bec7bb9174e7149cc0d2d34dae77da823a2fd 100644 GIT binary patch literal 10244 zcmeI1&uUXa6vn^Nf)xeby3s2rB$1Q^rB-keW1?1C#ir1O3uFE?6_VVLCW;%$Be?Mi zd<2)S1Xu2KA-;l7;8MRcb19QQLNK|Blru2%-OQc2GxIx>NzSs0s(+kX3_I! zSxiWBU-DQw5!GCv8ukZ5w2(y_8QdCctrbc@2`B+2pahh_|3HAh*^*YzIMq@KC;=sK zL_p4mfLSyb>A!1f6u%|$wJYP<58&U-LXR};Ay#&zfYK$=r? zkq(@??l7)9Of<5IJQQO`XTQKUhsinBQVA%5aRTDIU%>wm~@s8&4|NQieEG^EpdA3== zXv221M?=!u?VfkuWO388o7k$y9MDEQRj4J}vTN(6I(brWNic>{d^KPHm34l+$=|;Pcclc773p`Pn3_*Ve?VRFN}iBK!bolf*VM< hg3R1l_?>w&ze*qnBg7_#$?-f>CqERk#&6U|MgRr&D#ZW* diff --git a/HWFrom1-17-16(Lists and Sorts).playground/Contents.swift b/HWFrom1-17-16(Lists and Sorts).playground/Contents.swift index 5d51051..79a835e 100644 --- a/HWFrom1-17-16(Lists and Sorts).playground/Contents.swift +++ b/HWFrom1-17-16(Lists and Sorts).playground/Contents.swift @@ -11,16 +11,85 @@ Work on your solutions here. Link: https://docs.google.com/document/d/1XioaEqk6VqUPA-ccQhkqP3eAoDthxYyOM9vSPB7fDkg/edit#heading=h.uopysoy45zmw -1) +1) Given a partially filled in Sudoku board and a set of coordinates in that board pointing to an empty square, write a function that returns a list containing all numbers that the empty square could be. + +Input: sudokuBoard:[[Int?]]. (Each location on the board will be either be an Int from 1-9 or nil(empty cell)) +row: Int +col: Int + +func getValidNumbers(sudokuBoard:[[Int?]], row:Int, col:Int) -> [Int] { +return [Int]() +} + +Sample input: ,4,4 + +sample output: [1,3,4,5,6,8] +*/ + + +func getValidNumbers(sudokuBoard:[[Int?]], row:Int, col:Int) -> [Int] { + + // loop through the row and create an array with existing integers on the row + // loop through the column, add the integers on the column to the array if they are not there + // loop through the box, add the integers on the box to the array if they are not there + // compare the array with the array [1, 2, 3, 4, 5, 6, 7, 8, 9], the missing integest will be the numbers that the empty square could be. + + +// var sudokuBoard = [ +// [5, 0, 8, 0, 7, 3, 1, 9, 0], +// [9, 0, 0, 6, 0, 0, 4, 0, 8], +// [0, 0, 0, 9, 0, 8, 0, 3, 5], +// [0, 7, 0, 0, 0, 0, 0, 6, 0], +// [0, 0, 2, 0, 0, 0, 9, 0, 0], +// [0, 1, 0, 0, 0, 0, 0, 8, 0], +// [1, 9, 0, 3, 0, 6, 0, 0, 0], +// [2, 0, 3, 0, 0, 7, 0, 0, 9], +// [0, 8, 7, 1, 9, 0, 3, 0, 4]] +// + + return [Int]() + +} -2) +/* + +2) rotate a matrix by ninety degrees +Input: matrix:[[Int]] +Output: matrix: [[Int]] + +Sample Input: [[1,2,3,4], +[5,6,7,8], +[9,0,1,2], +[3,4,5,6]] +Sample Output: [ [3,9,5,1], +[4,0,6,2], +[5,1,7,3], +[6,2,8,4] ] +*/ +//The old matrix [arr1[0], arr1[1], arr1[2],...arr1[n], +// arr2[0], arr2[1], arr2[2],...arr2[n], +// arr3[0], arr3[1], arr3[2],...arr3[n], +// ... +// arrN[0], arrN[1], arrN[2],...arrN[n]] -3) +// The new matrix will be [arrN[0],...,arr3[0],arr2[0], arr1[0], +// arrN[1],...,arr3[1],arr2[1], arr1[1], +// arrN[2],...,arr3[2],arr2[2], arr1[2], +// ... +// arrN[n],...,arr3[n],arr2[n], arr1[n]] +/* + +3)Design an optimal algorithm for sorting four elements A, B, C, and D. By optimal, I mean one that sorts using the minimum number of comparisons. Hint: you may want to start by putting the first two items in order and the last two items in order... that takes two comparisons. How many more comparisons do you need to find the minimum element? The maximum? Once you’ve found the min and max, what if any additional comparisons are needed? -*/ \ No newline at end of file +*/ +//put A and B in order, and put C and D in order +//find the minAB and maxAB for A and B +//find the minCD and maxCD for C and D +//compare minAB and minCD to get min, compare maxAB and maxCD to get max +// From cf2c4bc5dde345daa0476c607e77fb05bf3ce150 Mon Sep 17 00:00:00 2001 From: Xiulan Shi Date: Thu, 21 Jan 2016 19:57:31 -0500 Subject: [PATCH 16/31] updated homework --- .DS_Store | Bin 10244 -> 10244 bytes .../Contents.swift | 135 ++++++++++++++++-- 2 files changed, 127 insertions(+), 8 deletions(-) diff --git a/.DS_Store b/.DS_Store index 8b1bec7bb9174e7149cc0d2d34dae77da823a2fd..a1fc3aabdf60b6c0b7d897e409da8adeeaadbeb1 100644 GIT binary patch delta 104 zcmZn(XbG6$&nUeyU^hRb^kfA=pUL|K`8KBsRIxB=yHBnW37b4Yn1?xEondmdNciS? tqWhScv}7m8Nk)LgS+ZCd7{D9>L2lL~Al~LU$(yX3*%fSAku;?-0RUdM9n}B; delta 80 zcmZn(XbG6$&nUSuU^hRb [Int] { + var valid: Set = [1, 2, 3, 4, 5, 6, 7, 8, 9] + for c in 0..(valid) + +} + let sampleInput: [[Int?]] = [ + [5, 0, 8, 0, 7, 3, 1, 9, 0], + [9, 0, 0, 6, 0, 0, 4, 0, 8], + [0, 0, 0, 9, 0, 8, 0, 3, 5], + [0, 7, 0, 0, 0, 0, 0, 6, 0], + [0, 0, 2, 0, 0, 0, 9, 0, 0], + [0, 1, 0, 0, 0, 0, 0, 8, 0], + [1, 9, 0, 3, 0, 6, 0, 0, 0], + [2, 0, 3, 0, 0, 7, 0, 0, 9], + [0, 8, 7, 1, 9, 0, 3, 0, 4]] + + getValidNumbers(sampleInput, row: 0, col: 1) + + + + //Method 1 + // loop through the row, the column and the box, create a set. + // call .subtract to get the values + + //Method 2 // loop through the row and create an array with existing integers on the row // loop through the column, add the integers on the column to the array if they are not there // loop through the box, add the integers on the box to the array if they are not there @@ -45,11 +103,10 @@ func getValidNumbers(sudokuBoard:[[Int?]], row:Int, col:Int) -> [Int] { // [1, 9, 0, 3, 0, 6, 0, 0, 0], // [2, 0, 3, 0, 0, 7, 0, 0, 9], // [0, 8, 7, 1, 9, 0, 3, 0, 4]] -// +// - return [Int]() -} + @@ -69,24 +126,86 @@ Sample Output: [ [3,9,5,1], [5,1,7,3], [6,2,8,4] ] + */ -//The old matrix [arr1[0], arr1[1], arr1[2],...arr1[n], -// arr2[0], arr2[1], arr2[2],...arr2[n], -// arr3[0], arr3[1], arr3[2],...arr3[n], + +func rotate90(matrix: [[Int]]) -> [[Int]] { + let n = matrix.count + + var result: [[Int]] = [] + + for _ in 0.. 0, n - 1 + // r, c -> r, n - c -1 + + // 0, n - 1 -> n - 1, n - 1 + // r, c -> n - r - 1, c + + // n - 1, n -1 -> n - 1, 0 + // r, c -> n + + +//The old matrix [arr1[0], arr1[1], arr1[2],...arr1[n-1], +// arr2[0], arr2[1], arr2[2],...arr2[n-1], +// arr3[0], arr3[1], arr3[2],...arr3[n-1], // ... -// arrN[0], arrN[1], arrN[2],...arrN[n]] +// arrN[0], arrN[1], arrN[2],...arrN[n-1]] // The new matrix will be [arrN[0],...,arr3[0],arr2[0], arr1[0], // arrN[1],...,arr3[1],arr2[1], arr1[1], // arrN[2],...,arr3[2],arr2[2], arr1[2], // ... -// arrN[n],...,arr3[n],arr2[n], arr1[n]] +// arrN[n-1],...,arr3[n-1],arr2[n-1], arr1[n-1]] /* 3)Design an optimal algorithm for sorting four elements A, B, C, and D. By optimal, I mean one that sorts using the minimum number of comparisons. Hint: you may want to start by putting the first two items in order and the last two items in order... that takes two comparisons. How many more comparisons do you need to find the minimum element? The maximum? Once you’ve found the min and max, what if any additional comparisons are needed? + + + +func mySort(values: [Int]) -> [Int] { + var left = values[0...1] + if left[0] > left[1] { + let t = left[0] + left[0] = left[1] + left[1] = t + } + var right = values[2...4] + if right[0] > right[1] { + let t = right[0] + right[0] = right[1] + right[1] = t + } + + return + +} */ //put A and B in order, and put C and D in order //find the minAB and maxAB for A and B From d8a8407b69f33d4f15758531b78741e66d240b63 Mon Sep 17 00:00:00 2001 From: Xiulan Shi Date: Sun, 24 Jan 2016 10:42:18 -0500 Subject: [PATCH 17/31] Updated --- .../Contents.swift | 74 ++++++++++++++++++- 1 file changed, 72 insertions(+), 2 deletions(-) diff --git a/HWFrom1-17-16(Lists and Sorts).playground/Contents.swift b/HWFrom1-17-16(Lists and Sorts).playground/Contents.swift index bd98551..2122c72 100644 --- a/HWFrom1-17-16(Lists and Sorts).playground/Contents.swift +++ b/HWFrom1-17-16(Lists and Sorts).playground/Contents.swift @@ -25,8 +25,51 @@ Sample input: ,4,4 sample output: [1,3,4,5,6,8] */ +/* - +func getValidNumbers(sudokuBoard:[[Int?]], row:Int, col:Int)->[Int] { + var availableNumbersMap = Array(count: 9, repeatedValue: true) + // check rows + for i in (0..<9) { + if( i != row && sudokuBoard[i][col] != nil) { + let usedNumber = sudokuBoard[i][col]! + availableNumbersMap[usedNumber - 1] = false + } + } + + //check cols + for i in (0..<9) { + if( i != row && sudokuBoard[row][i] != nil) { + let usedNumber = sudokuBoard[row][i]! + availableNumbersMap[usedNumber - 1] = false + } + } + + //check 3x3 box + let rowMultiplier = row/3 // taking advantage of integer division + let rowOffset = rowMultiplier*3 // ex: 8/3 = 2 + let colMultiplier = col/3 + let colOffset = colMultiplier*3 + for i in (0..<3) { + for j in (0..<3) { + if rowOffset+i != row && colOffset+j != col && sudokuBoard[rowOffset+i][colOffset+j] != nil { + let usedNumber = sudokuBoard[rowOffset+i][colOffset+i]! + availableNumbersMap[usedNumber - 1] = false + } + } + } + + // convert availableNumbers to an array of Ints + var availableNumbers = [Int]() + for i in (0.. [Int] { var valid: Set = [1, 2, 3, 4, 5, 6, 7, 8, 9] @@ -80,7 +123,7 @@ func getValidNumbers(sudokuBoard:[[Int?]], row:Int, col:Int) -> [Int] { getValidNumbers(sampleInput, row: 0, col: 1) - + */ //Method 1 // loop through the row, the column and the box, create a set. @@ -129,6 +172,31 @@ Sample Output: [ [3,9,5,1], */ +// O(N*M) space +// Extra: think of a way to do the rotation inplace +// meaning don't use any extra arrays. +func rotateMatrix(mat:[[Int]]) -> [[Int]] { + let newRowCount = mat[0].count // new number of rows will be the same as + let newColCount = mat.count // the old number of cols. vice versa for cols + var newMat = Array(count: newRowCount, repeatedValue: Array(count: newColCount, repeatedValue: 0)) + for i in (0.. [[Int]] { let n = matrix.count @@ -157,6 +225,8 @@ let rotateInput = [[1,2,3,4], rotate90(rotateInput) +*/ + // n * n matrix // 0, 0 -> 0, n - 1 From 532f5317617c7b56ef9e4aa60d074d23115a98d3 Mon Sep 17 00:00:00 2001 From: Xiulan Date: Thu, 28 Jan 2016 14:26:44 -0500 Subject: [PATCH 18/31] updated --- .DS_Store | Bin 8196 -> 10244 bytes .../Contents.swift | 25 ++++++++++++++++++ .../contents.xcplayground | 4 +++ .../contents.xcworkspacedata | 7 +++++ .../timeline.xctimeline | 6 +++++ .../Contents.swift | 3 ++- 6 files changed, 44 insertions(+), 1 deletion(-) create mode 100644 HWFrom1-24(Recursion).playground/Contents.swift create mode 100644 HWFrom1-24(Recursion).playground/contents.xcplayground create mode 100644 HWFrom1-24(Recursion).playground/playground.xcworkspace/contents.xcworkspacedata create mode 100644 HWFrom1-24(Recursion).playground/timeline.xctimeline diff --git a/.DS_Store b/.DS_Store index 3c722e62e7ae3abe7e02e16e480e2db412a06933..3bd69577ba1f4e05f46cbb92bd52f1b7a6c71c22 100644 GIT binary patch delta 579 zcmZp1XbF&DU|?W$DortDU{C-uIe-{M3-C-V6q~50$SA%sU^hRb_+$k^A1TkA{N$vZ z{3MV(5W4}f#(yxFEGOtUd7mKP<}`r_Ms#&&kkl0jxoqAin1Z1OWY!F*S@VPwz-Ac; zFJhENvlC<%R2{?SY7sL=ePsp@hH!>7h9ZW1hFk_i23-at24f&;$Y92x!4Sld%8<-Z z3Y0Bo$ONj$o9rMU;el!>V-S*|KqfE%Kt{Tu7-@pbu*si9g*o6(S}PjGw6URsRgf8E z5YQ-YAmIuM&y9uOnJ4qh1d1?0LRkYO&B(xD0HP-s$nEzYLlTdJF{& OISh#ml?>^i@BskSE0*g3 delta 131 zcmZn(XmOBWU|?W$DortDU;r^WfEYvza8E20o2aMAD7Z0TH$S7`2mn-2)2F-|@p zz_)plP#Auay-w} N$?L_o0M!RG0RXjD9@hW> diff --git a/HWFrom1-24(Recursion).playground/Contents.swift b/HWFrom1-24(Recursion).playground/Contents.swift new file mode 100644 index 0000000..1c44504 --- /dev/null +++ b/HWFrom1-24(Recursion).playground/Contents.swift @@ -0,0 +1,25 @@ +/* + + +Homework link: https://docs.google.com/document/d/1INvOynuggw69yLRNg3y-TPwBiYb3lQZQiFUOxZKBwsY/edit#heading=h.za36ai6n5fth + + + +*/ + + + +//Question 1 + + + + + + +//Question 2 + + + + + +//Question 3 \ No newline at end of file diff --git a/HWFrom1-24(Recursion).playground/contents.xcplayground b/HWFrom1-24(Recursion).playground/contents.xcplayground new file mode 100644 index 0000000..5da2641 --- /dev/null +++ b/HWFrom1-24(Recursion).playground/contents.xcplayground @@ -0,0 +1,4 @@ + + + + \ No newline at end of file diff --git a/HWFrom1-24(Recursion).playground/playground.xcworkspace/contents.xcworkspacedata b/HWFrom1-24(Recursion).playground/playground.xcworkspace/contents.xcworkspacedata new file mode 100644 index 0000000..919434a --- /dev/null +++ b/HWFrom1-24(Recursion).playground/playground.xcworkspace/contents.xcworkspacedata @@ -0,0 +1,7 @@ + + + + + diff --git a/HWFrom1-24(Recursion).playground/timeline.xctimeline b/HWFrom1-24(Recursion).playground/timeline.xctimeline new file mode 100644 index 0000000..bf468af --- /dev/null +++ b/HWFrom1-24(Recursion).playground/timeline.xctimeline @@ -0,0 +1,6 @@ + + + + + diff --git a/HWfrom1-23-16(Recursion).playground/Contents.swift b/HWfrom1-23-16(Recursion).playground/Contents.swift index 4776cab..f7c3b5c 100644 --- a/HWfrom1-23-16(Recursion).playground/Contents.swift +++ b/HWfrom1-23-16(Recursion).playground/Contents.swift @@ -1,4 +1,5 @@ //: Playground - noun: a place where people can play +//THIS IS AN OPTIONAL ASSIGNMENT import UIKit @@ -17,4 +18,4 @@ var str = "Hello, playground" -//3 \ No newline at end of file +//3 From a4541682b59b8e999ff0a4c5abfe6c0d4ff18f01 Mon Sep 17 00:00:00 2001 From: Xiulan Date: Thu, 28 Jan 2016 17:10:57 -0500 Subject: [PATCH 19/31] Added --- .DS_Store | Bin 10244 -> 10244 bytes .../Contents.swift | 61 +++++++++++++++++- .../Contents.swift | 24 +++++++ 3 files changed, 84 insertions(+), 1 deletion(-) diff --git a/.DS_Store b/.DS_Store index 3bd69577ba1f4e05f46cbb92bd52f1b7a6c71c22..eba6108a0ea43532829b3bd78c89f48a64f7764f 100644 GIT binary patch delta 35 icmZn(XbIS`Pn?B;fq`-IA@LXxgK4vp#2kK@kP`r>0SHV0 delta 35 gcmZn(XbIS`Pn_jH5KKNK9s_1 New > Project, select “Application” under “OS X” in the sidebar, then select “Command Line Tool”; on the next screen, choose “Swift” as the language. + + +Appendix A: Recursive Fibonacci from class (non-memoized) +func fib(n: Int) -> Int { +print("X") +if (n == 0 || n == 1) { +return 1 +} +return fib(n - 1) + fib(n - 2) +} +Appendix B: New and improved clumsy robot +import Foundation + +var stepNum = 0 +func tryStep() -> Int { +let stepCount = Int(arc4random_uniform(3)) - 1 +stepNum += stepCount; +switch(stepCount) { +case -1: print("Ouch \(stepNum)") +case 1: print("Yay \(stepNum)") +default: print("Beep \(stepNum)") +} +return stepCount +} + +Appendix C: File searching +import Foundation + +func findFile(name: String, atPath: String) -> String { +let fileManager = NSFileManager.defaultManager() +let contents = +try! fileManager.contentsOfDirectoryAtPath(atPath) +for fileOrDir in contents { +var isDir = ObjCBool(false); +let fullPath = atPath + "/" + fileOrDir +let exists = fileManager.fileExistsAtPath(fullPath, isDirectory: &isDir) +if exists && Bool(isDir) { +// YOUR CODE HERE +print("DIR: " + fileOrDir) +} else if exists { +// YOUR CODE HERE +print("FILE: " + fileOrDir) +} else { +print("NEITHER: " + fileOrDir) +} +} +return "NOT FOUND" +} + +print(findFile("awesome-idea.txt", atPath: "/Users/calebegg/Documents")) */ @@ -22,4 +81,4 @@ Homework link: https://docs.google.com/document/d/1INvOynuggw69yLRNg3y-TPwBiYb3l -//Question 3 \ No newline at end of file +//Question 3 diff --git a/HWfrom1-23-16(Recursion).playground/Contents.swift b/HWfrom1-23-16(Recursion).playground/Contents.swift index f7c3b5c..adce16d 100644 --- a/HWfrom1-23-16(Recursion).playground/Contents.swift +++ b/HWfrom1-23-16(Recursion).playground/Contents.swift @@ -7,6 +7,30 @@ var str = "Hello, playground" //https://docs.google.com/document/d/1KfnTOtPnBrYPFhBRAQPZBXor_mKDQvuJp4zwZbtHkRs/edit#heading=h.16sfqfmanxte +/* +Write a recursive method to print the binary representation of a decimal number to STDOUT. https://www.khanacademy.org/math/pre-algebra/applying-math-reasoning-topic/alternate-number-bases/v/decimal-to-binary - explanation of how to convert decimal to binary + + +func printBinaryRepresentation(number:Int) { + +} + +Sample Input: 5 +Sample Output: 101 + +2. Swap all adjacent elements in an array. All arrays will have an even size. Do not use loops. + +Sample input: [1,2,4,7,3,8,5,6] +Sample output: [2,1,7,4,8,3,6,5] + +3. Implement a binary search for a sorted array. Given an Int and an [Int]. Return true if the element exists in the array and false if not. + +Sample input: [1,2,7,23,23,167,9465] 167 +Sample output: true + + +*/ + //1 From 0425d02aadd5f4a61a19235878a46d3217d19384 Mon Sep 17 00:00:00 2001 From: Xiulan Date: Thu, 28 Jan 2016 19:10:41 -0500 Subject: [PATCH 20/31] updated --- .../Contents.swift | 169 ++++++++++++------ 1 file changed, 119 insertions(+), 50 deletions(-) diff --git a/HWFrom1-24(Recursion).playground/Contents.swift b/HWFrom1-24(Recursion).playground/Contents.swift index 332a0e5..e6b33f1 100644 --- a/HWFrom1-24(Recursion).playground/Contents.swift +++ b/HWFrom1-24(Recursion).playground/Contents.swift @@ -3,82 +3,151 @@ Homework link: https://docs.google.com/document/d/1INvOynuggw69yLRNg3y-TPwBiYb3lQZQiFUOxZKBwsY/edit#heading=h.za36ai6n5fth -Write an iterative (not recursive) fibonacci function that calculates the nth fibonacci number. How does its performance compare with the non-memoized recursive one (see Appendix A below), based on the number of iterations that Swift says it takes in the right margin? +*/ +//Question 1 -The engineers have been hard at work on the clumsy robot project, and have released a new API with a new tryStep method (see Appendix B). Now it returns an Int, which is -1 if the robot fell down a step, 0 if the robot stayed on the same step, or 1 if the robot went to the next step. Write a new stepUp method using this new tryStep method that works the same as before. +//Write an iterative (not recursive) fibonacci function that calculates the nth fibonacci number. How does its performance compare with the non-memoized recursive one (see Appendix A below), based on the number of iterations that Swift says it takes in the right margin? +//Appendix A: Recursive Fibonacci from class (non-memoized) +//func fib(n: Int) -> Int { +// print("X") +// if (n == 0 || n == 1) { +// return 1 +// } +// return fib(n - 1) + fib(n - 2) +//} + +//memorized fib +var cache = [Int: Int]() +cache[0] = 1 +cache[1] = 1 + +func fibm(n: Int) -> Int { + print("X") + if cache[n] != nil { + return cache[n]! + } + let value = fibm(n - 1) + fibm(n - 2) + cache[n] = value + return value +} +fibm(15) -Using the code in Appendix C as a starting point, create a Swift command line project to find files on your computer by name. Your solution should use recursion. Your method should return “NOT FOUND” if it couldn’t find the file, otherwise it should return the full path to that file. +//non-memorized fib +func fib(n: Int) -> Int { + print("X") + if (n == 0 || n == 1) { + return 1 + } + return fib(n - 1) + fib(n - 2) +} -You can’t use a playground for this because they don’t have filesystem access for some reason. Instead, in XCode, go to File > New > Project, select “Application” under “OS X” in the sidebar, then select “Command Line Tool”; on the next screen, choose “Swift” as the language. +fib(15) +//interative fib -Appendix A: Recursive Fibonacci from class (non-memoized) -func fib(n: Int) -> Int { -print("X") -if (n == 0 || n == 1) { -return 1 +func fibonacci(n: Int) -> Int { +// Some temporary variables. +var a = 1 +var b = 1 +// Add up numbers to the desired iteration. +for _ in 0.. Int { -let stepCount = Int(arc4random_uniform(3)) - 1 -stepNum += stepCount; -switch(stepCount) { -case -1: print("Ouch \(stepNum)") -case 1: print("Yay \(stepNum)") -default: print("Beep \(stepNum)") -} -return stepCount -} +fibonacci(15) -Appendix C: File searching -import Foundation +// Loop over values 0 through 14 inclusive. +//for i in 0..<15 { +// // Call Fibonacci method. +// let result = fibonacci(i) +// print("Fibonacci \(i) = \(result)") +//} -func findFile(name: String, atPath: String) -> String { -let fileManager = NSFileManager.defaultManager() -let contents = -try! fileManager.contentsOfDirectoryAtPath(atPath) -for fileOrDir in contents { -var isDir = ObjCBool(false); -let fullPath = atPath + "/" + fileOrDir -let exists = fileManager.fileExistsAtPath(fullPath, isDirectory: &isDir) -if exists && Bool(isDir) { -// YOUR CODE HERE -print("DIR: " + fileOrDir) -} else if exists { -// YOUR CODE HERE -print("FILE: " + fileOrDir) -} else { -print("NEITHER: " + fileOrDir) -} -} -return "NOT FOUND" -} -print(findFile("awesome-idea.txt", atPath: "/Users/calebegg/Documents")) -*/ +//Question 2 +//The engineers have been hard at work on the clumsy robot project, and have released a new API with a new tryStep method (see Appendix B). Now it returns an Int, which is -1 if the robot fell down a step, 0 if the robot stayed on the same step, or 1 if the robot went to the next step. Write a new stepUp method using this new tryStep method that works the same as before. +//Appendix B: New and improved clumsy robot +import Foundation -//Question 1 +var stepNum = 0 +func tryStep() -> Int { + let stepCount = Int(arc4random_uniform(3)) - 1 + stepNum += stepCount; + switch(stepCount) { + case -1: print("Ouch \(stepNum)") + case 1: print("Yay \(stepNum)") + default: print("Beep \(stepNum)") + } + return stepCount +} +/* +var stepNum = 0 +func tryStep() -> Bool { + let success = Int(arc4random_uniform(2)) > 0 + if (success) { + stepNum++ + print("Yay! \(stepNum)") + } else { + stepNum--; + print("Ow! \(stepNum)") + } + return success +} +​ +func stepUp() { + if tryStep() { + // We’re done! + return + } + // Now we’re two steps below where we want to be :-( + stepUp() + stepUp() +} +*/ +//Question 3 +//Using the code in Appendix C as a starting point, create a Swift command line project to find files on your computer by name. Your solution should use recursion. Your method should return “NOT FOUND” if it couldn’t find the file, otherwise it should return the full path to that file. -//Question 2 +//You can’t use a playground for this because they don’t have filesystem access for some reason. Instead, in XCode, go to File > New > Project, select “Application” under “OS X” in the sidebar, then select “Command Line Tool”; on the next screen, choose “Swift” as the language. +//Appendix C: File searching +import Foundation +func findFile(name: String, atPath: String) -> String { + let fileManager = NSFileManager.defaultManager() + let contents = + try! fileManager.contentsOfDirectoryAtPath(atPath) + for fileOrDir in contents { + var isDir = ObjCBool(false); + let fullPath = atPath + "/" + fileOrDir + let exists = fileManager.fileExistsAtPath(fullPath, isDirectory: &isDir) + if exists && Bool(isDir) { + // YOUR CODE HERE + print("DIR: " + fileOrDir) + } else if exists { + // YOUR CODE HERE + print("FILE: " + fileOrDir) + } else { + print("NEITHER: " + fileOrDir) + } + } + return "NOT FOUND" +} +//print(findFile("awesome-idea.txt", atPath: "/Users/calebegg/Documents")) -//Question 3 From 9582cf65e1a2242e38bb278004a71425ab202501 Mon Sep 17 00:00:00 2001 From: Xiulan Date: Thu, 28 Jan 2016 19:47:28 -0500 Subject: [PATCH 21/31] 01-28 --- .../Contents.swift | 41 +++++++++++++++---- 1 file changed, 32 insertions(+), 9 deletions(-) diff --git a/HWFrom1-24(Recursion).playground/Contents.swift b/HWFrom1-24(Recursion).playground/Contents.swift index e6b33f1..3e85475 100644 --- a/HWFrom1-24(Recursion).playground/Contents.swift +++ b/HWFrom1-24(Recursion).playground/Contents.swift @@ -31,8 +31,9 @@ func fibm(n: Int) -> Int { cache[n] = value return value } +(0...5).map { i in fibm(i) } +//fibm(15) -fibm(15) //non-memorized fib func fib(n: Int) -> Int { @@ -41,15 +42,17 @@ func fib(n: Int) -> Int { return 1 } return fib(n - 1) + fib(n - 2) + } +(0...5).map { i in fib(i) } -fib(15) +//fib(15) //interative fib func fibonacci(n: Int) -> Int { // Some temporary variables. -var a = 1 +var a = 0 var b = 1 // Add up numbers to the desired iteration. for _ in 0.. Int { return stepCount } +func stepUp() { + switch tryStep() { + case 1: + return + case -1: + stepUp() + stepUp() + default: + stepUp() + } +} + + /* var stepNum = 0 @@ -137,10 +153,17 @@ func findFile(name: String, atPath: String) -> String { let exists = fileManager.fileExistsAtPath(fullPath, isDirectory: &isDir) if exists && Bool(isDir) { // YOUR CODE HERE - print("DIR: " + fileOrDir) +// print("DIR: " + fileOrDir) + let result = findFile(name, atPath: fullPath) + if result != "NOT FOUND" { + return result + } } else if exists { // YOUR CODE HERE - print("FILE: " + fileOrDir) +// print("FILE: " + fileOrDir) + if fileOrDir == name { + return fullPath + } } else { print("NEITHER: " + fileOrDir) } @@ -148,6 +171,6 @@ func findFile(name: String, atPath: String) -> String { return "NOT FOUND" } -//print(findFile("awesome-idea.txt", atPath: "/Users/calebegg/Documents")) +//print(findFile("awesome-idea.txt", atPath: "/Users/C4Q/Documents")) From 114e59c6649b99c0d306146af9284b964b6b3908 Mon Sep 17 00:00:00 2001 From: Xiulan Date: Sun, 31 Jan 2016 13:44:01 -0500 Subject: [PATCH 22/31] Updated --- .DS_Store | Bin 10244 -> 10244 bytes 1 file changed, 0 insertions(+), 0 deletions(-) diff --git a/.DS_Store b/.DS_Store index eba6108a0ea43532829b3bd78c89f48a64f7764f..a2232c89ecee05ec2d850f12b1d58080d1e9c987 100644 GIT binary patch delta 20 ccmZn(XbISGP@Iu@^C9v7{EW<#4~aVg08}~$fdBvi delta 20 ccmZn(XbISGP@Iu*^C9v7{EUo~4~aVg08|(UeE Date: Sun, 31 Jan 2016 16:17:36 -0500 Subject: [PATCH 23/31] Updated --- .DS_Store | Bin 10244 -> 10244 bytes .../Contents.swift | 27 ++++++++++++++++++ .../Contents.swift | 26 +++++++++++++---- 3 files changed, 47 insertions(+), 6 deletions(-) diff --git a/.DS_Store b/.DS_Store index a2232c89ecee05ec2d850f12b1d58080d1e9c987..2fbbfc417bd53d0ee576c201445351cb20929f79 100644 GIT binary patch delta 195 zcmZn(XbG6$&nUSuU^hRb%osEnd>K-KGU-54fgu>EqKKhnvV(wD2qOmr0|U$d|3H#~!2rVuW1tw!h(Lx? zhD?TJhHRJt4B8AnK#^jG5+K%Q0LiC<@Z<|(QXqFtRuE%h16#nlSxMqA+h%r!zw7|~ Ck| Bool { +// +//} -//6) \ No newline at end of file From c307cc45e5f4cbed1dae5d3b5d21386824538873 Mon Sep 17 00:00:00 2001 From: Xiulan Date: Sun, 31 Jan 2016 17:49:53 -0500 Subject: [PATCH 24/31] 1-30-16 HW --- .../Contents.swift | 122 +++++++++++++++++- 1 file changed, 119 insertions(+), 3 deletions(-) diff --git a/HWFrom1-30-16(QuickSort+Lists+Queues).playground/Contents.swift b/HWFrom1-30-16(QuickSort+Lists+Queues).playground/Contents.swift index d9003f6..7a56096 100644 --- a/HWFrom1-30-16(QuickSort+Lists+Queues).playground/Contents.swift +++ b/HWFrom1-30-16(QuickSort+Lists+Queues).playground/Contents.swift @@ -5,10 +5,66 @@ //1)Without looking at the Big O Cheatsheet, write down the average time and space complexity for bubble sort, insertion sort, selection sort, mergesort, and quicksort. +// bubble sort: time - O(n^2) +// space - O(1) auxiliary (Additional space complexity can be O(n) in an implementation using arrays and O(1) in linked list implementations.) + +// insertion sort: time - O(n^2) best case could be O(n) +// space - О(n) total, O(1) auxiliary + +// selection sort: time - O(n^2) +// space - О(n) total, O(1) auxiliary + +// mergesort: time - O(nlog(n)) +// space - О(n) total, O(n) auxiliary + +// quicksort: time - O(nlog(n)) worst could O(n^2) +// space - O(n) auxiliary (naive), O(log n) auxiliary + + + //2)What is the advantage of partitioning quicksort in place? +//This ensures the partitioning phase of quicksort partitions the arrays into sub-arrays of almost equal size and hence that the expected running time remains O(nlogn) + //3)Without looking, implement quicksort. +/*func partition(inout arr: [Int], first: Int, last: Int) -> Int { + let pivot = arr[first] + var lM = first + 1 + var rM = last + + while lM <= rM { + while lM <= rM && arr[lM] < pivot { + lM += 1 + } + while lM <= rM && arr[rM] > pivot { + rM -= 1 + } + if lM < rM { + swap(&arr[lM], &arr[rM]) + } + } + if first != rM { + swap(&arr[first], &arr[rM]) + } + return rM +} + +func quickSort(inout arr: [Int], first: Int, last: Int) { + if first >= last { return } + let splitPoint = partition(&arr, first: first, last: last) + quickSort(&arr, first: first, last: splitPoint - 1) + quickSort(&arr, first: splitPoint + 1, last: last) +} + +func quickSort(inout arr: [Int]){ + quickSort(&arr, first: 0, last: arr.count - 1) +} + +var numberList = [22, 3, 43, 55, 23, 29, 17, 90] +quickSort(&numberList) +*/ + //4)Write a function to generate an array of random numbers bounded between 1..<10,000 of size 10,000. @@ -16,15 +72,75 @@ //Compare the time it takes to run mergesort, quicksort, and quicksort with the median. //https://gist.github.com/gummibeatz/8ff29bcec54d7e3ef683 +/* + +func profile(block:(()->())) { + let start = NSDate() + block() + let end = NSDate() + print(end.timeIntervalSinceDate(start)) +} + + +func partition(inout arr: [Int], first: Int, last: Int) -> Int { + let pivot = arr[first] + var lM = first + 1 + var rM = last + + while lM <= rM { + while lM <= rM && arr[lM] < pivot { + lM += 1 + } + while lM <= rM && arr[rM] > pivot { + rM -= 1 + } + if lM < rM { + swap(&arr[lM], &arr[rM]) + } + } + if first != rM { + swap(&arr[first], &arr[rM]) + } + return rM +} + +func quickSort(inout arr: [Int], first: Int, last: Int) { + if first >= last { return } + let splitPoint = partition(&arr, first: first, last: last) + quickSort(&arr, first: first, last: splitPoint - 1) + quickSort(&arr, first: splitPoint + 1, last: last) +} + +func quickSort(inout arr: [Int]){ + quickSort(&arr, first: 0, last: arr.count - 1) +} + +var arr = [Int(arc4random_uniform(UInt32(10000)))] + +//run your function/code inside the block below +profile({ + quickSort(&arr) +}) +*/ //5)Describe the algorithmic difference between mergesort and quicksort. Where does the sorting happen? As the recursive calls are being pushed onto the stack or as they are being popped off? +/* +Quick sort does not require any additional memory while executing. It just sorts everything in the very array where the unsorted elements are present. On the other hand Merge sort requires extra memory (a lot of memory if the array is large). And the amount of extra memory required is O(n) which means it is directly proportional to the input size n. so the concluding statement is: "Quick sort is an IN-PLACE Algorithm while Merge sort is not." +"Quick Sort is NOT a stable sorting algorithm while Merge is." Quick sort is not stable because it exchanges the non adjacent elements. So preservance of order is not taken care of. The result might be stable or unstable. While Merge is a stable sort. +Quick sort is likely to run 1.2 to 1.4 times faster than Merge sort. It is always a good choice to use Quick over merge if Stability is not required. Moreover a good implementation of Quick sort is easier to code than a good implantation of Merge sort. Although Quick Sort's worse case of running time is O(n2) but it is always avoided using a randomized version of quick sort. +MergeSort exhibits end order or bottom up recursion in that all the significant actions take place after the recursive calls. This means that the array is split all the way down to singletons (of size 1) and that all actions take place on the way out of recursion. +In contrast, quickSort is exactly the opposite, namely top down recursion in the sense that the main action of partitioning is done before the recursive calls. + +*/ //6)Given an array of strings containing “[“,”]”,”{“,”}”,”(“,”)”. Output whether or not the parentheses are balanced. //Good examples: () [] () ([]()[]) //Bad examples: ( ( ] ([)] // -//func isBalanced(paren: [String]) -> Bool { -// -//} +func isBalanced(paren: [String]) -> Bool { + + + return true +} From b9a19c15468cb8e17814ccac0b83e8f802015710 Mon Sep 17 00:00:00 2001 From: Xiulan Date: Mon, 1 Feb 2016 00:23:00 -0500 Subject: [PATCH 25/31] Finished 01-30 HW --- .../Contents.swift | 29 +++++++++++++++++-- 1 file changed, 26 insertions(+), 3 deletions(-) diff --git a/HWFrom1-30-16(QuickSort+Lists+Queues).playground/Contents.swift b/HWFrom1-30-16(QuickSort+Lists+Queues).playground/Contents.swift index 7a56096..a4a0ec0 100644 --- a/HWFrom1-30-16(QuickSort+Lists+Queues).playground/Contents.swift +++ b/HWFrom1-30-16(QuickSort+Lists+Queues).playground/Contents.swift @@ -139,8 +139,31 @@ In contrast, quickSort is exactly the opposite, namely top down recursion in the //Bad examples: ( ( ] ([)] // func isBalanced(paren: [String]) -> Bool { - - - return true + var stack = [String]() + for (var i = 0; i < paren.count; i++) { + let check = paren[i] + if (check == "(" || check == "[" || check == "{") { + stack.append(check); + } else if (stack.count == 0) { + return false + } else if (check == ")" && stack.removeLast() != "(") { + return false + } else if (check == "]" && stack.removeLast() != "[") { + return false + } else if (check == "}" && stack.removeLast() != "{") { + return false + } + } + return true; } +var good = ["(", ")", "[", "]", "(", ")", "(", "[", "]", "(", ")", "[", "]", ")"] +var bad = ["(", "(", "]", "(", "[", ")", "]"] +var test = [")", ")"] +var test2 = ["{","[", "]","}", "{", "}"] + +isBalanced(good) +isBalanced(bad) +isBalanced(test) +isBalanced(test2) +isBalanced([]) From 9aa9321f082dc12275d2189bb2c8e3797ee265ef Mon Sep 17 00:00:00 2001 From: Xiulan Date: Mon, 1 Feb 2016 16:21:00 -0500 Subject: [PATCH 26/31] Updated --- .DS_Store | Bin 10244 -> 10244 bytes .../Contents.swift | 79 +++++++++++++++++- 2 files changed, 78 insertions(+), 1 deletion(-) diff --git a/.DS_Store b/.DS_Store index 2fbbfc417bd53d0ee576c201445351cb20929f79..04837bcd32e03ae22a605457505cfd638ff72da2 100644 GIT binary patch delta 14 VcmZn(XbITRDZ$9Lxl5vo9{?zX1m6Gv delta 14 VcmZn(XbITRDZ$9Hxl5vo9{?zL1l<4t diff --git a/HWFrom1-28-16(Merge Sort).playground/Contents.swift b/HWFrom1-28-16(Merge Sort).playground/Contents.swift index 83c4706..70e5834 100644 --- a/HWFrom1-28-16(Merge Sort).playground/Contents.swift +++ b/HWFrom1-28-16(Merge Sort).playground/Contents.swift @@ -30,4 +30,81 @@ array // [2, 1] Challenge: Modify your implementation to work for any array of Comparable elements -*/ \ No newline at end of file +*/ + +// Insertion sort +//func insertionSort(var numberList: [Int]) { +// var x, y, key: Int +// for (x = 0; x < numberList.count; x++) { +// key = numberList[x] +// for (y = x; y > -1; y--) { +// if (key < numberList[y]) { +// numberList.removeAtIndex(y + 1) +// numberList.insert(key, atIndex: y) +// } +// } +// } +//} + +/* +func insertionSort(inout values: [Int], first: Int, last: Int) { + if (first < last) { + // sort all but not the last element + insertionSort(&values, first: first, last: last - 1) + // insert the last element in sorted order from the first through the last position + insertInOrder(values[last], values: values, first: first, last: last - 1) + } +} + +func insertionSort(inout values: [Int]) { + insertionSort(&values, first: 0, last: values.count - 1) +} + +func insertInOrder(key: Int, var values: [Int], first: Int, last: Int) { + if key >= values[last] { + values[last + 1] = key + } else if (first < last) { //if key < value[last] + values[last + 1] = values[last] + insertInOrder(key, values: values, first: first, last: last - 1) + } else { // first == last and element < values[last] + values[last + 1] = values[last] + values[last] = key + } +} + + +var arr = [2, 7, 9] +insertionSort(&arr) +*/ +/* +func select(xs: [Int], startingAt k: Int) -> Int { + var minIndex = k + for i in (k+1).. [Int] { + for sortedSoFar in 0.. Date: Thu, 4 Feb 2016 18:58:38 -0500 Subject: [PATCH 27/31] 01/31/16 --- .DS_Store | Bin 10244 -> 10244 bytes .../Contents.swift | 60 +++++++++++++----- 2 files changed, 45 insertions(+), 15 deletions(-) diff --git a/.DS_Store b/.DS_Store index efa1314b4851292d5ba9e00fa3268dc1b2f21065..b7135bd65cea3ebe4c14212b9b9945ce74eb9f05 100644 GIT binary patch delta 50 zcmV-20L}k|P=rvBPXQXSP`eKS8k5ivOq1Xl4wHZw1hZ-orwEgW8E666v+x-g29bbv Ivj-sk2h)oZp8x;= delta 66 zcmZn(XbG6$&nUeyU^hRb^yCWyK9g68^G$A$VA-4{u$+TYd$N$E Bool, using a built-in Swift Set to manage yo 3) Your company makes a phonebook app, and your users have been complaining about how long it takes to look people’s numbers up. You decide to upgrade your archaic array-based system to a sleek, modern hash map. Write a phonebook class that uses either our HashMap from class or the built in Swift dictionary (your choice). It should implement the protocol below. It needs to support importing from the old array based format which used an array of tuples, like [(“Caleb”, “501-555-1234”), (“Mike”, “212-555-4321”), (“Jenny”, “345-867-5309”)] - +*/ protocol PhoneBookProtocol { mutating func addPerson(name: String, phoneNumber: String) @@ -38,20 +38,50 @@ protocol PhoneBookProtocol { func findPerson(name: String) -> String // Return phone # } -*/ -//a) - - -//b) - - -//c) - - - -//2) - +struct PhoneBook:PhoneBookProtocol, CustomStringConvertible { + + var phonebookDict = [String:String]() + + mutating func addPerson(name: String, phoneNumber: String) { + + + + } + + mutating func removePerson(name: String) { + + + } + + mutating func importFrom(oldPhonebook: [(String, String)]) { + + for i in 0.. String { + + + return name + } + + //Custom String Convertible + var description: String { + + return "{\(phonebookDict)}" + } +} +let oldPhoneBook = [("Caleb", "501-555-1234"), ("Mike", "212-555-4321"), ("Jenny", "345-867-5309")] +var newPhonebook = PhoneBook() +newPhonebook.importFrom(oldPhoneBook) +newPhonebook.description -//3) From 71db86d4c7c2fa6420692b5b8cc8a0437770ca44 Mon Sep 17 00:00:00 2001 From: Xiulan Shi Date: Thu, 4 Feb 2016 19:35:52 -0500 Subject: [PATCH 28/31] Updated --- .../Contents.swift | 58 ++++++++++++++++++- 1 file changed, 57 insertions(+), 1 deletion(-) diff --git a/HWFrom1-31-16(Sets and HashMaps).playground/Contents.swift b/HWFrom1-31-16(Sets and HashMaps).playground/Contents.swift index 0416f05..3d55b58 100644 --- a/HWFrom1-31-16(Sets and HashMaps).playground/Contents.swift +++ b/HWFrom1-31-16(Sets and HashMaps).playground/Contents.swift @@ -26,10 +26,28 @@ moderate("Can’t we all just get along?") // true (approve) Write moderate(message: String) -> Bool, using a built-in Swift Set to manage your blacklist. Make your method case insensitive; it should block the word no matter what combination of upper and lowercase letters is used. +let blacklist: Set = ["crapple", "fandroid", "m$"] + +func moderate(message: String) -> Bool { + let words = message.componentsSeparatedByString(" ") + for word in words { + if blacklist.contains(word.lowercaseString) { + return false + } + } + return true +} + +moderate("I would never use a crApple product!") +moderate("something else") + +*/ +/* + 3) Your company makes a phonebook app, and your users have been complaining about how long it takes to look people’s numbers up. You decide to upgrade your archaic array-based system to a sleek, modern hash map. Write a phonebook class that uses either our HashMap from class or the built in Swift dictionary (your choice). It should implement the protocol below. It needs to support importing from the old array based format which used an array of tuples, like [(“Caleb”, “501-555-1234”), (“Mike”, “212-555-4321”), (“Jenny”, “345-867-5309”)] -*/ + protocol PhoneBookProtocol { mutating func addPerson(name: String, phoneNumber: String) @@ -82,6 +100,44 @@ let oldPhoneBook = [("Caleb", "501-555-1234"), ("Mike", "212-555-4321"), ("Jenny var newPhonebook = PhoneBook() newPhonebook.importFrom(oldPhoneBook) newPhonebook.description +*/ + +protocol PhoneBookProtocol { + mutating func addPerson(name: String, phoneNumber: String) + mutating func removePerson(name: String) + mutating func importFrom(oldPhonebook: [(String, String)]) + func findPerson(name: String) -> String? // Return phone # +} + +class PhoneBook: PhoneBookProtocol { + var storage: [String : String] = [:] // @{} + //var storage = Dictionary() + + func addPerson(name: String, phoneNumber: String) { + storage[name] = phoneNumber + } + + func removePerson(name: String) { + storage.removeValueForKey(name) + } + + func findPerson(name: String) -> String? { + return storage[name] + } + + func importFrom(oldPhonebook: [(String, String)]) { + for entry in oldPhonebook { + addPerson(entry.0, phoneNumber: entry.1) + } + } +} + +let oldData = [("Caleb", "501-555-1234"), ("Mike", "212-555-4321"), ("Jenny", "345-867-5309")] + +let phoneBook = PhoneBook() +phoneBook.importFrom(oldData) +phoneBook.findPerson("Jenny") + From b6c7fb2f75fc1fcd9bfef63059f0cb2a80b013f0 Mon Sep 17 00:00:00 2001 From: Xiulan Shi Date: Sun, 7 Feb 2016 15:43:59 -0500 Subject: [PATCH 29/31] Updated --- HWFrom2-05-16(Trees).playground/Contents.swift | 10 ++++++++++ HWFrom2-05-16(Trees).playground/contents.xcplayground | 4 ++++ .../playground.xcworkspace/contents.xcworkspacedata | 7 +++++++ HWFrom2-05-16(Trees).playground/timeline.xctimeline | 6 ++++++ README.md | 4 ++-- 5 files changed, 29 insertions(+), 2 deletions(-) create mode 100644 HWFrom2-05-16(Trees).playground/Contents.swift create mode 100644 HWFrom2-05-16(Trees).playground/contents.xcplayground create mode 100644 HWFrom2-05-16(Trees).playground/playground.xcworkspace/contents.xcworkspacedata create mode 100644 HWFrom2-05-16(Trees).playground/timeline.xctimeline diff --git a/HWFrom2-05-16(Trees).playground/Contents.swift b/HWFrom2-05-16(Trees).playground/Contents.swift new file mode 100644 index 0000000..ca035a2 --- /dev/null +++ b/HWFrom2-05-16(Trees).playground/Contents.swift @@ -0,0 +1,10 @@ +//https://docs.google.com/document/d/1te7mLS06MEYwETFSbVBqMrIzJ43GTEo5uuCiWdB0fyE/edit?usp=drivesdk + + +//1 + + +//Bonus1 + + +//Bonus2 \ No newline at end of file diff --git a/HWFrom2-05-16(Trees).playground/contents.xcplayground b/HWFrom2-05-16(Trees).playground/contents.xcplayground new file mode 100644 index 0000000..5da2641 --- /dev/null +++ b/HWFrom2-05-16(Trees).playground/contents.xcplayground @@ -0,0 +1,4 @@ + + + + \ No newline at end of file diff --git a/HWFrom2-05-16(Trees).playground/playground.xcworkspace/contents.xcworkspacedata b/HWFrom2-05-16(Trees).playground/playground.xcworkspace/contents.xcworkspacedata new file mode 100644 index 0000000..919434a --- /dev/null +++ b/HWFrom2-05-16(Trees).playground/playground.xcworkspace/contents.xcworkspacedata @@ -0,0 +1,7 @@ + + + + + diff --git a/HWFrom2-05-16(Trees).playground/timeline.xctimeline b/HWFrom2-05-16(Trees).playground/timeline.xctimeline new file mode 100644 index 0000000..bf468af --- /dev/null +++ b/HWFrom2-05-16(Trees).playground/timeline.xctimeline @@ -0,0 +1,6 @@ + + + + + diff --git a/README.md b/README.md index 72f8968..e793e5d 100644 --- a/README.md +++ b/README.md @@ -1,2 +1,2 @@ -# unit-4-assignments -Assignments for unit 4 +# units-4-5-assignments +Assignments for units 4 and 5 From eb4399510b191cac2b3114f8b572384fe279744c Mon Sep 17 00:00:00 2001 From: Xiulan Shi Date: Mon, 8 Feb 2016 23:57:59 -0500 Subject: [PATCH 30/31] Updated --- .DS_Store | Bin 10244 -> 10244 bytes .../Contents.swift | 53 +++++++++++++++++- 2 files changed, 52 insertions(+), 1 deletion(-) diff --git a/.DS_Store b/.DS_Store index b7135bd65cea3ebe4c14212b9b9945ce74eb9f05..37b1d86d84fb7b05f969e143281e8f99e1080e93 100644 GIT binary patch delta 279 zcmZn(XbG6$&nUYwU^hRb?BojqK9g68^G$A$U}0m>U|?Y2-CQ7Wijf7#;@)g0v=7YU z*(B1*sw&Um!4S^i#!$qN&ydSt#GuPyz+eg_4H?XUIzxcssSK%;FNjG^&XN={_zwm^ zV;F!+iPV_IpvO?mkOVZ-n8Ac01!%G*(Ckzosmo9TG{&1D8R&vi&z$_^q@4UDpwR+A f?8d;rSb=1n0#VlaNg6ZqZEliuX5GxL@RuC`kI_A~ delta 71 zcmZn(XbG6$&nUGqU^hRb)Z_~SK9ko-@l9@!U}0m>_zwh|3j|IvvVd83Li-@BO(LDF Tn@>yGux@N{V%*HG@RuC`J7*t9 diff --git a/HWFrom2-05-16(Trees).playground/Contents.swift b/HWFrom2-05-16(Trees).playground/Contents.swift index ca035a2..468e551 100644 --- a/HWFrom2-05-16(Trees).playground/Contents.swift +++ b/HWFrom2-05-16(Trees).playground/Contents.swift @@ -7,4 +7,55 @@ //Bonus1 -//Bonus2 \ No newline at end of file +//Bonus2 + +/* + +Using the Swift binary tree implementation below (the Node class), implement a function that takes in a string containing a simple postfix mathematical expression, and returns a binary tree representing that expression using the process described here. + +Required: Build and return the binary tree representation of the expression. The following characters should be treated as operators: +- + +Bonus 1: Print the inorder traversal of the binary tree. +Bonus 2: Evaluate the expression (substituting integers for the letters in the expression). + +Tips: +You may use additional data structures—as suggested in the link above, you will at least want to use a stack. This can be done using the Array type in Swift. +Test your tree by checking to see if the string returned by postorderDescription is equal to the input string. + +Sample input: +"ab+cde+**" + +Template for the function you should implement: +func parseExpression(input: String) -> Node? { + // Your implementation here! + let operators: Set = ["+", "-", "*", "/"] + var stack: [Node] = [] + for character in input.characters { + // Do something for each character + } + return nil +} + +Binary tree implementation: +class Node { + let value: T + var left: Node? + var right: Node? + init(value: T) { + self.value = value + } +} + +extension Node: CustomStringConvertible { + var description: String { + return "\(value)" + } + var postorderDescription: String { + let lt = left?.postorderDescription ?? "" + let rt = right?.postorderDescription ?? "" + return lt + rt + description + } +} + + +*/ \ No newline at end of file From 27893920e3922e000cbd875f2eb0fd3e8eb4d4d7 Mon Sep 17 00:00:00 2001 From: Xiulan Shi Date: Mon, 8 Feb 2016 23:59:31 -0500 Subject: [PATCH 31/31] Updated --- .../Contents.swift | 67 ++++++++++++++++++- 1 file changed, 66 insertions(+), 1 deletion(-) diff --git a/HWFrom2-05-16(Trees).playground/Contents.swift b/HWFrom2-05-16(Trees).playground/Contents.swift index 468e551..a0c3e71 100644 --- a/HWFrom2-05-16(Trees).playground/Contents.swift +++ b/HWFrom2-05-16(Trees).playground/Contents.swift @@ -58,4 +58,69 @@ extension Node: CustomStringConvertible { } -*/ \ No newline at end of file +*/ + +//: Playground - noun: a place where people can play + +import UIKit +import Foundation + +indirect enum Tree { + case Node(Int, left: Tree, right: Tree) + case Empty +} + +func printTree(tree: Tree, label: String = "t") -> String { + switch(tree) { + case let .Node(x, left, right): + var ret = "" + switch (left) { + case .Node: ret += "\(label) -> \(label)l\n" + case .Empty: ret += "\(label) -> \(label)L\n\(label)L[shape=point]\n" + } + switch (right) { + case .Node: ret += "\(label) -> \(label)r\n" + case .Empty: ret += "\(label) -> \(label)R\n\(label)R[shape=point]\n" + } + ret += "\(label)[label=\"\(x)\"]\n" + return ret + printTree(left, label: label + "l") + + printTree(right, label: label + "r") + case .Empty: + return "" + } +} + +func generateTree(depth: UInt32 = 10) -> Tree { + if (arc4random_uniform(depth) == 0) { + return Tree.Empty + } else { + return Tree.Node(Int(arc4random_uniform(100)), + left: generateTree(depth - 1), + right: generateTree(depth - 1)) + } +} + +// To show the tree, uncomment this and copy and paste the output into +// http://www.webgraphviz.com/ (or your local GraphViz installation) +//print("digraph g {\n" + printTree(tree) + "}") + +func dfs(tree: Tree, needle: Int) -> Bool { + switch (tree) { + case let .Node(value, left: left, right: right): + if value == needle { + return true + } else { + return dfs(left, needle: needle) || dfs(right, needle: needle) + } + case .Empty: + return false + } +} + +//let tree = Tree.Node(28, left: Tree.Empty, right: Tree.Empty) + +let tree = generateTree(8) + +print("diagraph g {\n" + printTree(tree) + "}") + +dfs(tree, needle: 18)