Powershell 查找序列中的下一个数字
我正努力在一组数字中找到下一个可用的数字,但遇到了麻烦 我的数据集是一个字符串数组,然后将其转换为整数数组。原始数据集可能有重复的编号 当我试图找到下一个可用的号码时,重复的号码似乎会导致产生不良结果的问题Powershell 查找序列中的下一个数字,powershell,Powershell,我正努力在一组数字中找到下一个可用的数字,但遇到了麻烦 我的数据集是一个字符串数组,然后将其转换为整数数组。原始数据集可能有重复的编号 当我试图找到下一个可用的号码时,重复的号码似乎会导致产生不良结果的问题 $dataset = "0001","0002","0004","0006","2","5" #Convert our strings to integers [array]$Used = foreach($number in $dataset) { try { [
$dataset = "0001","0002","0004","0006","2","5"
#Convert our strings to integers
[array]$Used = foreach($number in $dataset) {
try {
[int]::parse($number)
} catch {
Invoke-Expression -Command $number;
}
}
[array]::sort($Used)
$range = 1..10
$Available = compare $range $Used -PassThru
我的结果是:
$Dataset =
0001
0002
0004
0006
2
5
$Used =
1
2
2
4
5
6
注意,$Used
(已排序)显示2
是重复的:
$Available =
2
3
7
8
9
10
最后,$Available
将2
列为一个错误的可用号码2实际上使用了两次,正确答案应该是3
有什么想法吗?这个问题以前已经回答过了:
有很多很棒的答案选项,但基本上:
$Used=$Used |选择-uniq
还是另一种选择
$Used | sort-uniq
Compare-Object
cmdlet总是让我困惑[脸红],所以我完全避免了它。[咧嘴笑]这是
- 将数据集
[string]
项转换为[int]
项
- 消除重复
- 筛选不在已用编号列表中的目标范围编号
这是密码
$DataSet = '0001','0002','0004','0006','2','5'
$UsedNumbers = $DataSet.
ForEach({[int]$_}) |
Sort-Object -Unique
$TargetRange = 1..10
$AvailableNumbers = $TargetRange.
Where({
$_ -notin $UsedNumbers
})
$AvailableNumbers
输出
3
7
8
9
10
可以通过简单的强制转换将字符串转换为数字:
要对这些数字进行排序并消除重复项,请执行以下操作:
$uniqueSortedNumbers = $numbers | Sort-Object -Unique
要查找结果列表中的第一个可用数字,或者可能是下一个更高的数字,请执行以下操作:
# Find the first gap in the list of sorted numbers, if any.
$nextAvailableNumber =
Compare-Object -PassThru $uniqueSortedNumbers (1..($uniqueSortedNumbers[-1])) |
Select-Object -First 1
# If there was no gap, use the highest number + 1
if ($null -eq $nextAvailableNumber) {
$nextAvailableNumber = $uniqueSortedNumbers[-1] + 1
}
至于你所尝试的:
比较对象
列出两个集合中唯一的对象
通过在$used
中使用重复项,也会将重复项报告为唯一项,因为$range
没有重复项
使用-PassThru
,传递唯一值时,不会(明显)区分它们对哪个输入集合是唯一的,因此最终会出现对任一集合唯一的数字组合,包括$range
唯一的数字和重复的数字,这解释了您的症状
通过预先消除$used
中的重复项,避免了问题,因为所有唯一值都保证仅来自$range
。$Available=比较$range$used-PassThru |其中SideIndicator-eq'或$Available=比较对象$range($used |排序对象-unique)-PassThru
# Find the first gap in the list of sorted numbers, if any.
$nextAvailableNumber =
Compare-Object -PassThru $uniqueSortedNumbers (1..($uniqueSortedNumbers[-1])) |
Select-Object -First 1
# If there was no gap, use the highest number + 1
if ($null -eq $nextAvailableNumber) {
$nextAvailableNumber = $uniqueSortedNumbers[-1] + 1
}