changeset 1:772b9f146b20

day 2
author Jordi Gutiérrez Hermoso <jordigh@octave.org>
date Thu, 07 Dec 2017 11:44:51 -0500
parents 0fa6cd63af21
children 4620ff0a058c
files 2017/02/app.d
diffstat 1 files changed, 57 insertions(+), 0 deletions(-) [+]
line wrap: on
line diff
new file mode 100644
--- /dev/null
+++ b/2017/02/app.d
@@ -0,0 +1,57 @@
+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);
+}