Created
December 28, 2017 17:26
-
-
Save anonymous/bc528ced2cb4faeede915f1f8d0211ee to your computer and use it in GitHub Desktop.
Snippet from https://play.nim-lang.org
This file contains 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 strutils, tables, sequtils | |
const | |
instructions = readFile("./inputs/21.txt").splitLines | |
start = ".#./..#/###" | |
var | |
mappings = initTable[seq[string], seq[string]]() | |
seen = initTable[seq[string], seq[string]]() | |
proc flip(s: seq[string]): seq[string] = | |
result = s | |
result[0] = s[^1] | |
result[^1] = s[0] | |
proc transpose(s: seq[string]): seq[string] = | |
result = s | |
for i in 0 .. s.high: | |
for j in 0 .. s.high: | |
result[j][i] = s[i][j] | |
iterator transform(s: seq[string]): seq[string] = | |
for a in [s, s.flip]: | |
let | |
b = a.transpose | |
c = b.flip | |
d = c.transpose | |
yield a; yield b; yield c; yield d | |
for line in instructions: | |
let | |
divided = line.strip.split(" => ") | |
source = divided[0].split('/') | |
dest = divided[1].split('/') | |
for src in source.transform: | |
mappings[src] = dest | |
proc getSquare(grid: seq[string], i, j, by: int): seq[string] = | |
result = newSeqWith(by, newString(by)) | |
var row = 0 | |
for x in i ..< i+by: | |
result[row] = grid[x][j ..< j+by] | |
inc row | |
proc findNext(grid: seq[string]): seq[string] = | |
let | |
size = grid.len | |
by = if size mod 2 == 0: 2 else: 3 | |
newSize = size * (by+1) div by | |
result = newSeqWith(newSize, newString(newSize)) | |
for i in countup(0, size-1, by): | |
for j in countup(0, size-1, by): | |
let | |
square = grid.getSquare(i, j, by) | |
enhanced = mappings[square] | |
for x, row in enhanced: | |
for y, c in row: | |
result[(i*(by+1) div by) + x][(j*(by+1) div by) + y] = c | |
proc findNew9x9(grid: seq[string]): seq[string] = | |
result = grid | |
if grid notin seen: | |
for _ in 1 .. 3: | |
result = result.findNext | |
seen[grid] = result | |
return seen[grid] | |
proc pixelsOn(grid: seq[string]): int = | |
for r in grid: | |
for c in r: | |
if c == '#': | |
inc result | |
var grid = start.split("/") | |
for _ in 1 .. 5: | |
grid = grid.findNext | |
echo grid.pixelsOn | |
grid = grid.findNext | |
proc expand(grid: seq[string]): seq[string] = | |
let size = grid.len | |
result = newSeqWith(3*size, newString(3*size)) | |
for i in countup(0, size-1, 3): | |
for j in countup(0, size-1, 3): | |
let | |
square = grid.getSquare(i, j, 3) | |
sqSol = square.findNew9x9 | |
for x, row in sqSol: | |
for y, c in row: | |
result[3*i + x][3*j + y] = c | |
for _ in 1 .. (18 - 6) div 3: | |
grid = grid.expand | |
echo grid.pixelsOn |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment