From 73c4fb998408a4a02733bbb561db0e749c1a579e Mon Sep 17 00:00:00 2001 From: Mattrixwv Date: Thu, 3 Dec 2020 12:10:28 -0500 Subject: [PATCH] Optomized solutions for Day1 --- Day1-1.cpp | 9 ++++++++- Day1-2.cpp | 19 +++++++++++++------ 2 files changed, 21 insertions(+), 7 deletions(-) diff --git a/Day1-1.cpp b/Day1-1.cpp index 16e4778..972c8d3 100644 --- a/Day1-1.cpp +++ b/Day1-1.cpp @@ -7,6 +7,7 @@ #include #include +#include #include "Stopwatch.hpp" @@ -32,10 +33,16 @@ int main(){ //Start the timer timer.start(); + std::sort(numbersList.begin(), numbersList.end()); + //Find the two numbers in the array that make the correct sum for(int cnt1 = 0;(cnt1 < numbersList.size()) && (!found);++cnt1){ for(int cnt2 = cnt1 + 1;(cnt2 < numbersList.size()) && (!found);++cnt2){ - if((numbersList[cnt1] + numbersList[cnt2]) == NEEDED_SUM){ + int sum = numbersList[cnt1] + numbersList[cnt2]; + if(sum > NEEDED_SUM){ + break; + } + else if(sum == NEEDED_SUM){ firstNum = numbersList[cnt1]; secondNum = numbersList[cnt2]; found = true; diff --git a/Day1-2.cpp b/Day1-2.cpp index 1f55537..238f7cc 100644 --- a/Day1-2.cpp +++ b/Day1-2.cpp @@ -7,6 +7,7 @@ #include #include +#include #include "Stopwatch.hpp" @@ -33,16 +34,22 @@ int main(){ //Start the timer timer.start(); + std::sort(numbersList.begin(), numbersList.end()); + //Find the two numbers in the array that make the correct sum for(int cnt1 = 0;(cnt1 < numbersList.size()) && (!found);++cnt1){ for(int cnt2 = cnt1 + 1;(cnt2 < numbersList.size()) && (!found);++cnt2){ for(int cnt3 = cnt2 + 1;(cnt3 < numbersList.size()) && (!found);++cnt3){ - if((numbersList[cnt1] + numbersList[cnt2] + numbersList[cnt3]) == NEEDED_SUM){ - firstNum = numbersList[cnt1]; - secondNum = numbersList[cnt2]; - thirdNum = numbersList[cnt3]; - found = true; - } + int sum = numbersList[cnt1] + numbersList[cnt2] + numbersList[cnt3]; + if(sum > NEEDED_SUM){ + break; + } + else if(sum == NEEDED_SUM){ + firstNum = numbersList[cnt1]; + secondNum = numbersList[cnt2]; + thirdNum = numbersList[cnt3]; + found = true; + } } } }