Skip to content

Instantly share code, notes, and snippets.

@vukcevich
Created August 16, 2017 18:52
Show Gist options
  • Select an option

  • Save vukcevich/2c084a15b850ca35b13f9e2ea8e31021 to your computer and use it in GitHub Desktop.

Select an option

Save vukcevich/2c084a15b850ca35b13f9e2ea8e31021 to your computer and use it in GitHub Desktop.
Recursion - recursive functions - swift.
/*
Things to 'remember' about recursion:
--- you can call a function inside of itself
--- you always have at least "ONE BASE CASE" in order to prevent the function calling itself infinite times.
*/
func fibonacci(_ i: Int) -> Int {
if i <= 2 {
return 1
} else {
return fibonacci(i - 1) + fibonacci(i - 2)
}
}
func factorial(_ N: Int) -> Int {
if N == 1 {
return 1
} else {
return N * factorial(N - 1)
}
}
func digits(_ number:Int) -> [Int] {
if number >= 10 {
let firstDigit = digits(number / 10)
let lastDigit = number % 10
return firstDigit + [lastDigit]
} else {
return [number]
}
}
func pow(_ x: Int, _ y: Int) -> Int {
if y == 0 {
return 1
} else {
return x * pow(x, y - 1)
}
}
func euclidian(_ a: Int, _ b: Int) -> Int {
if b == 0 {
return a
} else {
if a > b {
return euclidian(a - b, b)
} else {
return euclidian(a, b - a)
}
}
}
func binarySearch(_ key:Int, _ numbers:[Int], left:Int = 0, right:Int = -1) -> Bool {
var right = right
if right == -1 {
right = numbers.count - 1
}
if left < right {
print(#line, "left:", left, "-right:", right)
var mid = (left + right) / 2
print(#line, "mid: ", mid)
if key < numbers[mid] {
return binarySearch(key, numbers, left: left, right: mid)
} else if key > numbers[mid] {
return binarySearch(key, numbers, left: mid + 1, right: right)
} else {
return true
}
} else {
return numbers[left] == key
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment