DEV Community

Discussion on: 6-10PM challenge problem #001

Collapse
 
earlware profile image
EarlWare

Swift solution:

import Foundation

/*
 6-10PM Challenge part 1

@param mixedArray is a ordered list of Ints with zeros mixed in randomly.

 @return the same list of Ints with order preserved, except that all the zeros have been moved to the end.
 */
func zerosToEnd(mixedArray:[Int]) -> [Int] {
    return mixedArray.filter({ $0 != 0})+mixedArray.filter({ $0 == 0})
}


let example1 = [12, 3, 0, 2, 8, 11, 0, 0, 6, 4, 0, 5, 7, 0, 8, 9, 0]
let solution1 = [12, 3, 2, 8, 11, 6, 4, 5, 7, 8, 9, 0, 0, 0, 0, 0, 0]


print(zerosToEnd(mixedArray: example1), "\n")
print("Testing example1 matches solution1:     ", (zerosToEnd(mixedArray: example1) == solution1), "\n\n")

Output:

[12, 3, 2, 8, 11, 6, 4, 5, 7, 8, 9, 0, 0, 0, 0, 0, 0] 

Testing example1 matches output1:      true 


Program ended with exit code: 0

I opted to just filter out all the zeros entirely/filter everything but zeros, then recombine in the correct order.