Skip to content

Instantly share code, notes, and snippets.

@groob
Last active December 9, 2019 15:51
Show Gist options
  • Save groob/6e8514d1128d9ae810b57af07355087a to your computer and use it in GitHub Desktop.
Save groob/6e8514d1128d9ae810b57af07355087a to your computer and use it in GitHub Desktop.

Revisions

  1. groob revised this gist Dec 9, 2019. 1 changed file with 47 additions and 0 deletions.
    47 changes: 47 additions & 0 deletions Readable.swift
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,47 @@
    import Foundation

    enum Pixel: Int {
    case black = 0
    case white = 1
    case transparent = 2
    }

    func makeLayers(_ input: String, size: Int) -> [[Pixel]] {
    var layers = Array(repeating: [Pixel](), count: input.count / size)
    for (i, char) in input.enumerated() {
    let pixel = Pixel(rawValue: Int(String(char))!)!
    layers[i / size].append(pixel)
    }
    return layers
    }

    func flatten(_ layers: [[Pixel]], size: Int) -> [Pixel] {
    var image = Array(repeating: Pixel.transparent, count: size)
    layers.forEach { layer in
    for (i, pixel) in layer.enumerated() {
    if pixel != .transparent && (image[i] == .transparent) {
    image[i] = pixel
    }
    }
    }
    return image
    }

    func printImage(_ pixels: [Pixel], width: Int) {
    for (i, pixel) in pixels.enumerated() {
    if i != 0 && i % width == 0 { print("") }
    print(pixel == .white ? "" : " ", terminator: "")
    }
    }

    let width = 25
    let height = 6
    let size = width * height

    let input = try
    String(contentsOfFile: "data.txt")
    .trimmingCharacters(in: .whitespacesAndNewlines)

    let layers = makeLayers(input, size: size)
    let image = flatten(layers, size: size)
    printImage(image, width: width)
  2. groob created this gist Dec 9, 2019.
    34 changes: 34 additions & 0 deletions Advent of Code Day 8.swift
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,34 @@
    import Foundation

    enum Pixel: Int {
    case black = 0
    case white = 1
    case transparent = 2
    }

    let width = 25
    let height = 6
    let size = width * height

    let input = try
    String(contentsOfFile: "data.txt")
    .trimmingCharacters(in: .whitespacesAndNewlines)

    input
    .enumerated()
    .reduce(into: Array(repeating: [Pixel](), count: input.count / size)) { partial, current in
    let pixel = Pixel(rawValue: Int(String(current.1))!)!
    partial[current.0 / size].append(pixel)
    }
    .reduce(into: Array(repeating: Pixel.transparent, count: size)) { partial, layer in
    for (idx, pixel) in layer.enumerated() {
    if pixel != .transparent && (partial[idx] == .transparent) {
    partial[idx] = pixel
    }
    }
    }
    .enumerated()
    .forEach {
    if $0.0 != 0 && $0.0 % width == 0 { print("") }
    print($0.1 == .white ? "" : " ", terminator: "")
    }