Skip to content

Instantly share code, notes, and snippets.

@simonbromberg
Created May 28, 2015 22:27
Show Gist options
  • Save simonbromberg/e2931424cc2c046d4443 to your computer and use it in GitHub Desktop.
Save simonbromberg/e2931424cc2c046d4443 to your computer and use it in GitHub Desktop.
SwiftSpiral
import UIKit
enum Dimension {
case X, Y
}
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
var out = buildSpiral(12)
for i in 0..<out.count {
printLine(out[i])
}
}
func printLine(line: [Bool]) {
let asterisk = "*"
let space = " "
var output = ""
for i in 0..<line.count {
output += line[i] ? asterisk : space
}
println(output)
}
func buildSpiral(size: Int) -> [[Bool]] {
var spiral: [[Bool]] = []
for i in 0..<size {
var row: [Bool] = []
for i in 0..<size {
row += [false]
}
spiral += [row]
}
var position: (x: Int, y: Int) = (0,0)
var maxDim = size - 1
var activeDimension = Dimension.X
var direction = 1
var count = 0
while maxDim > 0 {
for i in 0...maxDim {
spiral[position.y][position.x] = true
if i != maxDim {
if activeDimension == Dimension.X {
position.x = position.x + direction
}
else {
position.y = position.y + direction
}
}
}
if activeDimension == Dimension.X {
activeDimension = Dimension.Y
}
else {
activeDimension = Dimension.X
}
if ++count % 2 == 0 {
direction *= -1
maxDim-=2
}
}
return spiral
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment