Skip to content

Instantly share code, notes, and snippets.

@dautermann
Created March 27, 2019 21:38
Show Gist options
  • Save dautermann/eb0c3758eba9687e211d7c7c77118399 to your computer and use it in GitHub Desktop.
Save dautermann/eb0c3758eba9687e211d7c7c77118399 to your computer and use it in GitHub Desktop.
implement Threebonacci
//
// ThreeFibonacciViewController.swift
//
// For the purposes of this problem, a Threebonacci sequence is a twist on the
// Fibonacci sequence where you would sum the previous three elements to get the
// next element. That is, if the Threebonacci function is defined as t, where n is the
// index of the element involved, t(n) = t(n-1) + t(n-2) + t(n-3).
// You can assume t(0) = 0, t(1) = 1, and t(2) = 1. With this information, please
// complete the tableview in the following UIViewController so that each
// UITableViewCell displays its Threebonacci value corresponding with its row index.
// An example is as follows: 0 1 1 2 4 and so on so forth.
import UIKit
class ThreeFibonacciViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
@IBOutlet weak var tableView: UITableView!
var threebonacciArray = [0,1,1]
let totalNumberOfThreebonacci = 1000000
override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self
tableView.dataSource = self
calculateThreebonacci()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return threebonacciArray.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Default", for: indexPath)
// if we need a row that's greater than the number of results in the array,
// we need to calculate
if indexPath.row < threebonacciArray.count
{
cell.textLabel.text = String(threebonacciArray[indexPath.row])
} else {
cell.textLabel.text = "great place to put spinner"
}
return cell
}
func calculateThreebonacci() {
DispatchQueue.global(qos: .background).async { [weak self] in
for index in 3...totalNumberOfThreebonacci {
let tNminusThree = self?.threeebonacciArray[index-3] ?? 0
let tNminusTwo = self?.threebonacciArray[index-2]
let tNminusOne = self?.threebonacciArray[index-1]
let newResult = tNminusThree + tNminusTwo + tNminusOne
self?.threebonacciArray.append(newResult)
// insert row if the bottom of the table view is visible
}
// or get to end of calculating and reloadData on the table
DispatchQueue.main.async {
self?.tableView.reloadData()
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment