Created
February 8, 2016 05:27
-
-
Save alonecuzzo/a924a5240f7d3067e2ba to your computer and use it in GitHub Desktop.
snail
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
//convert to ruby | |
//: Playground - noun: a place where people can play | |
import UIKit | |
let result = [1, 2, 3, 4, 5, 10, 15, 20, 25, 24, 23, 22, 21, 16, 11, 6, 7, 8, 9, 14, 19, 18, 17, 12, 13] | |
enum Direction { | |
case Right, Left, Up, Down | |
func nextDirection() -> Direction { | |
switch self { | |
case .Right: | |
return .Down | |
case .Down: | |
return .Left | |
case .Up: | |
return .Right | |
case .Left: | |
return .Up | |
} | |
} | |
} | |
//test([[1, 2, 3, 4, 5], [6, 7, 8, 9, 10], [11, 12, 13, 14, 15], [16, 17, 18, 19, 20], [21, 22, 23, 24, 25]], [1, 2, 3, 4, 5, 10, 15, 20, 25, 24, 23, 22, 21, 16, 11, 6, 7, 8, 9, 14, 19, 18, 17, 12, 13]) | |
func snail(array: [[Int]]) -> [Int] { | |
var ary: [Int] = [] | |
var currentDirection = Direction.Right | |
let aryLength = array.count * array.count | |
var counter = 0 | |
var row = 0 | |
var col = 0 | |
let width = array.count | |
let height = array.count | |
var widthOffset = 0 | |
var heightOffset = 0 | |
var numTurns = 0 | |
while counter < aryLength { | |
switch currentDirection { | |
case .Right: | |
ary.insert(array[row][col], atIndex: counter) | |
col++ | |
widthOffset = (numTurns > 3) ? 1 : 0 | |
if col == width - widthOffset { | |
currentDirection = currentDirection.nextDirection() | |
numTurns++ | |
//when we change the direction increment row! | |
row++ | |
col-- | |
} | |
case .Down: | |
ary.insert(array[row][col], atIndex: counter) | |
row++ | |
heightOffset = (numTurns > 3) ? 1 : 0 | |
if row == height - heightOffset { | |
currentDirection = currentDirection.nextDirection() | |
numTurns++ | |
col-- | |
row-- | |
} | |
break | |
case .Left: | |
ary.insert(array[row][col], atIndex: counter) | |
col-- | |
if col == -1 + widthOffset { | |
currentDirection = currentDirection.nextDirection() | |
numTurns++ | |
col++ | |
row-- | |
} | |
break | |
case .Up: | |
ary.insert(array[row][col], atIndex: counter) | |
row-- | |
if row == 0 + widthOffset { | |
currentDirection = currentDirection.nextDirection() | |
numTurns++ | |
row++ | |
col++ | |
} | |
break | |
} | |
counter++ | |
} | |
return ary | |
} | |
snail([[1, 2, 3, 4, 5], [6, 7, 8, 9, 10], [11, 12, 13, 14, 15], [16, 17, 18, 19, 20], [21, 22, 23, 24, 25]]) == result |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment