r/PowerShell • • Dec 04 '25

Misc Advent of Code - Day 3

was waiting for u/dantose to make this post ;)

I'm running a day behind, so have only just got to Day 3 Part 2 (Part 1 stumped me because I misread it - I was adding max1 and max2 for each battery bank together as integers, whereas I needed to concat them as strings....

Still, Part 2 has me so stumped I can't even work out how to start :(

7 Upvotes

12 comments sorted by

View all comments

Show parent comment

1

u/Future-Remote-4630 Dec 04 '25

I wish I thought of using indexof instead of a for loop!

    Function Get-LargestSubstringInteger($string,$remainingValues = 1)
    {
        $ints = $string.ToCharArray() | select -skiplast $remainingValues | % { [int]"$_" }
    
        $max = 0 
        $maxindex = 0
        for($i = 0; $i -lt $ints.count; $i++){
            if($ints[$i] -gt $max){
                $max = $ints[$i]
                $maxindex = $i
            }
        }
    
        return [pscustomobject]@{
            max=$max
            maxindex=$maxindex
            remainingString = $string.substring($maxindex+1,$string.Length-($maxindex+1))
        }
        
    }



$batteryrow = gc C:\temp\AdventOfCode\Day3Input.txt
$totalVoltage = foreach($row in $batteryrow){

    $string = $row
    $volts = 11..0 | % {
        $obj = Get-LargestSubstringInteger -string $string -remainingValues $_
        $obj.max
        $string = $obj.remainingString
    }

    $voltage = [int64]"$($volts -join '')"
    $voltage
}

$totalvoltage | measure -sum