SashaZ
SashaZ

Reputation: 403

Array after an element is > 0 change all elements to that value until next non zero value

I have an array that is for example

[0.0, 0.0, 55.0, 0.0, 0.0, 55.0, 55.0, 22.0, 0.0, 55.0] 

How can I change the element with 0 value if the previous value > 0? so

[0.0, 0.0, 55.0, 0.0, 0.0, 55.0, 55.0, 22.0, 0.0, 55.0]

becomes

[0.0, 0.0, 55.0, 55.0, 55.0, 55.0, 55.0, 22.0, 22.0, 55.0]

I have tried the following and it removes the zeros and nothing else.

func weightArrayRemovedZero(array: [Double])->[Double]{

 var arrayToAlter = [Double]()

 for(index,item) in array.enumerated() {

   print("The \(item) is at index:\(index)")

   if item == 0.0 {
     if index > 0 && index < array.count - 1 {

       if array[index - 1] != 0.0 {
         let nonZeroElement = array[index - 1]
         arrayToAlter.append(nonZeroElement)
       }
     }


   } else {
     arrayToAlter.append(item)
   }
 }

 return arrayToAlter
}

Upvotes: 0

Views: 561

Answers (3)

David Berry
David Berry

Reputation: 41236

map seems to be the natural approach to me:

var last = 0.0
let mapped = values.map { elem -> (Double) in
    last = elem > 0.0 ? elem : last
    return last
}

Generally speaking, map is your go to when you want to change one collection into another collection with a one-to-one element mapping.

Upvotes: 2

MirekE
MirekE

Reputation: 11555

Another option:

var array = [0.0, 0.0, 55.0, 0.0, 0.0, 55.0, 55.0, 22.0, 0.0, 55.0]

for i in array.indices {
    if i == 0 { continue }
    if array[i] == 0  && array[i-1] != 0 {
        array[i] = array[i-1]
     }
}

// [0, 0, 55, 55, 55, 55, 55, 22, 22, 55]

Upvotes: 0

Callam
Callam

Reputation: 11539

Try this out

var array = [0.0, 0.0, 55.0, 0.0, 0.0, 55.0, 55.0, 22.0, 0.0, 55.0]

array.enumerated().forEach {
    array[$0] = $1 == 0 &&
        array.indices.contains($0 - 1) &&
        array[$0 - 1] > 0 ? array[$0 - 1] : $1
}

print(array)

Upvotes: 0

Related Questions