Skip to content

Commit

Permalink
solve(day 2): Red nosed reports part 2
Browse files Browse the repository at this point in the history
  • Loading branch information
dev-xero committed Dec 3, 2024
1 parent 2378688 commit e536196
Show file tree
Hide file tree
Showing 2 changed files with 91 additions and 3 deletions.
6 changes: 3 additions & 3 deletions day-1/01.cpp
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
#include <bits/stdc++.h>

#include "types.hpp"

using namespace std;


int main() {
ios::sync_with_stdio(0);
cin.tie(0);
Expand All @@ -25,7 +25,7 @@ int main() {
// Build both lists from input
while (inputFile >> l1 >> l2) {
cout << "l1: " << l1 << " l2: " << l2 << '\n';

list1.push_back(l1);
list2.push_back(l2);
}
Expand All @@ -40,7 +40,7 @@ int main() {
// Compare each element and sum absolute diff (both lists are same size)
ll diff = 0;

for (size_t i = 0; i < list1.size(); i++) {
for (int i = 0; i < list1.size(); i++) {
diff += abs(list1[i] - list2[i]);
}

Expand Down
88 changes: 88 additions & 0 deletions day-2/02.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
#include <bits/stdc++.h>

using namespace std;

bool isLevelSafe(vector<int> levels) {
bool isIncreasing = true;
bool isDecreasing = true;

for (size_t i = 1; i < levels.size(); i++) {
int curr = levels.at(i);
int prev = levels.at(i - 1);

int diff = curr - prev;

// It cannot be safe since it isn't within bounds
if (prev == curr) return false;

// Bounds is [1, 3]
if (abs(diff) > 3) return false;

if (curr > prev) isDecreasing = false;
if (prev > curr) isIncreasing = false;
}

// Must either be increasing or decreasing
return isIncreasing || isDecreasing;
}

// Safety dampener into consideration
bool isDampenedLevelSafe(vector<int> levels) {
if (isLevelSafe(levels)) {
return true;
}

for (size_t i = 0; i < levels.size(); i++) {
vector<int> remaining = levels;
remaining.erase(remaining.begin() + i);

if (isLevelSafe(remaining)) return true;
}

// If we get here, the level can never be safe
return false;
}

int main() {
ios::sync_with_stdio(0);
cin.tie(0);

string filename = "";

// Prompt for filename
cout << "Input File: ";
cout.flush();

// Read in file name
getline(cin, filename);

// Read input from file
ifstream inputFile("day-2/" + filename);
if (!inputFile.is_open()) {
cerr << "Unable to read file\n";

return 1;
}

// We are reading an n x m input list
string line = "";

int safeLevels = 0;

// Analyze each level
while (getline(inputFile, line)) {
vector<int> levels;
stringstream stream(line);

int num;

// Read each num into the vector
while (stream >> num) levels.push_back(num);

if (isDampenedLevelSafe(levels)) safeLevels++;
}

cout << "safe levels: " << safeLevels << '\n';

return 0;
}

0 comments on commit e536196

Please sign in to comment.