Refactor Messy Nested Loop Code to Improve Readability and Performance
You are given a C++ function that uses nested loops and multiple conditionals in a messy and repetitive way to find common elements between two integer vectors and sum them. Refactor the code to improve readability, reduce complexity, and maintain the same output.
Challenge prompt
Below is a C++ function that evaluates two integer vectors and sums up all common elements between them. The code works correctly but is hard to read and inefficient due to the nested loops and repeated conditions. Refactor this function to make it cleaner, easier to understand, and ideally more performant, without changing its behavior or output.
Guidance
- • Consider using appropriate STL containers or algorithms to simplify membership checks and iteration.
- • Avoid nested loops where possible to reduce time complexity.
- • Make the intent of your code clearer by using descriptive variable names and breaking down complex statements.
Hints
- • Use an unordered_set for fast lookup of elements when checking for common values.
- • Utilize standard library algorithms like std::accumulate or std::count_if for summation.
- • Try separating logic into smaller functions or steps for clarity.
Starter code
int sumCommonElements(const std::vector<int>& v1, const std::vector<int>& v2) {
int sum = 0;
for (int i = 0; i < v1.size(); ++i) {
for (int j = 0; j < v2.size(); ++j) {
if (v1[i] == v2[j]) {
sum += v1[i];
break;
}
}
}
return sum;
}Expected output
For input v1 = {1, 2, 3, 4}, v2 = {3, 4, 5, 6}, the function should return 7 since 3 + 4 = 7.
Core concepts
Challenge a Friend
Send this duel to someone else and see if they can solve it.