view 2017/day02.d @ 3:b5533de6ff5b

move all app.d's to top level
author Jordi Gutiérrez Hermoso <jordigh@octave.org>
date Thu, 07 Dec 2017 11:44:52 -0500
parents 2017/02/app.d@772b9f146b20
children
line wrap: on
line source

import std.stdio;
import std.array: array;
import std.algorithm: map, maxElement, minElement;
import std.string: split;
import std.conv: to;
import std.traits: isNumeric;

auto tokenize(numType, lineType)(lineType line)
  if(isNumeric!numType)
{
  return line.split.map!(x => to!numType(x)).array;
}

numType part1(numType, lineType)(lineType spreadsheet)
  if(isNumeric!numType)
{
  numType checksum = 0;
  foreach(line; spreadsheet) {
    checksum += line.maxElement - line.minElement;
  }
  return checksum;
}

numType part2(numType, lineType)(lineType spreadsheet)
  if(isNumeric!numType)
{
  numType checksum = 0;
  foreach(line; spreadsheet) {
  nextline:
    foreach(idx, x; line) {
      foreach (y; line[idx+1..$]) {
        if (x % y == 0) {
          checksum += x/y;
          continue nextline;
        }
        if (y % x == 0) {
          checksum += y/x;
          continue nextline;
        }
      }
    }
  }
  return checksum;
}

void main(string[] args) {
  alias numType = int;
  auto spreadsheet =
    File(args[1])
    .byLineCopy
    .array
    .map!(line => tokenize!numType(line));
  auto result1 = part1!numType(spreadsheet);
  auto result2 = part2!numType(spreadsheet);
  writeln(result1);
  writeln(result2);
}