-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathday1.cpp
More file actions
65 lines (54 loc) · 1.49 KB
/
day1.cpp
File metadata and controls
65 lines (54 loc) · 1.49 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
// Locations listed by location ID
// Mismatched lists
// Smallest-smallest;second-second;...
// intrapair distance
// optimal sorting algo
#include "day1.h"
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
#include <vector>
#include <algorithm>
namespace DayOne
{
namespace {
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 dayOne() {
std::cout << "Running program dayOne" << '\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::sort(secondElements.begin(), secondElements.end());
int diffTotal = 0;
size_t lineCount = firstElements.size();
for (int i = 0; i < lineCount; i++)
{
diffTotal += abs(firstElements[i] - secondElements[i]);
}
std::cout << diffTotal;
}
else std::cout << "Unable to open file";
}
}