Created
May 28, 2015 22:27
-
-
Save simonbromberg/e2931424cc2c046d4443 to your computer and use it in GitHub Desktop.
SwiftSpiral
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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