Skip to content

Instantly share code, notes, and snippets.

@mgarod
Last active August 19, 2016 18:06
Show Gist options
  • Save mgarod/f2e90a4dadbb93fb8f8052d1d02b712d to your computer and use it in GitHub Desktop.
Save mgarod/f2e90a4dadbb93fb8f8052d1d02b712d to your computer and use it in GitHub Desktop.
#include <fstream>
#include <iostream>
#include <unordered_map>
#include <vector>
int main() {
std::ifstream datafile("data.txt");
int64_t numlists;
int64_t a, b, c, d;
std::vector<int64_t> A, B, C, D;
datafile >> numlists;
while (datafile >> a >> b >> c >> d) {
A.push_back(a);
B.push_back(b);
C.push_back(c);
D.push_back(d);
}
std::unordered_map<int64_t, int64_t> AB, CD;
// Compute all pairs of a + b
for (auto a : A) {
for (auto b : B) {
try {
AB.at(a + b) += 1;
} catch (const std::out_of_range& oor) {
AB[a + b] = 1;
}
}
}
// Compute all pairs of c + d
for (auto c : C) {
for (auto d : D) {
try {
CD.at(c + d) += 1;
} catch (const std::out_of_range& oor) {
CD[c + d] = 1;
}
}
}
// Do there exist (c + d) == -(a + b)? How many?
int result = 0;
for (auto i : AB) {
try {
// Accounts for possibilities were distinct are distinct combinations of
// a, b result in equal sums
result += i.second * CD.at(-(i.first));
} catch (const std::out_of_range& oor) {}
}
std::cout << "result: " << result << std::endl;
return 0;
}
/*
data.txt
6
-45 22 42 -16
-41 -27 56 30
-36 53 -37 77
-36 30 -75 -46
26 -38 -10 62
-32 -54 -6 45
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment