Skip to content

Instantly share code, notes, and snippets.

@joanmolinas
Last active August 29, 2015 14:18
Show Gist options
  • Save joanmolinas/5772f0a204cc735bb84d to your computer and use it in GitHub Desktop.
Save joanmolinas/5772f0a204cc735bb84d to your computer and use it in GitHub Desktop.
// Fibonacci is a Struct that generate an Infinite Array from Fibonacci Numbers.
// Fibonacci include a functions with calculate a positions from the Fibonacci Sequence, plus two numbers from this and
// The max number will be 2,147,483,647. It's the maximum number from Int.
// If want generate number more bigger than 2,147,483,647, you can use Int64 I think.
extension Fibonacci {
func numberAtIndex (index : Int) -> Int {
return ^^index
}
func plusTwoNumbers(posOne pos : Int, posTwo pos2 : Int) -> Int? {
return pos <= 1 || pos2 <= 1 ? nil : pos^+^pos2
}
}
extension Fibonacci : CollectionType {
var startIndex : Int { return 0 }
var endIndex : Int { return backing.count }
subscript (index : Int) -> Int {
let result = ^^index
assert(result < Int.max, "Result is out of range Int")
return result
}
subscript (range : Range<Int>) -> [Int] {
var array = [Int]()
for i in range {
array.append(self[i])
}
return array
}
}
struct Fibonacci : SequenceType {
private var backing = [Int : Int]()
var isEmpty : Bool { return backing.isEmpty }
var last : Int { return self.backing[backing.count]! }
var count : Int { return backing.count }
typealias Generator = GeneratorOf<Int>
func generate() -> Generator {
var index = 0
return GeneratorOf {
if index < self.backing.count {
return self.backing[index++]
}
return nil
}
}
}
prefix operator ^^ {}
prefix func ^^ (rhs : Int) -> Int { return rhs < 0 ? 0 : rhs <= 2 ? 1 : ^^(rhs - 1) + ^^(rhs - 2) }
postfix operator ^^{}
postfix func ^^ (lhs : Int) -> Int { return lhs < 0 ? 0 : lhs <= 2 ? 1 : ^^(lhs - 1) + ^^(lhs - 2) }
infix operator ^+^ { associativity right precedence 140}
func ^+^ (lhs : Int, rhs : Int) -> Int { return ^^rhs + ^^lhs }
//Example Usage
var arr = Fibonacci()
var arr2 = arr[1...10] //OUTPUT -> [1, 1, 2, 3, 5, 8, 13, 21, 34, 55]
arr2.startIndex //OUTPUT -> 0
arr2.last //OUTPUT -> 55
arr2.count //OUTPUT -> 10
arr.numberAtIndex(5) //OUTPUT -> 5
arr.plusTwoNumbers(posOne: 2, posTwo: 3) // OUTPUT -> 3
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment