-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathday01.cpp
More file actions
108 lines (88 loc) · 2.39 KB
/
day01.cpp
File metadata and controls
108 lines (88 loc) · 2.39 KB
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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
#include "day01.h"
#include <cctype>
#include <fstream>
#include <iostream>
#include <regex>
#include <string>
namespace day01
{
int part1LineSum(const std::string& line);
int part2LineSum(const std::string& line);
void run_day(const bool example)
{
std::cout << "Running day 01 \n";
const std::string fileName{ example ? "inputs/day01_example.txt" : "inputs/day01_real.txt" };
std::ifstream file{ fileName };
int sum{};
std::string line;
while (std::getline(file, line))
{
sum += part1LineSum(line);
}
std::cout << "Part 1 answer: " << sum << '\n';
file.close();
file.open(fileName);
sum = 0;
while (std::getline(file, line))
{
sum += part2LineSum(line);
}
std::cout << "Part 2 answer: " << sum << '\n';
}
int part1LineSum(const std::string& line)
{
int secondDigit{};
int firstDigit{ -1 };
for (const char c : line)
{
if (std::isdigit(c))
{
if (firstDigit < 0)
{
firstDigit = c - '0';
}
secondDigit = c - '0';
}
}
return firstDigit * 10 + secondDigit;
}
const char* digits[9] = { "one", "two", "three", "four", "five", "six", "seven", "eight", "nine" };
int detectEndingDigitWord(const std::string& string)
{
for (int i = 1; i < 10; i++)
{
if (string.ends_with(digits[i-1]))
{
return i;
}
}
return -1;
}
int part2LineSum(const std::string& line)
{
int secondDigit{};
int firstDigit{ -1 };
for (size_t i = 0; i < line.length(); i++)
{
std::string subLine{ line.substr(0, i + 1) };
int currentDigit;
if (std::isdigit(subLine[i]))
{
currentDigit = subLine[i] - '0';
}
else
{
currentDigit = detectEndingDigitWord(subLine);
}
if (currentDigit > 0)
{
if (firstDigit < 0)
{
firstDigit = currentDigit;
}
secondDigit = currentDigit;
}
}
return firstDigit * 10 + secondDigit;
}
}