Skip to content

Instantly share code, notes, and snippets.

@ProbablyRusty
Last active June 19, 2017 15:08
Show Gist options
  • Save ProbablyRusty/f4af1ec40450f36b630263339e092a91 to your computer and use it in GitHub Desktop.
Save ProbablyRusty/f4af1ec40450f36b630263339e092a91 to your computer and use it in GitHub Desktop.
Swift Spiral Ascension
// In reference to:
// https://www.reddit.com/r/dailyprogrammer/comments/6i60lr/20170619_challenge_320_easy_spiral_ascension/
let input = 5
enum Direction {
case right, down, left, up
mutating func turn() {
switch self {
case .right:
self = .down
case .down:
self = .left
case .left:
self = .up
case .up:
self = .right
}
}
}
struct Matrix {
let rows, columns: Int
var grid: [Int]
init(rows: Int, columns: Int) {
self.rows = rows
self.columns = columns
self.grid = Array(repeating: 0, count: rows * columns)
}
func isValid(_ row: Int, _ column: Int) -> Bool {
return row >= 0 && column >= 0 && row < rows && column < columns && self[row, column] == 0
}
subscript(row: Int, column: Int) -> Int {
get { return grid[(row * columns) + column] }
set { grid[(row * columns) + column] = newValue }
}
}
func advance(_ row: Int, _ column: Int) -> (row: Int, column: Int) {
var row = row
var column = column
switch currentDirection {
case .right:
column += 1
case .down:
row += 1
case .left:
column -= 1
case .up:
row -= 1
}
return (row, column)
}
func numberOfDigits(in num: Int) -> Int {
if num < 10 {
return 1
} else {
return 1 + numberOfDigits(in: num/10)
}
}
func padding(for num: Int) -> String {
let longestIntLength = numberOfDigits(in: input * input)
let currentIntLength = numberOfDigits(in: num)
return String(repeating: " ", count: longestIntLength - currentIntLength)
}
var matrix = Matrix(rows: input, columns: input)
var currentDirection: Direction = .right
var currentRow = 0, currentColumn = 0
for index in 0..<input*input {
matrix[currentRow, currentColumn] = index + 1
let possible = advance(currentRow, currentColumn)
if matrix.isValid(possible.row, possible.column) {
currentRow = possible.row
currentColumn = possible.column
} else {
currentDirection.turn()
let alternate = advance(currentRow, currentColumn)
currentRow = alternate.row
currentColumn = alternate.column
}
}
for row in 0..<matrix.rows {
for column in 0..<matrix.columns {
print("\(matrix[row, column]) ", terminator: padding(for: matrix[row, column]))
}
print("")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment