1

Given an array (for example, [ 1, 0, 2, 0, 0, 3, 4 ]), implement methods that moves the non-zero elements to the beginning of the array (the rest of the elements don't matter)

I have implemented as follows, it works but I wonder shorter way of doing it?

import Foundation

var inputArray = [ 1, 0, 2, 0, 0, 3, 4 ]

func remoZeros (inputArray :[Int]) -> [Int]
{
  var nonZeroArray = [Int]()
  var zeroArray = [Int]()

  for item in inputArray
  {
    if item != 0
    {
      nonZeroArray.append(item)
    }
    else
    {
      zeroArray.append(item)
    }
  }

return nonZeroArray + zeroArray

}

var result = remoZeros (inputArray: inputArray)
9
  • pay attention to the fact that the problem does not specify order, only that non-zero should be first Commented Oct 18, 2018 at 21:11
  • @PaulDegnan, could u please illustrate your approach with an example? Commented Oct 18, 2018 at 21:12
  • This is a code review. You should post this at codereview.stackexchange.com and then delete it from here. Commented Oct 18, 2018 at 21:15
  • If the relative order of the elements doesn't matter, then you want partition(by:). Commented Oct 18, 2018 at 21:33
  • 4
    inputArray.partition(by: { $0 == 0 }) – note that this mutates the original array in-place rather than returning a new one. Commented Oct 18, 2018 at 21:38

1 Answer 1

2

You can try

var inputArray = [ 1, 0, 2, 0, 0, 3, 4 ]

func remoZeros (inputArray :[Int]) -> [Int] {

   return inputArray.filter{$0 != 0} + inputArray.filter{$0 == 0}
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.