-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathday05_md5hash.dart
77 lines (65 loc) · 1.87 KB
/
day05_md5hash.dart
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
import 'dart:convert';
import 'package:crypto/crypto.dart';
// ########
// SOLUTION
// ########
String generateMd5(String input) {
return md5.convert(utf8.encode(input)).toString();
}
String part1(puzzleInput) {
int counter = 0;
String password = "";
while (true) {
String candidateString = puzzleInput + counter.toString();
String hashedString = generateMd5(candidateString);
if (hashedString.startsWith("00000")) {
password += hashedString[5];
}
if (password.length == 8) {
break;
}
counter++;
}
return password;
}
String part2(puzzleInput) {
int counter = -1;
List<String> password = ["*", "*", "*", "*", "*", "*", "*", "*"];
while (true) {
counter++;
String candidateString = puzzleInput + counter.toString();
String hashedString = generateMd5(candidateString);
if (hashedString.startsWith("00000")) {
int characterPosition = int.parse(hashedString[5], radix: 16);
if (characterPosition > 7) continue;
if (password[characterPosition] != "*") continue;
String character = hashedString[6];
password[characterPosition] = character;
}
if (!password.contains("*")) {
break;
}
}
return password.reduce((a, b) => a + b);
}
// ###########
// RUN PROGRAM
// ###########
void main() {
// part 1
// const TEST_INPUT = "abc";
// assert(part1(TEST_INPUT) == "18f47a30");
// String puzzleInput = "reyedfim";
// final stopwatchPart1 = Stopwatch()..start();
// print("part 1: ${part1(puzzleInput)}");
// stopwatchPart1.stop();
// print("Elapsed time: ${stopwatchPart1.elapsed}");
// part 2
// const TEST_INPUT = "abc";
// assert(part2(TEST_INPUT) == "05ace8e3");
String puzzleInput = "reyedfim";
final stopwatchPart2 = Stopwatch()..start();
print("part 2: ${part2(puzzleInput)}");
stopwatchPart2.stop();
print("Elapsed time: ${stopwatchPart2.elapsed}");
}