Guest User

Untitled

a guest
Jun 17th, 2018
80
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.53 KB | None | 0 0
  1. # Question 1
  2. ```swift
  3. import UIKit
  4.  
  5. var firstArray = ["A","B","C","D","E"]
  6. var secondArray: [String] = ["A","E", "D"]
  7.  
  8.  
  9. func isSubset(firstArray: [String], secondArray: [String]) -> Bool {
  10.  
  11. for character in secondArray {
  12. if !firstArray.contains(character) {
  13. return false
  14. }
  15. }
  16. return true
  17. }
  18. ```
  19.  
  20. # Question 2
  21. The computational complexity to the answer in Problem 1 is O(n^2) as there is a nested loop when each character in the second array is being traversed. The second loop itself traverses each element in the first array.
  22.  
  23. # Question 3
  24. ```swift
  25. import UIKit
  26.  
  27. var fibonnaciSeq: [Int] = [1, 1]
  28.  
  29. func computeFibonnacci(request: Int) {
  30. var lastIndex = fibonnaciSeq.endIndex - 1
  31. var secondLastIndex = lastIndex - 1
  32. while fibonnaciSeq[lastIndex] <= request {
  33. let nextFB = fibonnaciSeq[lastIndex] + fibonnaciSeq[secondLastIndex]
  34. fibonnaciSeq.append(nextFB)
  35. lastIndex += 1
  36. secondLastIndex += 1
  37. }
  38. }
  39.  
  40. func nextFibonnacci(requests: [Int]) {
  41.  
  42. for request in requests {
  43.  
  44. if fibonnaciSeq.contains(request) && fibonnaciSeq.index(of: request) != fibonnaciSeq.last! {
  45. let nextFB = fibonnaciSeq[fibonnaciSeq.index(of: request)! + 1]
  46. print(nextFB)
  47. }
  48.  
  49. if fibonnaciSeq.contains(request) && fibonnaciSeq.index(of: request) == fibonnaciSeq.last! {
  50. computeFibonnacci(request: request)
  51. if let lastItem = fibonnaciSeq.last {
  52. print(lastItem)
  53. }
  54. }
  55.  
  56. if !fibonnaciSeq.contains(request) {
  57. if request > fibonnaciSeq.last! {
  58. computeFibonnacci(request: request)
  59. print(fibonnaciSeq.last!)
  60. } else {
  61. for number in fibonnaciSeq {
  62. if number > request {
  63. print(number)
  64. break
  65. }
  66. }
  67. }
  68. }
  69. }
  70. }
  71. ```
  72. # Question 4
  73. ```javascript
  74. function createArrayOfFunctions(y) {
  75. var arr = [];
  76. for(var i = 0; i<y; i++) {
  77. arr[i] = function(x) { return x + i; }
  78. }
  79. return arr; }
  80. ```
  81.  
  82. For this problem, x is not well-defined. To fix the problem define an in-scope variable called x like so:
  83. ```javascript
  84. function createArrayOfFunctions(y) {
  85. var arr = [];
  86. var x = c;
  87. for(var i = 0; i<y; i++) {
  88. arr[i] = function(x) { return x + i; }
  89. }
  90. return arr; }
  91. ```
  92.  
  93. where c itself is an integer.
Add Comment
Please, Sign In to add comment