This commit is contained in:
Tyler Beckman 2024-10-09 19:44:09 -06:00
parent a25f823f9d
commit 4b065d6058
Signed by: Ty
GPG key ID: 2813440C772555A4

View file

@ -1,14 +1,77 @@
#include "OutputProcessor.h" #include "OutputProcessor.h"
#include <atomic>
#include <chrono>
#include <fstream> #include <fstream>
#include <future>
#include <iomanip> #include <iomanip>
#include <iostream> #include <iostream>
#include <ostream> #include <ostream>
#include <random>
#include <string> #include <string>
#include <thread>
#include <utility>
#include <vector> #include <vector>
#include <cstdint> #include <cstdint>
bool checkSorted(const std::vector<std::string> &vector) {
for (size_t i = 0; i < vector.size() - 1; i++) {
if (vector.at(i) > vector.at(i + 1)) {
return false;
}
}
return true;
}
void bozosortAlignedVectors(std::vector<std::string> &vector1,
std::vector<unsigned int> &vector2) {
auto threadCount = std::thread::hardware_concurrency();
if (threadCount == 0)
threadCount = 8;
std::atomic<bool> shouldAbort(false);
std::vector<std::thread> threads{};
for (unsigned int i = 0; i < threadCount; i++) {
std::thread t(
[vector1, vector2, &shouldAbort,
i](std::vector<std::string>* vector1Original, std::vector<unsigned int>* vector2Original) mutable {
std::mt19937 twister(std::chrono::steady_clock::now()
.time_since_epoch()
.count() +
i);
std::uniform_int_distribution<size_t> dist(0,
vector1.size() - 1);
do {
if (shouldAbort) return;
size_t first = dist(twister);
size_t second = dist(twister);
std::string temp = vector1.at(first);
vector1.at(first) = vector1.at(second);
vector1.at(second) = temp;
// Also swap elements in the aligned vector. If I store
// where everything moved to maybe it could be faster?
unsigned int temp2 = vector2.at(first);
vector2.at(first) = vector2.at(second);
vector2.at(second) = temp2;
} while (!checkSorted(vector1));
*vector1Original = vector1;
*vector2Original = vector2;
shouldAbort = true;
},
&vector1, &vector2);
threads.push_back(std::move(t));
}
for (unsigned int i = 0; i < threadCount; i++) {
threads.at(i).join();
}
}
OutputProcessor::OutputProcessor() { OutputProcessor::OutputProcessor() {
_fileOut = std::ofstream(); _fileOut = std::ofstream();
_allWords = std::vector<std::string>(); _allWords = std::vector<std::string>();
@ -77,6 +140,9 @@ void OutputProcessor::analyzeWords(std::vector<std::string> allWords,
// Increment total word count // Increment total word count
_totalWordCount++; _totalWordCount++;
} }
// :3
bozosortAlignedVectors(_uniqueWords, _wordCounts);
} }
bool OutputProcessor::openStream() { bool OutputProcessor::openStream() {