Skip to content

Instantly share code, notes, and snippets.

@junebash
Last active October 9, 2019 19:03
Show Gist options
  • Save junebash/2f9574686caac0fd2c0132a47a470bd1 to your computer and use it in GitHub Desktop.
Save junebash/2f9574686caac0fd2c0132a47a470bd1 to your computer and use it in GitHub Desktop.
Unit 1 Sprint 2 Swift Coding Challenge (2019-10-09 Wed)
// INCOMPLETE AS OF 2019-10-09 08:46
func heightChecker(_ heights: [Int]) -> Int {
// handle invalid list length
if heights.count < 1 || heights.count > 100 {
print("List is too long or short; must have between 1 and 100 students (inclusive).")
return 0
}
var wrongStudents: [(index: Int, height: Int)] = []
var lastCorrectStudent: (index: Int, height: Int) = (index: -1, height: 0)
for i in 0 ..< heights.count - 1 {
let currentStudent = (index: i, height: heights[i])
// handle invaild heights
if currentStudent.height < 1 || currentStudent.height > 100 {
print("Student at array index \(i) is too tall or short; height must be between 1 and 100 (inclusive).")
return 0
}
if currentStudent.height < lastCorrectStudent.height || currentStudent.height > heights[i + 1] {
print("Student in wrong spot!")
wrongStudents.append(currentStudent)
} else {
lastCorrectStudent = currentStudent
}
}
print("Student array: \(heights)")
print("Wrong students: \(wrongStudents)")
print("Wrong students count: \(wrongStudents.count)")
return wrongStudents.count
}
heightChecker([1,1,4,2,1,3])
//
// correct (?) implementation found ~10 minutes later
//
func simpleHeightChecker(_ heights: [Int]) -> Int {
// handle invalid list length
if heights.count < 1 || heights.count > 100 {
print("List is too long or short; must have between 1 and 100 students (inclusive).")
return 0
}
let sortedHeights = heights.sorted()
var numWrongStudents = 0
for i in 0 ..< heights.count {
let currentStudentHeight = heights[i]
// handle wrong heights
if currentStudentHeight < 1 || currentStudentHeight > 100 {
print("Height of student at index \(i) is too low or high; must be between 1 and 100 (inclusive).")
return 0
}
if heights[i] != sortedHeights[i] {
numWrongStudents += 1
}
}
return numWrongStudents
}
print(simpleHeightChecker([1,1,4,2,1,3]))
@vicxruiz
Copy link

vicxruiz commented Oct 9, 2019

So close! Great error handling though!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment