Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Swift and Big O homework #12

Open
wants to merge 22 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Binary file added .DS_Store
Binary file not shown.
9 changes: 9 additions & 0 deletions 20160124 Homework.playground/Contents.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
//: Playground - noun: a place where people can play

import UIKit

var str = "Hello, playground"

/*

/*
4 changes: 4 additions & 0 deletions 20160124 Homework.playground/contents.xcplayground
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<playground version='5.0' target-platform='ios'>
<timeline fileName='timeline.xctimeline'/>
</playground>

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

6 changes: 6 additions & 0 deletions 20160124 Homework.playground/timeline.xctimeline
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<Timeline
version = "3.0">
<TimelineItems>
</TimelineItems>
</Timeline>
147 changes: 147 additions & 0 deletions 20160124-homework-recursion.playground/Contents.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,147 @@
// Exercises from: https://docs.google.com/document/d/1INvOynuggw69yLRNg3y-TPwBiYb3lQZQiFUOxZKBwsY/edit#

import UIKit
import Foundation

/* 1) 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?

Note: In the Fibonacci sequence, each number is the sum of the two previous numbers.
ie: [0, 1, 1, 2, 3, 5, 8, 13, 21, 34] */

//Appendix A: Recursive Fibonacci from class (non-memoized)
func fib1(n: Int) -> Int {
if (n == 0 || n == 1) {
return 1
}
return fib1(n - 1) + fib1(n - 2)
}
print(fib1(10))
(0...5).map { i in fib1(i) } // create map

// Answer: this non recursive method is waaay faster.

var fibNo = 1
var index = 0

func fib2(numbers: Int) -> Int {

for number in 1...numbers { // loop through numbers 1...10
print("index \(number): \(fibNo)")
let temp = fibNo + index
index = fibNo
fibNo = temp
}
return fibNo
}



print(fib2(10)) // Note: this is actually returning the 11th fib no because the function is starting with a 0 indexed number

/* 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. */

// Original Program:
/*
var stepNum = 0
func tryStep() -> Bool {
let success = Int(arc4random_uniform(2)) > 0 // generate rando number
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()
}
print(stepUp())
*/

// Appendix B:
var steppNum = 0

func tryStepp() -> Int {
let stepCount = Int(arc4random_uniform(3)) - 1 // generate rando number
steppNum += stepCount;

switch(stepCount) {
case -1: print("Ouch \(steppNum)")
case 1: print("Yay \(steppNum)")
default: print("Beep \(steppNum)")
}
return stepCount
}

//// My code:
//func steppUp(var stepsTaken: Int = 0) {
// stepsTaken += tryStepp()
// if stepsTaken == 1 {
// // we're done!
// return
// }
// steppUp(stepsTaken)
//}
//steppUp()

// Cameron's Code:
func stepUp() {
switch tryStepp() {
case 1:
return
case -1:
stepUp()
stepUp()
default:
stepUp()
}
}
stepUp()







































4 changes: 4 additions & 0 deletions 20160124-homework-recursion.playground/contents.xcplayground
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<playground version='5.0' target-platform='ios'>
<timeline fileName='timeline.xctimeline'/>
</playground>

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

6 changes: 6 additions & 0 deletions 20160124-homework-recursion.playground/timeline.xctimeline
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<Timeline
version = "3.0">
<TimelineItems>
</TimelineItems>
</Timeline>
159 changes: 159 additions & 0 deletions 20160128-homework-merge-sort.playground/Contents.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,159 @@
//: Playground - noun: a place where people can play

import Foundation

var str = "Hello, playground"

/*

Use recursion to implement Insertion Sort in Swift:

Requirements:
You may not use loops
Your implementations should be in-place (try not to create additional arrays)
You should implement and use additional helper functions

Tips:
Add additional parameters to your helper functions to pass information between recursive calls
You can use the swap function to exchange two values in a mutable (var) array:

var array = [1, 2]
swap(&array[0], &array[1])
array // [2, 1]

// Insertion Sort from Stack Overflow:
public static int[] RecursiveInsertionSort(int[] array, int n) {
int i;
if (n > 1)
RecursiveInsertionSort(array, n - 1);
else {
int k = array[n];
i = n - 1;
while (i >= 0 & & array[i] > k) {
array[i + 1] = array[i];
i = i - 1;
}
array[i + 1] = k;
}
return array;
}
*/

// regular insertion sort:
func exchange<T>(inout data: [T], i:Int, j:Int) {
let temp:T = data[i]
data[i] = data[j]
data[j] = temp
}

func insertionSort(var unsortedArray:Array<Int>)->Array<Int>{
if(unsortedArray.count<2) {
return unsortedArray
}
for var j = 1; j < unsortedArray.count; j++ {
var i = j
while i>0 && unsortedArray[i-1]>unsortedArray[i] {
exchange(&unsortedArray, i: i-1, j: i)
i--;
}
}
return unsortedArray;
}
insertionSort([3, 4, 5, 1, 2])

// Cameron's notes for homework:
func printAllElements(values: [Int]) {
for value in values {
print(value)
}
}

func printAllElementsRecursive(values: [Int]) {
printElementsHelper(values, index: 0)
}

func printElementsHelper(values: [Int], index: Int) {
if index < values.count {
print(values[index])
printElementsHelper(values, index: index + 1)
}
}

func setValue(inout array: [Int], value: Int, atIndex index: Int) {
array[index] = value
}

var values = [10, 20, 30]
printAllElements(values)

setValue(&values, value: 100, atIndex: 1)
values



func reverse(inout array: [Int]) {
for i in 0..<array.count / 2 {
swap(&array[i], &array[array.count - i - 1])
}
}

reverse(&values)
values


// 2)

let blacklist: Set<String> = ["crapple", "fandroid", "m$"]

func moderate(message: String) -> Bool {

let words = (message as NSString).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)

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<String, String>()
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")

4 changes: 4 additions & 0 deletions 20160128-homework-merge-sort.playground/contents.xcplayground
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<playground version='5.0' target-platform='ios'>
<timeline fileName='timeline.xctimeline'/>
</playground>

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

6 changes: 6 additions & 0 deletions 20160128-homework-merge-sort.playground/timeline.xctimeline
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<Timeline
version = "3.0">
<TimelineItems>
</TimelineItems>
</Timeline>
Loading