-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy path04.cpp
76 lines (62 loc) · 1.85 KB
/
04.cpp
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
#include <cctype>
#include <chrono>
#include <iostream>
#include <string_view>
#include <unordered_set>
using std::string;
using std::string_view;
using std::unordered_set;
int character_value(const string_view &word) {
int value = 1;
for (const char ch : word) {
value *= (ch - 'a' + 1);
}
return value;
}
int main() {
auto tstart = std::chrono::high_resolution_clock::now();
int pt1 = 0;
int pt2 = 0;
string input;
unordered_set<std::string_view> words;
unordered_set<int> anagrams;
while (std::getline(std::cin, input)) {
words.clear();
anagrams.clear();
bool valid = true;
bool valid_pt2 = true;
string::iterator it = input.begin();
string::iterator lineend = input.end();
while (valid || valid_pt2) {
string::iterator wordstart = it;
while (it != lineend && !std::isspace(*it)) {
it++;
}
string_view word(wordstart, it);
valid = valid && !words.contains(word);
// TODO: We could get rid of the allocation here
// By multiplying each character with its ordinal value and summing the
// result string anagram(word); sort(anagram.begin(), anagram.end());
int anagram = character_value(word);
valid_pt2 = valid_pt2 && !anagrams.contains(anagram);
if (it == lineend) {
break;
}
it++;
words.insert(word);
anagrams.insert(anagram);
}
pt1 += valid;
pt2 += valid_pt2;
}
std::cout << "--- Day 4: High-Entropy Passphrases ---\n";
std::cout << "Part 1: " << pt1 << "\n";
std::cout << "Part 2: " << pt2 << "\n";
auto tstop = std::chrono::high_resolution_clock::now();
auto duration =
std::chrono::duration_cast<std::chrono::microseconds>(tstop - tstart);
std::cout << "Time: " << (static_cast<double>(duration.count()) / 1000.0)
<< " ms"
<< "\n";
return EXIT_SUCCESS;
}