changeset 16:990a4fa2aebe

day 10: modularise and debug
author Jordi Gutiérrez Hermoso <jordigh@octave.org>
date Fri, 15 Dec 2017 12:40:11 -0500
parents 817954f71d53
children 1b739c382980
files 2017/day10.d
diffstat 1 files changed, 22 insertions(+), 10 deletions(-) [+]
line wrap: on
line diff
--- a/2017/day10.d
+++ b/2017/day10.d
@@ -19,30 +19,42 @@
   }
 }
 
+auto pos = 0, skip = 0;
 auto knotUp(int Size)(int[] lengths, int[Size] twine) {
-  static pos = 0, skip = 0;
   foreach(length; lengths) {
     reverse(twine, pos, pos+length);
-    pos += length + skip;
-    skip++;
+    pos = (pos + length + skip) % Size;
+    skip = (skip + 1) % Size;
   }
   return twine;
 }
 
-auto getHash(int Size, int Rounds, int ChunkSize)(int[] lengths)
+auto calcHash(int Size=256, int Rounds=64, int ChunkSize=16)(string input)
   if( Size % ChunkSize == 0)
 {
+  int[] lengths = to!(int[])(cast(ubyte [])(input));
+  static salt = [17, 31, 73, 47, 23];
+  lengths ~= salt;
   int[Size] twine = iota(0, Size).array;
   for(int i = 0; i < Rounds; i++) {
     twine = knotUp(lengths, twine);
   }
+  pos=skip=0;
   return twine.array.chunks(ChunkSize).map!(
-      x => format("%02x", reduce!((a,b) => a ^ b)(x[0], x[1..$]))
-  ).join;
+      x => reduce!((a,b) => a ^ b)(x[0], x[1..$])
+  ).array.to!(ubyte[Size/ChunkSize]);
 }
 
-void main(string[] args){
-  int[] lengths = to!(int[])(cast(ubyte[]) args[1]) ~ [17, 31, 73, 47, 23];
-  auto hash = getHash!(256, 64, 16)(lengths);
-  writeln(hash);
+auto getHash(int Size=256, int Rounds=64, int ChunkSize=16)(string input)
+  if( Size % ChunkSize == 0)
+{
+  auto hash = calcHash!(Size, Rounds, ChunkSize)(input);
+  return hash.array.map!(x => format("%02x", x)).join;
 }
+
+version(standalone) {
+  void main(string[] args){
+    auto hash = getHash(args[1]);
+    writeln(hash);
+  }
+}