Skip to content

feat: day09 in c++ #13

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Dec 9, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,4 +19,4 @@ Ideally, the solution does not use external crates/dependencies.
| 6 | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |
| 7 | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |
| 8 | ✅ | ✅ | ✅ | ✅ | ❌ | ❌ |
| 9 | ✅ | ✅ | | | ❌ | ❌ |
| 9 | ✅ | ✅ | | | ❌ | ❌ |
12 changes: 1 addition & 11 deletions cpp/day03.cc
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
#include "helpers.h"
#include <cctype>
#include <fstream>
#include <iostream>
Expand Down Expand Up @@ -142,17 +143,6 @@ int parseWithRules(const std::string &message) {
return count;
}

std::string readFile(const std::string &filePath) {
std::ifstream file(filePath);
if (!file.is_open()) {
throw std::runtime_error("Unable to open file: " + filePath);
}

std::ostringstream content;
content << file.rdbuf();
return content.str();
}

int main() {
try {
std::string message = readFile("crates/day03/input.txt");
Expand Down
11 changes: 1 addition & 10 deletions cpp/day05.cc
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
#include "helpers.h"
#include <algorithm>
#include <fstream>
#include <iostream>
Expand Down Expand Up @@ -114,16 +115,6 @@ class PrintQueueChecker {
}
};

std::string readFile(const std::string &filename) {
std::ifstream file(filename);
if (!file)
throw std::runtime_error("Unable to open file");

std::ostringstream ss;
ss << file.rdbuf();
return ss.str();
}

int main() {
try {
std::string message = readFile("crates/day05/input.txt");
Expand Down
11 changes: 1 addition & 10 deletions cpp/day06.cc
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
#include "helpers.h"
#include <fstream>
#include <iostream>
#include <optional>
Expand Down Expand Up @@ -206,16 +207,6 @@ class Lab {
}
};

string readFile(const string &filename) {
ifstream file(filename);
if (!file.is_open()) {
throw runtime_error("Could not open file");
}
stringstream buffer;
buffer << file.rdbuf();
return buffer.str();
}

int main() {
try {
string message = readFile("crates/day06/input.txt");
Expand Down
14 changes: 2 additions & 12 deletions cpp/day07.cc
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
#include "helpers.h"
#include <algorithm>
#include <cassert>
#include <cmath>
Expand Down Expand Up @@ -91,20 +92,9 @@ struct Calibration {
}
};

std::string read_file(const std::string &file_path) {
std::ifstream file(file_path);
if (!file) {
throw std::runtime_error("Could not open file: " + file_path);
}

std::ostringstream buffer;
buffer << file.rdbuf();
return buffer.str();
}

int main() {
try {
std::string message = read_file("crates/day07/input.txt");
std::string message = readFile("crates/day07/input.txt");

// --- Part One ---
Calibration checker(message);
Expand Down
13 changes: 2 additions & 11 deletions cpp/day08.cc
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
#include "helpers.h"
#include <algorithm>
#include <cmath>
#include <fstream>
Expand Down Expand Up @@ -140,19 +141,9 @@ class Antenna {
GridSize grid;
};

std::string read_file(const std::string &filename) {
std::ifstream file(filename);
if (!file) {
throw std::runtime_error("Could not open the file");
}
std::stringstream buffer;
buffer << file.rdbuf();
return buffer.str();
}

int main() {
try {
std::string message = read_file("crates/day08/input.txt");
std::string message = readFile("crates/day08/input.txt");

// --- Part One ---
Antenna checker(message);
Expand Down
184 changes: 184 additions & 0 deletions cpp/day09.cc
Original file line number Diff line number Diff line change
@@ -0,0 +1,184 @@
#include "helpers.h"
#include <algorithm>
#include <cstdint>
#include <fstream>
#include <iostream>
#include <optional>
#include <string>
#include <vector>

enum class File { Free, Taken };

struct TakenFile {
uint32_t id;
};

class FileSystem {
private:
std::vector<std::optional<TakenFile>> files;
std::vector<std::optional<TakenFile>> defragmentedFiles;

public:
FileSystem(const std::string &content) {
uint32_t id = 0;
for (const auto &line : split(content, '\n')) {
for (size_t i = 0; i < line.size(); ++i) {
char c = line[i];
if (std::isdigit(c)) {
uint32_t digit = c - '0';
if (i % 2 == 0) {
for (uint32_t j = 0; j < digit; ++j) {
files.emplace_back(TakenFile{id});
}
id++;
} else {
for (uint32_t j = 0; j < digit; ++j) {
files.emplace_back(std::nullopt);
}
}
}
}
}
defragmentedFiles = files;
}

static size_t
countFreeFiles(const std::vector<std::optional<TakenFile>> &files,
size_t index) {
size_t count = 0;
for (size_t i = index; i < files.size(); ++i) {
if (files[i].has_value()) {
break;
}
count++;
}
return count;
}

static std::optional<std::pair<size_t, size_t>>
detectBlock(const std::vector<std::optional<TakenFile>> &files,
size_t indexEnd) {
std::optional<std::pair<uint32_t, size_t>> currentBlock;

for (size_t i = indexEnd; i-- > 0;) {
if (!files[i].has_value()) {
if (currentBlock.has_value()) {
return std::make_pair(i + 1, currentBlock->second);
}
currentBlock.reset();
} else if (files[i]->id) {
if (!currentBlock.has_value()) {
currentBlock = std::make_pair(files[i]->id, 1);
} else if (files[i]->id != currentBlock->first) {
return std::make_pair(i + 1, currentBlock->second);
} else {
currentBlock->second++;
}
}
}

return std::nullopt;
}

void fragmentFiles() {
size_t last_index = defragmentedFiles.size();
for (size_t i = 0; i < defragmentedFiles.size(); i++) {
if (!defragmentedFiles[i].has_value()) {
std::optional<size_t> check_index;

for (size_t j = last_index; j > i; j--) {
if (defragmentedFiles[j - 1].has_value()) {
check_index = j - 1;
break;
}
}
if (check_index.has_value()) {
last_index = check_index.value();
std::iter_swap(defragmentedFiles.begin() + i,
defragmentedFiles.begin() + last_index);
}
}
}
}

void fragmentFilesBlock() {
size_t endVec = files.size();
while (auto block = detectBlock(files, endVec)) {
size_t startIndex = block->first;
size_t size = block->second;
bool followingFreeFile = false;
for (size_t i = 0; i < files.size(); ++i) {
if (!files[i].has_value()) {
if (!followingFreeFile) {
followingFreeFile = true;
size_t numberFreeFiles = countFreeFiles(files, i);
if (numberFreeFiles >= size && i < startIndex) {
for (size_t j = 0; j < size; ++j) {
std::swap(files[i + j], files[startIndex + j]);
}
break;
}
}
} else {
followingFreeFile = false;
}
}
endVec = startIndex;
}
}

static uint64_t
calculateChecksum(const std::vector<std::optional<TakenFile>> &files) {
uint64_t checksum = 0;
for (size_t i = 0; i < files.size(); ++i) {
if (files[i].has_value()) {
checksum += i * files[i]->id;
}
}
return checksum;
}

const std::vector<std::optional<TakenFile>> &getDefragmentedFiles() const {
return defragmentedFiles;
}

const std::vector<std::optional<TakenFile>> &getFiles() const {
return files;
}

private:
static std::vector<std::string> split(const std::string &str,
char delimiter) {
std::vector<std::string> tokens;
size_t start = 0, end = 0;
while ((end = str.find(delimiter, start)) != std::string::npos) {
tokens.push_back(str.substr(start, end - start));
start = end + 1;
}
tokens.push_back(str.substr(start));
return tokens;
}
};

int main() {
try {
std::string message = readFile("crates/day09/input.txt");

// --- Part One ---
FileSystem checker(message);
checker.fragmentFiles();
std::cout << "Part One solution: "
<< FileSystem::calculateChecksum(checker.getDefragmentedFiles())
<< "\n";

// --- Part Two ---
checker.fragmentFilesBlock();
std::cout << "Part Two solution: "
<< FileSystem::calculateChecksum(checker.getFiles()) << "\n";

} catch (const std::exception &ex) {
std::cerr << "Error: " << ex.what() << "\n";
return 1;
}
return 0;
}
12 changes: 12 additions & 0 deletions cpp/helpers.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
#include <fstream>
#include <sstream>
#include <string>

std::string readFile(const std::string &filePath) {
std::ifstream file(filePath);
if (!file) {
throw std::runtime_error("Could not open file");
}
return std::string((std::istreambuf_iterator<char>(file)),
std::istreambuf_iterator<char>());
}
12 changes: 0 additions & 12 deletions crates/day06/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -221,16 +221,4 @@ mod tests {
assert!(response_part_1 == 41);
assert!(response_part_2 == 6);
}

#[test]
fn check_result() {
let message = read_file("input.txt").unwrap();

let mut checker = Lab::new(&message).unwrap();
let response_part_1 = checker.find_path();
let response_part_2 = checker.find_if_stuck();

assert!(response_part_1 == 4374);
assert!(response_part_2 == 1705);
}
}
Loading
Loading