-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathday1PartTwo.cpp
More file actions
71 lines (59 loc) · 1.72 KB
/
day1PartTwo.cpp
File metadata and controls
71 lines (59 loc) · 1.72 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
#include "day1PartTwo.h"
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
#include <vector>
#include <algorithm>
#include <unordered_map>
namespace DayOnePartTwo
{
namespace {
using cmap_return_val_t = std::unordered_map<int, int>::iterator;
std::vector<int> firstElements;
std::vector<int> secondElements;
void handleLine(std::string& line) { // operates on the read value, destructive function
std::stringstream ss(line);
std::string stringPart;
std::string delim = " ";
size_t delimLen = delim.length();
size_t pos = line.find(delim); // unsigned long long
while (pos != std::string::npos)
{
firstElements.push_back(std::stoi(line.substr(0, pos)));
(void)line.erase(0, pos + delimLen);
pos = line.find(delim);
}
secondElements.push_back(std::stoi(line));
}
}
void dayOnePartTwo() {
std::cout << "Running program dayOne Part Two" << '\n';
std::string line;
std::ifstream inputFile("day1full.txt");
if (inputFile.is_open())
{
while (getline(inputFile, line)) {
handleLine(line);
}
std::sort(firstElements.begin(), firstElements.end()); // faster than any handwritten algorithm.
std::unordered_map<int, int> countMap;
for (const int& num : secondElements) {
++countMap[num];
}
int diffTotal = 0;
size_t lineCount = firstElements.size();
int idToCheck = 0;
for (int i = 0; i < lineCount; i++)
{
idToCheck = firstElements[i];
cmap_return_val_t foundPair = countMap.find(idToCheck); // _map[key] inserts values
if (foundPair != countMap.end()) { // end value = not found
diffTotal += idToCheck * (*foundPair).second;
}
}
std::cout << diffTotal;
}
else std::cout << "Unable to open file";
}
}