comparison 2017/day10.d @ 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 bd993cf00e2f
children
comparison
equal deleted inserted replaced
15:817954f71d53 16:990a4fa2aebe
17 twine[a..$] = result[0..Size-a]; 17 twine[a..$] = result[0..Size-a];
18 twine[0..b] = result[Size-a..$]; 18 twine[0..b] = result[Size-a..$];
19 } 19 }
20 } 20 }
21 21
22 auto pos = 0, skip = 0;
22 auto knotUp(int Size)(int[] lengths, int[Size] twine) { 23 auto knotUp(int Size)(int[] lengths, int[Size] twine) {
23 static pos = 0, skip = 0;
24 foreach(length; lengths) { 24 foreach(length; lengths) {
25 reverse(twine, pos, pos+length); 25 reverse(twine, pos, pos+length);
26 pos += length + skip; 26 pos = (pos + length + skip) % Size;
27 skip++; 27 skip = (skip + 1) % Size;
28 } 28 }
29 return twine; 29 return twine;
30 } 30 }
31 31
32 auto getHash(int Size, int Rounds, int ChunkSize)(int[] lengths) 32 auto calcHash(int Size=256, int Rounds=64, int ChunkSize=16)(string input)
33 if( Size % ChunkSize == 0) 33 if( Size % ChunkSize == 0)
34 { 34 {
35 int[] lengths = to!(int[])(cast(ubyte [])(input));
36 static salt = [17, 31, 73, 47, 23];
37 lengths ~= salt;
35 int[Size] twine = iota(0, Size).array; 38 int[Size] twine = iota(0, Size).array;
36 for(int i = 0; i < Rounds; i++) { 39 for(int i = 0; i < Rounds; i++) {
37 twine = knotUp(lengths, twine); 40 twine = knotUp(lengths, twine);
38 } 41 }
42 pos=skip=0;
39 return twine.array.chunks(ChunkSize).map!( 43 return twine.array.chunks(ChunkSize).map!(
40 x => format("%02x", reduce!((a,b) => a ^ b)(x[0], x[1..$])) 44 x => reduce!((a,b) => a ^ b)(x[0], x[1..$])
41 ).join; 45 ).array.to!(ubyte[Size/ChunkSize]);
42 } 46 }
43 47
44 void main(string[] args){ 48 auto getHash(int Size=256, int Rounds=64, int ChunkSize=16)(string input)
45 int[] lengths = to!(int[])(cast(ubyte[]) args[1]) ~ [17, 31, 73, 47, 23]; 49 if( Size % ChunkSize == 0)
46 auto hash = getHash!(256, 64, 16)(lengths); 50 {
47 writeln(hash); 51 auto hash = calcHash!(Size, Rounds, ChunkSize)(input);
52 return hash.array.map!(x => format("%02x", x)).join;
48 } 53 }
54
55 version(standalone) {
56 void main(string[] args){
57 auto hash = getHash(args[1]);
58 writeln(hash);
59 }
60 }