secondplace
secondplace

Reputation: 588

Powershell processing arrays in a multi dimensional array after defined number

if i need to process all arrays in a multi dimensional array after skipping the first one how would i go about this?

in this case adding + 5 to each value. what if i want to start at the second array $mdarr[1]<

cls
$mdarr = @()
$i = @()
$ii = @()
$mdarr = @((0,1,2,3,4),(5,6,7,8,9),(10,11,12,13,14))

for ($i = 0; $i -lt $mdarr.Length; ++$i){
    for ($ii = 0; $ii -lt $mdarr[$i].Length; ++$i){
    $mdarr = $mdarr[$i][$ii] + 5
    }
}
write-host $mdarr

there is so much wrong with the above. the result i'm looking for should be:

((0,1,2,3,4),(10,11,12,13,14),(15,16,17,18,19))

how would this be done?

Upvotes: 0

Views: 108

Answers (1)

vonPryz
vonPryz

Reputation: 24091

The problem is in updating the array contents. All that's needed is a nested loop to process elements in the inner arrays with appropriate indexing. Like so,

$mdarr = @((0,1,2,3,4),(5,6,7,8,9),(10,11,12,13,14))
for($i = 1; $i -lt $mdarr.Length; ++$i) {
    for($j = 0; $j -lt $mdarr[$i].Length; ++$j) {
        $mdarr[$i][$j] += 5
    }
}

$mdarr[1]
10
11
12
13
14

As why didn't the original work, let's analyze the code and see what was wrong:

# This starts from 1st element (index 0), which was to be skipped. Bug
for ($i = 0; $i -lt $mdarr.Length; ++$i){

    # Loop counters $ii and $i are confusing, name is almost same
    # What's more, $i is increased instead of $ii. Bug 
    for ($ii = 0; $ii -lt $mdarr[$i].Length; ++$i){
        # This doesn't make sense. It's overwriting the whole 
        # source array-of-arrays with a single value.
        # The array cell was to be updated instead. Bug
        $mdarr = $mdarr[$i][$ii] + 5
    }
}

To sum up, the idea was there. Due indexing bugs and inappropriate assignment operation, the outcome was wrong. Still, fixing is quite straightforward, as the main logic was okay.

Upvotes: 2

Related Questions