ps/Modules/Cole.PowerShell.Developer/Public/Group-Numbers.ps1
2023-05-30 22:51:22 -07:00

34 lines
911 B
PowerShell

function Group-Numbers {
<#
.SYNOPSIS
Group an array of numbers into islands of contiguous sequences
#>
[CmdletBinding()]
[OutputType([System.Collections.ArrayList])]
param (
[Parameter(Mandatory = $true)]
[int[]]$Values
)
$groups = (New-Object -TypeName "System.Collections.ArrayList")
if ($Values.Length -eq 0) {
return $groups
}
$len = $Values.Length
$group = (New-Object -TypeName "System.Collections.ArrayList")
$group.Add($Values[0]) | Out-Null
for($i = 1; $i -lt $len; $i++) {
if (($Values[$i] - $Values[$i-1]) -eq 1) {
$group.Add($Values[$i]) | Out-Null
} else {
$groups.Add($group) | Out-Null
$group = (New-Object -TypeName "System.Collections.ArrayList")
$group.Add($Values[$i]) | Out-Null
}
}
$groups.Add($group) | Out-Null
return $groups
}