This is a 100% scoring solution to the Codility StoneWall problem. Note the bunch of print statements which I've left included for now.
//: https://codility.com/programmers/task/stone_wall/ import UIKit
public func solution1(inout H : [Int]) -> Int { var stack: [Int] = [] var nBlocks = 0 var i = 0 var lastHeight = 0 func append(height: Int) { print("append \(height)") stack.append(height) lastHeight = height nBlocks += 1 } while i < H.count { let currHeight = H[i] print("i=\(i), currHeight=\(currHeight)") if i == 0 { append(currHeight) } else { if currHeight == lastHeight { print("currHeight == lastHeight") } else if currHeight > lastHeight { append(currHeight) } else { // currHeight < lastHeight // Keep popping stack.popLast() var found = false while !stack.isEmpty { let lastAppendedHeight = stack.last! if lastAppendedHeight == currHeight { print("lastAppendedHeight == currHeight == \(currHeight)") lastHeight = currHeight found = true break } else if lastAppendedHeight < currHeight { print("break") break } print("popLast") stack.popLast() } if !found { append(currHeight) } } } i += 1 } return nBlocks }
var H = [8,8,5,7,9,8,7,4,8] H = [1,2,3,4,5] H = [1,1,1,1,1,1,1,1,1] H = [1,2,3,3,3,2,2,2,2,2,1] H = [5,4,3,2,1] H = [1,2,1,2,1,2]
solution1(&H)