r/backtickbot • • Dec 02 '20

https://np.reddit.com/r/adventofcode/comments/k4e4lm/2020_day_1_solutions/gec0e6f/

PowerShell: I am removing the pivot elements when comparing to the input list in the case that an element gives a false positive by pinging against itself. This allows for a more generalized function, though this is only useful if there are no duplicates in the list. If there are duplicates in the list that would allow for the bailout condition to be true, then this would break the solution i.e. the value to search for is 40 and there are two elements that are 20.

|Times running on Ryzen 3700x (Standard Clock Speed)| Solution 1: Average - 2.2 ms Solution 2: Average - 200 ms

[System.Collections.ArrayList]$in =gc .\input.txt | foreach-object{$_.ToInt64($Null)}

#Solution 1
function twoSum{
param($val,$list)
    foreach($e in $list){
        $diff = $val-$e
        if(($list -ne $e) -contains $diff){
            $e*$list[[array]::IndexOf($list,$diff)]
            return
        }
    }
}

twoSum 2020 $in

#Solution 2
function threeSum{
param($val,$list)
    foreach($e in $list){
        foreach($e1 in ($list -ne $el)){
            $diff = $val-($e+$e1)
            if(($list -ne $e -ne $e1) -contains $diff){
                $e*$e1*$list[[array]::IndexOf($list,$diff)]
                return
            }
        }
    }
}

threeSum 2020 $in
1 Upvotes

0 comments sorted by