Skip to content

Instantly share code, notes, and snippets.

@AdrianFerreyra
Created November 2, 2017 03:02
Show Gist options
  • Save AdrianFerreyra/205275ec4f240c0d79b67864126a23e6 to your computer and use it in GitHub Desktop.
Save AdrianFerreyra/205275ec4f240c0d79b67864126a23e6 to your computer and use it in GitHub Desktop.
Given an array of numbers, reset the array to put all the non-zero numbers in front of all the zeros in the array, then return the count of non-zero numbers. e.g., for an input array of [3,0,2,0,0,1,0,4], you’ll end up with a return value of 4 and an array of [3,2,1,4,0,0,0,0]
import Foundation
/*Given an array of numbers, reset the array to put all the non-zero numbers in front of all the zeros in the array, then return the count of non-zero numbers.
e.g., for an input array of [3,0,2,0,0,1,0,4], you’ll end up with a return value of 4 and an array of [3,2,1,4,0,0,0,0]
*/
//idea
//get first zero
//return func(array.removeZero) + [0]
//do until array.firstZero() is nil -> there, return array
func get<T: Equatable>(value: T, toBottomOf array: [T]) -> [T] {
func removeFirst(value: T, from array: [T]) -> [T] {
guard let firstItem = array.first else {
return array
}
if firstItem == value {
return Array(array.dropFirst())
} else {
return [firstItem] + removeFirst(value: value, from: Array(array.dropFirst()))
}
}
guard array.filter({ $0 == value}).count > 0 else {
return array
}
return get(value: value, toBottomOf: removeFirst(value: value, from: array)) + [value]
}
let array = [3,0,2,0,0,1,0,4]
let resetArray = get(value: 0, toBottomOf: array)
@AdrianFerreyra
Copy link
Author

You could always filter the zeros out and then create a new array with the zeros.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment