Printing out a Random Array

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Laharl
    Recognized Expert Contributor
    • Sep 2007
    • 849

    #46
    It is something like that, only not quite. You want to check if a[i] is 0 as well each time. If it is, you don't want to do anything immediately. If it isn't, you can set a[k] to a[i] and a[i] to 0, and then use a break; statement to leave the loop.

    Also, since you're sliding zeroes down the array a few spots at a time, each zero is going to come up several times. Thus, sum is going to be much larger than the actual number of zeroes. You're better off doing your counting up at the top, when you're filling the array.

    Comment

    • JosAH
      Recognized Expert MVP
      • Mar 2007
      • 11453

      #47
      Oh dear; this thread is approaching 50 replies already; a serious sign that this
      little problem will never be solved. The OP should design a bit first before writing
      almost random code.

      Think of an index 't' ('t' for trash). Starting at that index value and to the right of it
      the array contains trash. Initially t == array.length.

      Also think of an index 'i' that iterates over the interval [0, t) (exclusive). Each time
      array[i] equals zero move the elements in the interval [i+1, t) to [i, t-1) and
      decrement t. If the element array[i] was zero, don't increment i.

      Repeat until i >= t and you're done.

      kind regards,

      Jos

      Comment

      • BigDaddyLH
        Recognized Expert Top Contributor
        • Dec 2007
        • 1216

        #48
        Perhaps some example code is in order.

        [CODE=Java]public class Shift {
        void shift(int[] source) {
        int[] destination = new int[source.length];
        int di = 0;
        for(int si=0; si<source.lengt h; si++) {
        if (isEven(source[si])) {
        destination[di] = source[si];
        di++;
        }
        }
        //here di is the count of elements copied to destination
        //...
        }

        boolean isEven(int n) {
        return n % 2 == 0;
        }
        }[/CODE]
        This code copies the even numbers from source to destination. Because the two arrays have the same length, there may be unused cells in destination, but after the loop, you know the count of elements copied is di.

        Question: what if I hadn't created a second array and just copied from the given array back to itself? Hmmm...

        Comment

        Working...