Skip to content
Snippets Groups Projects
Commit 2d92ed40 authored by Evy Storozhenko's avatar Evy Storozhenko
Browse files

implementation

parent d8704673
No related branches found
No related tags found
No related merge requests found
int main() {}
#include <algorithm>
#include <fstream>
#include <iostream>
#include <ranges>
#include <set>
#include <string>
void part_a() {
std::ifstream data("data.txt");
std::string line;
int sum = 0;
while (std::getline(data, line)) {
int a = *std::ranges::find_if(line.begin(), line.end(), [](char c) {
return std::isdigit(c);
}) - '0';
int b = *std::ranges::find_if(line.rbegin(), line.rend(), [](char c) {
return std::isdigit(c);
}) - '0';
sum += a * 10 + b;
}
std::cout << sum << std::endl;
}
void part_b() {
std::ifstream data("data.txt");
constexpr std::array<std::string_view, 9> numbers
= { "one", "two", "three", "four", "five", "six", "seven", "eight", "nine" };
std::string line;
uint32_t sum = 0;
while (std::getline(data, line)) {
std::pair num_a { 0, line.size() };
for (size_t index = 0; index < numbers.size(); ++index) {
auto offset = std::min(line.find(numbers[index]), line.find(std::to_string(index + 1)));
if (offset != line.npos && offset < num_a.second) {
num_a.first = index + 1;
num_a.second = offset;
}
}
std::pair num_b { 0, -1 };
for (size_t index = 0; index < numbers.size(); ++index) {
std::set found = { line.rfind(numbers[index]), line.rfind(std::to_string(index + 1)) };
found.erase(line.npos);
if (!found.empty()) {
auto offset = std::ranges::max(found);
if (static_cast<int>(offset) > num_b.second) {
num_b.first = index + 1;
num_b.second = offset;
}
}
}
sum += num_a.first * 10 + num_b.first;
}
std::cout << sum << std::endl;
}
int main() {
part_a();
part_b();
}
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment