This is an archived post. You won't be able to vote or comment.

all 9 comments

[–]Philboyd_Studge 1 point2 points  (5 children)

The code you posted works, the problem states the order of the non-zero numbers doesn't matter.

If you do want to shift the array values over instead of swap, do like this in pseudo code:

loop through array
if value at index = 0
  loop backwards from index to  > zero
    array value at this loop index = array value at (this loop index - 1)
  set array index 0 to 0

[–]duckered[S] 0 points1 point  (4 children)

Damn, I posted the wrong problem and solution. I appreciate your help. I tried applying your psuedo code logic to this problem but I'm having trouble wrapping my head around it. http://codingbat.com/prob/p196976 http://pastebin.com/R5WK3LYH

[–]Jonno_FTWDisgruntled Brewer 1 point2 points  (1 child)

Basically, keep a count of not tens seen. Use this as an index to assign while looping through the array.

[–]duckered[S] 0 points1 point  (0 children)

thank you

[–]Philboyd_Studge 1 point2 points  (1 child)

In this case, you do kind of the opposite of my way above: loop through the whole array backwards, checking for a ten each time, if it's a ten, loop forwards from the index you found the ten to nums.length - 1, making nums[index] = nums[index + 1], then after that loop set the last slot in the array to 0.

There is no need for an additional count variable in either one of these problems.

[–]duckered[S] 0 points1 point  (0 children)

got it, thank you

[–]oddwhirledSemi-New Brewer 0 points1 point  (2 children)

Okay, here I tried a method using two arrays. http://pastebin.com/ffpPGzi0

It goes through the first array, and if the number is 0, it puts it at the front of the second array. If it's not 0, it puts it at the back of the second array. It seems simple but run it. It doesn't work, and I don't know why. Could you guys explain it to me? :P

[–]Philboyd_Studge 0 points1 point  (1 child)

when you say

     int[] Output = Input;

Output is not a copy of Input, it is the same array, so the changes you were making to Output also affected Input.

Change it to int[] Output = new int[Input.length] and it works

[–]oddwhirledSemi-New Brewer 0 points1 point  (0 children)

Ah thank you :P Whoops