# HG changeset patch # User Jordi GutiƩrrez Hermoso # Date 1513359611 18000 # Node ID 990a4fa2aebec50de3fb03e113e51ffbc32299cf # Parent 817954f71d53b8d63c19052bc297e565725df18c day 10: modularise and debug diff --git a/2017/day10.d b/2017/day10.d --- 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); + } +}