Home > OS >  Compare item in Array with next item
Compare item in Array with next item

Time:05-12

I'm not really good at coding in general but also in Powershell so I hope someone can support me here. I have a list of numbers and I want to iterate through each item and check if it is bigger by 1 ( 1) than the last item. If yes it should add it to a new list and the output should look like this: numbers = @("12","50","5041-5043") instead of numbers = @("12","50","5041","5042","5043") so basically I want concatenate range of numbers that were sorted ascending beforehand.

Any recommendation or guidance is appreciated

numbers = @("12","50","5041","5042","5043")
count = 0
while(numbers.Length){
 if(#ItemInList[$count] -eq #nextItemInList[$count   1]){
  #put in range
} 
}

CodePudding user response:

Here is one way you can do it, hopefully the inline comments help you understand the logic.

$numbers = "0","1","2","12","50","5041","5042","5043","8888","8889"
$firstInRange = $null

$result = for($i = 0; $i -lt $numbers.Count; $i  ) {
    # Convert this number to int so we can compare it
    [int] $thisNumber = $numbers[$i]
    # if this number   1 is equal to the next number
    if($thisNumber   1 -eq $numbers[$i   1]) {
        # if `$firstInRange` is populated, go to next iteration
        if($null -ne $firstInRange) { continue }
        # else, this is the first number in range, assign it
        $firstInRange = $thisNumber
        # and skip the next logic
        continue
    }

    # if previous condition was `$false` and `$firstInRange` is populated
    if($null -ne $firstInRange) {
        # this is signal to output the range, concatenate first and last
        $firstInRange, $thisNumber -join '-'
        # clear the this variable for next capture
        $firstInRange = $null
        # and skip the next logic
        continue
    }

    # if none of the before were `$true`, just output this number
    $thisNumber
}

$result -join ', ' # => 0-2, 12, 50, 5041-5043, 8888-8889
  • Related