views:

663

answers:

2

Given a file compact.txt that contains no more than 100 integers greater than 0, you need to read the file into an array, then traverse the array removing all the zeros keeping the original order of numbers in tact. And below is my unfinished code.

import java.io.File;
import java.util.Scanner;

public class CompactUtil {
    private static Scanner scan;
    static int[] num = new int[100];

    public static int[] readInArray(String filePath){
        try{
            scan = new Scanner(new File(filePath));
            for(int x=0; scan.hasNext(); x++){
                num[x]=scan.nextInt();
                System.out.print("the original array is : "+num[x]);
            }
        }catch(Exception e){
            System.out.println("You got: "+e.getMessage());
        }

        return num;
    }

    private static int[] removeAndShift(int[] nums, int index){
        for()
    }

    public static int[] removeZeros(int[] nums){
    }

    public static void printArray(int[] nums){
    }

}

public class Driver {
    public static void main(String[] args) {
        int[] num = CompactUtil.readInArray("H:/compact.txt");
    }

}
+1  A: 

First of all, if all the numbers are greater than zero, how do you get zeroes in the array? I think it meant greater/equals to zero or this is pointless.

I am guessing that you're asked to to do this in O(N)? Because otherwise it's trivial

What you need to do is to run with two indices. One of them for locations where you'll put stuff after the shift (destination), and one of them for scanning all items in the array and finding what to shift (source).

Your "source" will move faster since it will also read 0s.

Start out with both of them at index 0. Then do a loop where you constantly move the source forward. Every time that the source encounters a non-zero, copy it into the destination and then increase the destination index by one.

This way, your destination will "leave behind" a sequence of numbers without zeros. Once you're done, the destination will have the "Real size" of the array after the shifting.

Uri
A: 

If this was a real situation and not howmork (which you should have clearly stated in your question), the specification would only state the input data and the outcome. It would not specify that the data would have to be read into an array, and then remove some of the data.

So, in a real situation the zero values would simply not be added to the array.

Guffa