Problem Description: I am trying to do the task mentioned here - https://codereview.stackexchange.com/questions/182483/advent-of-code-2017-day-1-sum-of-digits-matching-the-next-digit-circular-list
But in Windows Power Shell using simple loop logic (as I am new to Power Shell)
The task requires to review a sequence of digits and find the sum of all digits that match the next digit in the list. The list is circular, so the digit after the last digit is the first digit in the list. For example:
1122 produces a sum of 3 (1 + 2) because the first digit 1 matches the second digit and the third digit 2 matches the fourth digit; 1111 produces 4 because each digit (all 1) matches the next; 1234 produces 0 because no digit matches the next; 91212129 produces 9 because the only digit that matches the next one is the last digit, 9
I have coded this:
foreach($line in [System.IO.File]::ReadLines("./task1.txt"))
{
$data = ($line)
}
$i=0
Do
{
if ($data[$i] -eq $data[$i+1]) {
$final += $data[$i]
}
$i++
}
While ($i -le $data.Length)
($final | Measure-Object -Sum).sum
My "task1.txt" contains the value - "1122"
The $final is storing the value "12" these digits are expected but I am unable to sum them up to get the desired answer - "3"
When I try to use:
foreach($line in [System.IO.File]::ReadLines("./task1.txt"))
{
[int[]]$data = [int[]]$line.split('')
}
My "$data" gets the entire "1122" as a value
Please help!
The var $i iterates through the Length,
Edit streamlined version thank to a hint from BenH
## Q:\Test\2018\05\17\SO_50397884.ps1
function CodeAdvent2017-1 {
param ([string]$data)
$res = 0
for ($i=0;$i -le $data.Length-1;$i++){
if ($data[$i] -eq $data[$i-1]){
$res+=[int]$data.substring($i,1)
}
#"`$i={0}, `$pnt={1} `$data[`$i]={2} `$res={3}" -f $i,$pnt,$data[$i],$res
}
return "Result: {0} of {1}" -f $res, $data
}
CodeAdvent2017-1 1122 #produces 3
CodeAdvent2017-1 1111 #produces 4
CodeAdvent2017-1 1234 #produces 0
CodeAdvent2017-1 91212129 #produces 9
Sample output:
> Q:\Test\2018\05\17\SO_50397884.ps1
Result: 3 of 1122
Result: 4 of 1111
Result: 0 of 1234
Result: 9 of 91212129