Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <fstream>
- #include <vector>
- #include <sstream>
- #include <algorithm>
- #include <unordered_map>
- #include <chrono>
- std::pair<std::vector<int>, std::vector<int>> create_sorted_vectors_from_file(const std::string& file_name) {
- std::ifstream file(file_name);
- std::vector<int> col1, col2;
- std::string line;
- while (std::getline(file, line)) {
- std::istringstream iss(line);
- int num1, num2;
- if (iss >> num1 >> num2) {
- col1.push_back(num1);
- col2.push_back(num2);
- }
- }
- std::sort(col1.begin(), col1.end());
- std::sort(col2.begin(), col2.end());
- return {col1, col2};
- }
- int64_t calculate_l1_distance(const std::vector<int>& vec1, const std::vector<int>& vec2) {
- int64_t distance = 0;
- for (size_t i = 0; i < vec1.size(); ++i) {
- distance += std::abs(static_cast<int64_t>(vec1[i]) - vec2[i]);
- }
- return distance;
- }
- int64_t find_similarity_score(const std::vector<int>& vec1, const std::vector<int>& vec2) {
- std::unordered_map<int, unsigned int> vec2_counter;
- for (int el : vec2) {
- vec2_counter[el]++;
- }
- int64_t score = 0;
- for (int el : vec1) {
- auto it = vec2_counter.find(el);
- if (it != vec2_counter.end()) {
- score += static_cast<int64_t>(el) * it->second;
- }
- }
- return score;
- }
- int main() {
- auto start = std::chrono::high_resolution_clock::now();
- try {
- auto [col1, col2] = create_sorted_vectors_from_file(R"(C:\Users\msmin\code\aoc_python\day1_input.txt)");
- if (col1.size() == col2.size()) {
- int64_t l1_distance = calculate_l1_distance(col1, col2);
- int64_t similarity_score = find_similarity_score(col1, col2);
- std::cout << "L1 distance between the two vectors: " << l1_distance << std::endl;
- std::cout << "similarity score between the two vectors: " << similarity_score << std::endl;
- } else {
- std::cout << "Error: Vectors have different lengths" << std::endl;
- }
- } catch (const std::exception& e) {
- std::cout << "Error reading file: " << e.what() << std::endl;
- }
- auto end = std::chrono::high_resolution_clock::now();
- auto duration = std::chrono::duration_cast<std::chrono::microseconds>(end - start);
- std::cout << "Time elapsed: " << duration.count() << " microseconds" << std::endl;
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement