Skip to content

Instantly share code, notes, and snippets.

@dimpiax
Created November 23, 2016 13:54
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 dimpiax/bf3df197996565a710f31fedfe09f5eb to your computer and use it in GitHub Desktop.
Save dimpiax/bf3df197996565a710f31fedfe09f5eb to your computer and use it in GitHub Desktop.
let input = [
"1 1 1 0 0 0",
"0 1 0 0 0 0",
"1 1 1 0 0 0",
"0 0 2 4 4 0",
"0 0 0 2 0 0",
"0 0 1 2 4 0"
]
let scanner = [
"1 1 1",
"0 1 0",
"1 1 1"
]
struct Matrix {
let value: [[Int8]]
let rows: Int
let cols: Int
init(input: [String]) {
value = input.map { value in value.characters.split(separator: " ").map { Int8(String($0))! } }
rows = value[0].count
cols = value.count
}
init(input: [[Int8]]) {
value = input
rows = input[0].count
cols = input.count
}
func scan(_ input: Matrix, offset: (Int, Int)) -> Matrix {
let inputArr = input.value
let offsetX = Int(offset.0), offsetY = Int(offset.1)
// scan here
var scannedArr = [[Int8]]()
for y in 0..<rows {
let patternRow = value[y]
let row = inputArr[offsetY+y]
var scannedRow = [Int8]()
for x in 0..<cols where patternRow[x] != 0 {
let scannedValue = row[offsetX+x]
scannedRow.append(scannedValue)
}
scannedArr.append(scannedRow)
}
return Matrix(input: scannedArr)
}
}
func scan(matrix: Matrix, pattern: Matrix) -> [Matrix] {
let w = matrix.rows-pattern.rows+1
let h = matrix.cols-pattern.cols+1
var examples = [Matrix]()
for y in 0..<h {
for x in 0..<w {
examples.append(pattern.scan(matrix, offset: (x, y)))
}
}
return examples
}
let scanned = scan(matrix: Matrix(input: input), pattern: Matrix(input: scanner))
let summed = scanned.map { value in
return value.value.flatMap { $0 }.reduce(0, +)
}
summed.max()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment