Search code examples
javaarraysgridjava.util.scannervariable-assignment

Why is my Scanner taking too long to convert inputs to a 2D char array?


Scanner to 2D char array taking too long time.

Hi! For some reason unkown to me makes my code take very long time, my only guess is that Scanner is slow however I cant escape it because I need to use it. The size of the seaCard can be anything from 1 * 1 to 10000 * 10000. The cpu time limit is 8 seconds which should be plenty of time to execute this. The whole assignment is to count islands in a grid but I cant even read the data in a timely manner.

The inputs are maps like these

~~~~~
~@@~~
@~~~~.

My code is like this.

public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        int rows = input.nextInt();
        int cols = input.nextInt();
        input.nextLine();
        
        char[][] seaCard = new char[rows][cols];

        // making the map
        for(int i = 0; i < rows; i++){
            String thisRow = input.nextLine();
            for(int j = 0; j < cols; j++){
                seaCard[i][j] = thisRow.charAt(j);
            }
        }
        input.close();

I have tried changing from 2D array to a 1D string array but that didnt change much, I have also tried using next() instead of nextLine().

I expected the code to run smoothly and not take longer than 6s for rows = 10000 and cols = 10000 with an string input of a 10000 string lines of length 10000.

However it just dosent finish, my only idea is that because Im using 2 for loops I get a time complexity of n^2 but I feel like this still shouldnt make it take this long.


Solution

  • This version takes input from a file. The first line should be the number of rows. Nothing needs to be entered from the console.

    public static void main(String[] args) {
        try (Scanner fromFile = new Scanner(new File("C:/yourFilename.txt"))) {
            int rows = fromFile.nextInt(); // read the rows from the file.
            fromFile.nextLine();  // remove EOL from the input buffer
            char[][] seaCard = new char[rows][];
            for (int r = 0; r < rows; r++) {
                seaCard[r] = fromFile.nextLine().toCharArray();
            }
            System.out.println("Done!");
        } catch (IOException ioe) {
            ioe.printStackTrace();
        }
    }