Skip to content

Instantly share code, notes, and snippets.

@boone
Created December 6, 2015 14:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save boone/2c2b9d25991f3bd33135 to your computer and use it in GitHub Desktop.
Save boone/2c2b9d25991f3bd33135 to your computer and use it in GitHub Desktop.
// http://adventofcode.com/day/1 - part 1
//
// instructions - String containing coded instructions for moving up a floor with
// "(" and down a floor with ")"
// Starting ground floor numbered zero is assumed.
// Returns an integer value for the expected floor.
func upsAndDowns(instructions: String) -> Int {
var floor: Int = 0
for character in instructions.characters {
if character == "(" {
floor += 1
} else if character == ")" {
floor -= 1
}
}
return floor
}
// http://adventofcode.com/day/1 - part 2
//
// instructions - String containing coded instructions for moving up a floor with
// "(" and down a floor with ")"
// Starting ground floor numbered zero is assumed.
// Also assuming that the first character of the instructions is considered
// instruction #1 (not zero).
//
// Returns an integer value for the first instruction that leads to the basement
// (floor -1), or nil if it did not ever lead there.
func inTheBasement(instructions: String) -> Int? {
var floor: Int = 0
for (index, character) in instructions.characters.enumerate() {
if character == "(" {
floor += 1
} else if character == ")" {
floor -= 1
}
if floor == -1 {
return index + 1
}
}
return nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment