Home > Mobile >  Find the time interval, when there was the greatest number of visitors
Find the time interval, when there was the greatest number of visitors

Time:11-21

I need to find the time interval in which there was a maximum number of visitors. I take the visit time of each visitor from the file. File content example:

09:37,09:46
10:00,10:30
10:10,10:40
10:20,10:50

Expected output based on the file data above:

09:37 - 09:46;1
10:20 - 10:30;3
10:20 - 10:40;2
10:20 - 10:50;1

Actual result:

09:37 - 09:46;1
10:20 - 10:30;4
10:20 - 10:30;4
10:20 - 10:30;4

My code:

public class Algo {
    public void Algo(String pathname) {
        try {
            File myObj = new File(pathname);
            Scanner myReader = new Scanner(myObj);
            ArrayList<String> times = new ArrayList<>();

            LocalTime entranceTime;
            LocalTime leavingTime;

            LocalTime currEntrance;
            LocalTime currLeaving;
            int count;


            while (myReader.hasNextLine()) {
                String data = myReader.nextLine();
                times.add(data);
            }
            myReader.close();
            System.out.println(times);

            for (int i = 0; i < times.size(); i  ) {
                entranceTime = LocalTime.parse(times.get(i).split(",")[0]);
                leavingTime = LocalTime.parse(times.get(i).split(",")[1]);
                count = 1;

                for (int j = 1; j < times.size(); j  ) {
                    currEntrance = LocalTime.parse(times.get(j).split(",")[0]);
                    currLeaving = LocalTime.parse(times.get(j).split(",")[1]);

                    if (!entranceTime.isAfter(currLeaving) && !currEntrance.isAfter(leavingTime)) {
                        count  ;
                        if (currEntrance.compareTo(entranceTime) >= 0) {
                            entranceTime = currEntrance;
                        }
                        if (currLeaving.compareTo(leavingTime) <= 0) {
                            leavingTime = currLeaving;
                        }
                    }
                }
                System.out.println(entranceTime   " - "   leavingTime   ";"   count);
            }
        } catch (FileNotFoundException e) {
            System.out.println("An error occurred.");
            e.printStackTrace();
        }
    }
}

CodePudding user response:

Its easy. for obtain the output you wat just do j=i 1 not j=1 because with this you cont the same again in each iteration, to avoid that just do this

 for (int j = i 1; j < times.size(); j  ) 

then you have the espected output.

  • Related