gpt4 book ai didi

windows - 如何在 Powershell 中的 System.String 类型的字符串中添加值

转载 作者:可可西里 更新时间:2023-11-01 11:23:44 25 4
gpt4 key购买 nike

问题描述:我正在尝试执行此处提到的任务 - 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 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

我已经编码了:

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”作为一个值

请帮忙!

最佳答案

var $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

关于windows - 如何在 Powershell 中的 System.String 类型的字符串中添加值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50397884/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com