Mercurial > hg > aoc
changeset 18:70937ca0e7eb
day 14: part 2
author | Jordi Gutiérrez Hermoso <jordigh@octave.org> |
---|---|
date | Sat, 16 Dec 2017 19:45:22 -0500 |
parents | 1b739c382980 |
children | 6ee82d2c10fa |
files | 2017/day14.d |
diffstat | 1 files changed, 42 insertions(+), 9 deletions(-) [+] |
line wrap: on
line diff
--- a/2017/day14.d +++ b/2017/day14.d @@ -1,18 +1,51 @@ import std.stdio; -import std.bitmanip: BitArray; -import std.array: array; -import std.algorithm; -import std.range: iota; +import std.algorithm: map, sum; +import std.range: join; import std.format: format; import day10: calcHash, getHash; -auto countBits(string input) { - return iota(0,128).map!( - i => BitArray(format("%s-%d", input, i).calcHash, 128).bitsSet.array.length - ).sum; +auto getBitMap(string input) { + int[][] bitmap; + foreach(i; 0..128) { + bitmap ~= format("%s-%d", input, i).calcHash[].map!( + function(ubyte x) { + int[] result; + for(auto i = 7; i >= 0; i--) { + result ~= (x & (1 << i)) ? 1 : 0; + } + return result; + } + ).join; + } + return bitmap; +} + +void wipeRegion(ref int[][] bitmap, int i, int j) { + if (i < 0 || j < 0 || i > 127 || j > 127 || bitmap[i][j] == 0) + return; + bitmap[i][j] = 0; + bitmap.wipeRegion(i+1, j); + bitmap.wipeRegion(i-1, j); + bitmap.wipeRegion(i, j+1); + bitmap.wipeRegion(i, j-1); +} + +auto countRegions(int[][] bitmap) { + auto numregions = 0; + foreach(i; 0..128) { + foreach(j; 0..128) { + if(bitmap[i][j]) { + numregions++; + bitmap.wipeRegion(i, j); + } + } + } + return numregions; } void main(string[] args) { - writeln(args[1].countBits); + auto bitmap = getBitMap(args[1]); + writeln(bitmap.map!(sum).sum); + writeln(bitmap.countRegions); }