-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathday01.cpp
More file actions
106 lines (100 loc) · 2.44 KB
/
day01.cpp
File metadata and controls
106 lines (100 loc) · 2.44 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
#include <fstream>
#include <string>
#include <iostream>
std::vector<std::string> readFile()
{
std::ifstream file("inputsmall.txt");
std::string str;
std::vector<std::string> lines;
while (std::getline(file, str))
{
lines.push_back(str);
}
return lines;
}
void part1()
{
std::vector<std::string> lines = readFile();
int total = 0;
for (int i = 0; i < lines.size(); i++)
{
std::string line = lines[i];
std::string firstDigit;
for (int j = 0; j < line.size(); j++)
{
if (isdigit(line[j]))
{
firstDigit = line[j];
break;
}
}
std::string lastDigit;
for (int j = line.size()-1; j >= 0; j--)
{
if (isdigit(line[j]))
{
lastDigit = line[j];
break;
}
}
std::string value = firstDigit + lastDigit;
total = total + stoi(value);
}
std::cout << total;
}
void replace(std::string& str, const std::string& from, const std::string& to) {
size_t start_pos = 0;
while((start_pos = str.find(from, start_pos)) != std::string::npos) {
str.replace(start_pos, from.length(), to);
start_pos += to.length();
}
}
void replaceDigits(std::string& line) {
replace(line, "one", "1");
replace(line, "two", "2");
replace(line, "three", "3");
replace(line, "four", "4");
replace(line, "five", "5");
replace(line, "six", "6");
replace(line, "seven", "7");
replace(line, "eight", "8");
replace(line, "nine", "9");
}
void part2()
{
std::vector<std::string> lines = readFile();
int total = 0;
for (int i = 0; i < lines.size(); i++)
{
std::string line = lines[i];
replaceDigits(line);
std::string firstDigit;
for (int j = 0; j < line.size(); j++)
{
if (isdigit(line[j]))
{
firstDigit = line[j];
break;
}
}
std::string lastDigit;
for (int j = line.size()-1; j >= 0; j--)
{
if (isdigit(line[j]))
{
lastDigit = line[j];
break;
}
}
std::string value = firstDigit + lastDigit;
total = total + stoi(value);
}
std::cout << "part2: ";
std::cout << total;
}
int main()
{
// part1();
part2();
return EXIT_SUCCESS;
}