Mercurial > hg > aoc
comparison 2017/day10.d @ 10:bd993cf00e2f
day 10
author | Jordi Gutiérrez Hermoso <jordigh@octave.org> |
---|---|
date | Mon, 11 Dec 2017 19:50:57 -0500 |
parents | |
children | 990a4fa2aebe |
comparison
equal
deleted
inserted
replaced
9:18e7ffa83a14 | 10:bd993cf00e2f |
---|---|
1 import std.stdio; | |
2 import std.range: iota, array, chunks; | |
3 import std.algorithm: invert=reverse, map, reduce; | |
4 import std.conv: to; | |
5 import std.format: format; | |
6 import std.string: join; | |
7 | |
8 void reverse(int Size)(ref int[Size] twine, int a, int b) { | |
9 a = a % Size; | |
10 b = b % Size; | |
11 if (a <= b) { | |
12 invert(twine[a..b]); | |
13 } | |
14 else { | |
15 auto result = twine[a..$] ~ twine[0..b]; | |
16 invert(result); | |
17 twine[a..$] = result[0..Size-a]; | |
18 twine[0..b] = result[Size-a..$]; | |
19 } | |
20 } | |
21 | |
22 auto knotUp(int Size)(int[] lengths, int[Size] twine) { | |
23 static pos = 0, skip = 0; | |
24 foreach(length; lengths) { | |
25 reverse(twine, pos, pos+length); | |
26 pos += length + skip; | |
27 skip++; | |
28 } | |
29 return twine; | |
30 } | |
31 | |
32 auto getHash(int Size, int Rounds, int ChunkSize)(int[] lengths) | |
33 if( Size % ChunkSize == 0) | |
34 { | |
35 int[Size] twine = iota(0, Size).array; | |
36 for(int i = 0; i < Rounds; i++) { | |
37 twine = knotUp(lengths, twine); | |
38 } | |
39 return twine.array.chunks(ChunkSize).map!( | |
40 x => format("%02x", reduce!((a,b) => a ^ b)(x[0], x[1..$])) | |
41 ).join; | |
42 } | |
43 | |
44 void main(string[] args){ | |
45 int[] lengths = to!(int[])(cast(ubyte[]) args[1]) ~ [17, 31, 73, 47, 23]; | |
46 auto hash = getHash!(256, 64, 16)(lengths); | |
47 writeln(hash); | |
48 } |