# HG changeset patch # User Jordi GutiƩrrez Hermoso # Date 1513471522 18000 # Node ID 70937ca0e7ebbce2cd65cd38f8a367cc3527f700 # Parent 1b739c38298064ee1c40a9fdafe71b4c997d770a day 14: part 2 diff --git a/2017/day14.d b/2017/day14.d --- 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); }