Day 2: Part 1

This commit is contained in:
Fawkes100 2024-12-08 09:38:24 +01:00
parent 1574e882e0
commit f26c591168
4 changed files with 1097 additions and 0 deletions

6
Aufgabe 2/CMakeLists.txt Normal file
View File

@ -0,0 +1,6 @@
cmake_minimum_required(VERSION 3.31)
project(Aufgabe_2)
set(CMAKE_CXX_STANDARD 17)
add_executable(Aufgabe_2 main.cpp)

1000
Aufgabe 2/input.txt Normal file

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,6 @@
7 6 4 2 1
1 2 7 8 9
9 7 6 2 1
1 3 2 4 5
8 6 4 4 1
1 3 6 7 9

85
Aufgabe 2/main.cpp Normal file
View File

@ -0,0 +1,85 @@
#include <iostream>
#include <vector>
#include <fstream>
std::vector<std::string> readTextFromFile(const std::string& fileName) {
std::vector<std::string> lines;
std::ifstream file(fileName);
if (!file) { // Überprüft, ob die Datei geöffnet werden konnte
std::cerr << "Fehler: Datei konnte nicht geöffnet werden: " << fileName << std::endl;
return lines;
}
std::string s;
while(getline(file, s)) {
lines.push_back(s);
}
return lines;
}
std::vector<std::string> splitString(const std::string& input, char ch) {
std::vector<std::string> splittedString;
size_t pos = input.find(ch);
size_t initialPos = 0;
while(pos != std::string::npos) {
splittedString.push_back(input.substr(initialPos, pos - initialPos));
initialPos = pos + 1;
pos = input.find(ch, initialPos);
}
splittedString.push_back(input.substr(initialPos, std::min(pos, input.size()) - initialPos));
return splittedString;
}
std::vector<int> convertReportToNumericalReport(const std::vector<std::string>& splittedReport) {
std::vector<int> numericalReport;
for(const auto& s : splittedReport) {
numericalReport.push_back(std::stoi(s));
}
return numericalReport;
}
bool isReportSave(std::string report) {
std::vector<std::string> splittedReport = splitString(report, ' ');
std::vector<int> numericalReport = convertReportToNumericalReport(splittedReport);
bool isIncreasing = true;
bool isDecreasing = true;
for(int i=0; i<numericalReport.size()-1; i++) {
if(numericalReport.at(i) > numericalReport.at(i+1)) {
isDecreasing = false;
}
if(numericalReport.at(i) < numericalReport.at(i+1)) {
isIncreasing = false;
}
int differ = std::abs(numericalReport.at(i) - numericalReport.at(i+1));
if(differ < 1 || differ > 3) {
return false;
}
}
return isIncreasing || isDecreasing;
}
int calcNumberSaveReports(std::vector<std::string> reports) {
int saveReports = 0;
for(const auto& report : reports) {
if(isReportSave(report)) {
saveReports++;
}
}
return saveReports;
}
int main() {
std::string inputFile = "../input.txt";
std::vector<std::string> reports = readTextFromFile(inputFile);
int result = calcNumberSaveReports(reports);
std::cout << "There are " << result << " save reports";
return 0;
}