问题描述:我正在尝试完成这里提到的任务- https://codereview.stackexchange.com/questions/182483/advent-of-code-2017-day-1-sum-of-digits-matching-the-next-digit-circular-list
但是在Windows Power Shell中使用简单的循环逻辑(因为我对Power Shell还不熟悉)
该任务需要检查一个数字序列,并查找与列表中的下一个数字匹配的所有数字的总和。列表是循环的,所以最后一个数字后面的数字是列表中的第一个数字。例如:
1122产生3 (1 + 2)和,因为第一个数字1匹配第二位数字,第三位数字2与第四位数字匹配;1111生成4是因为每个数字(全部1)匹配下一个数字;1234生成0是因为没有数字匹配下一个数字;91212129生成9是因为唯一匹配下一个数字的数字是最后一个数字,9。
我对此进行了编码:
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我的"task1.txt“包含值- "1122”
$final正在存储"12“值--这些数字是预期的,但我无法对它们进行求和以得到所需的答案-- "3”。
当我试图使用:
foreach($line in [System.IO.File]::ReadLines("./task1.txt"))
{
[int[]]$data = [int[]]$line.split('')
}我的"$data“将整个"1122”作为一个值
请帮帮我!
发布于 2018-05-17 19:10:30
变量$i遍历长度,
编辑精简版感谢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样本输出:
> Q:\Test\2018\05\17\SO_50397884.ps1
Result: 3 of 1122
Result: 4 of 1111
Result: 0 of 1234
Result: 9 of 91212129发布于 2018-05-18 01:20:58
foreach($line in (gc ".\task1")) {
[string]$data = $line
}
$i=0
$final = 0
Do {
if ($data[$i] -eq $data[$i -1]) {
$final += [int]$data.substring($i,1)
}
$i++
} While ($i -le $data.Length-1)
$final https://stackoverflow.com/questions/50397884
复制相似问题