summaryrefslogtreecommitdiff
path: root/2023/07/src/part2.cpp
diff options
context:
space:
mode:
authorFederico Igne <undyamon@disroot.org>2023-12-07 12:21:32 +0100
committerFederico Igne <undyamon@disroot.org>2023-12-07 12:21:32 +0100
commit9cba3e782b8ff464fc94b10d9ed8737193659bcc (patch)
tree3aeebdf451faee487082383017cff3a6e38005c4 /2023/07/src/part2.cpp
parent7c94a61035a4b96707f1fee5fdc26734c09543b0 (diff)
downloadaoc-9cba3e782b8ff464fc94b10d9ed8737193659bcc.tar.gz
aoc-9cba3e782b8ff464fc94b10d9ed8737193659bcc.zip
aoc(2307): Camel Cards
Diffstat (limited to '2023/07/src/part2.cpp')
-rw-r--r--2023/07/src/part2.cpp113
1 files changed, 113 insertions, 0 deletions
diff --git a/2023/07/src/part2.cpp b/2023/07/src/part2.cpp
new file mode 100644
index 0000000..239df11
--- /dev/null
+++ b/2023/07/src/part2.cpp
@@ -0,0 +1,113 @@
1#include <algorithm>
2#include <array>
3#include <fstream>
4#include <iostream>
5#include <set>
6#include <sstream>
7#include <string>
8
9class Hand
10{
11 static constexpr int HAND{ 5 };
12
13 int bet_;
14 int score_{};
15 std::array<char,HAND> cards_;
16
17public:
18 Hand(const std::string& cards, int bet) : bet_{ bet }
19 {
20 for (int c = 0; c < HAND; ++c)
21 {
22 switch (cards[c])
23 {
24 case 'A':
25 cards_[c] = 12;
26 break;
27 case 'K':
28 cards_[c] = 11;
29 break;
30 case 'Q':
31 cards_[c] = 10;
32 break;
33 case 'J':
34 cards_[c] = 0;
35 break;
36 case 'T':
37 cards_[c] = 9;
38 break;
39 default:
40 cards_[c] = cards[c] - '1';
41 }
42 }
43
44 std::array<int,13> mult{};
45 std::for_each(cards_.begin(), cards_.end(), [&mult](int c) { ++mult[c]; });
46 std::for_each(mult.begin() + 1, mult.end(), [this](int c) {
47 switch (c)
48 {
49 case 2:
50 this->score_ += 1;
51 break;
52 case 3:
53 this->score_ += 3;
54 break;
55 case 4:
56 this->score_ += 5;
57 break;
58 case 5:
59 this->score_ += 6;
60 break;
61 }
62 });
63 for (int j = 1; j <= mult[0] and j < HAND; ++j)
64 {
65 score_ += (1 <= score_ and score_ < 4) ? 2 : 1;
66 }
67 }
68
69 inline int bet() const
70 {
71 return bet_;
72 }
73
74 bool operator<(const Hand& that) const
75 {
76 return this->score_ < that.score_ or
77 (this->score_ == that.score_ and this->cards_ < that.cards_);
78 }
79
80 static Hand from_string(const std::string& str)
81 {
82 int bet;
83 std::string hand;
84 std::istringstream{ str } >> hand >> bet;
85 return { hand, bet };
86 }
87};
88
89int main(void)
90{
91 int answer{};
92 std::multiset<Hand> hands;
93
94 std::ifstream input{ "resources/input.txt" };
95 if (input.is_open())
96 {
97 std::string line;
98 while (not std::getline(input,line).eof())
99 {
100 hands.insert(Hand::from_string(line));
101 }
102 }
103 input.close();
104
105 int rank{};
106 for (const auto& h : hands)
107 {
108 answer += ++rank * h.bet();
109 }
110
111 std::cout << answer << std::endl;
112 return 0;
113}