-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDay2.cpp
More file actions
91 lines (72 loc) · 2.14 KB
/
Day2.cpp
File metadata and controls
91 lines (72 loc) · 2.14 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
#include "Day2.h"
void Day2::ParseInput()
{
//ifstream input("Example/Day2Part1.txt");
//ifstream input("Example/Day2Part2.txt");
ifstream input("Input/Day2.txt");
if (input.fail())
{
std::cout << "Failed to open input file.\n";
return;
}
string line;
while (getline(input, line))
Rows.push_back(line);
}
vector<int> ParseRowToIntegerVector(const string& row)
{
// Split the numbers by space
vector<string> numberStrings = Helpers::Split(row, ' ');
// Convert the string vector to an integer vector
vector<int> numbers = vector<int>();
for (const string& numberString : numberStrings)
numbers.push_back(stoi(numberString));
return numbers;
}
int Day2::RowDifference(const string& row)
{
// Parse the row string
vector<int> numbers = ParseRowToIntegerVector(row);
int maxElement = *max_element(numbers.begin(), numbers.end());
int minElement = *min_element(numbers.begin(), numbers.end());
return maxElement - minElement;
}
void Day2::Part1()
{
ParseInput();
int checksum = 0;
for (const std::string& row : Rows)
checksum += RowDifference(row);
std::cout << "Day 2 Part 1 answer is: " << checksum << std::endl;
}
int Day2::EvenlyDivided(const string& row)
{
/* Find the only two numbers in each row where one evenly divides the other
so where the result of the division operation is a whole number. */
// Parse the row string
vector<int> numbers = ParseRowToIntegerVector(row);
for (int number : numbers)
{
for (int number2 : numbers)
{
// Ignore checking with the same numbers because of nested loop
// Ignore checking when first number is smaller than second number
if (number == number2 || number < number2)
continue;
float division = static_cast<float>(number) / static_cast<float>(number2);
// Check if it is a whole number and return it if it is
if (floor(division) == division)
return static_cast<int>(division);
}
}
cout << "Error, no numbers where division is a whole number exist.\n";
return -1;
}
void Day2::Part2()
{
ParseInput();
int checksum = 0;
for (const std::string& row : Rows)
checksum += EvenlyDivided(row);
std::cout << "Day 2 Part 2 answer is: " << checksum << std::endl;
}