view 2017/day14.d @ 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
line wrap: on
line source

import std.stdio;
import std.algorithm: map, sum;
import std.range: join;
import std.format: format;

import day10: calcHash, getHash;

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) {
  auto bitmap = getBitMap(args[1]);
  writeln(bitmap.map!(sum).sum);
  writeln(bitmap.countRegions);
}