Last active
December 9, 2019 15:51
-
-
Save groob/6e8514d1128d9ae810b57af07355087a to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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: "") | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment