Verify on CodeGym said
"The program ran too long - Check your code. It looks like you have an infinite loop."
Program runs on IntelliJ and give correct output. Looking for your support on this
package com.codegym.task.task18.task1804;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
/*
Rarest bytes
Enter a file name from the console.
Find the byte or bytes with the minimum number of repetitions.
Display them on the screen, separated by spaces.
Close the IO stream.
Requirements:
• The program should read a file name from the console.
• Use a FileInputStream to read from the file.
• All of the least frequently repeated bytes from the file should be displayed,
separated by spaces.
• The screen output should be displayed in one line.
• The stream used to read the file must be closed.
Filename = CodeGym-task1804_file.txt
*/
public class Solution {
public static void main(String[] args) throws Exception {
ArrayList<Integer> listOfBytes = new ArrayList<>();
String file = getFileName();
int listIndex = 0;
FileInputStream inputStream = new FileInputStream(file);
// read the file and put all byte in an ArrayList
while(inputStream.available() > 0) {
int data = inputStream.read();
listOfBytes.add(listIndex, data);
listIndex++;
}
inputStream.close();
// All of the least frequently repeated bytes from the file should be displayed,
// separated by spaces.
HashMap<Integer,Integer> map = new HashMap<>();
int min = 1;
int count = 0;
boolean minFound = false;
boolean firstByte = false;
String result = "";
for (int i = 0; i<listOfBytes.size(); i++) {
for (int j = 0; j<listOfBytes.size(); j++) {
if (listOfBytes.get(i)==listOfBytes.get(j)) {
count++;
}
}
map.put(listOfBytes.get(i),count);
count = 0;
}
while (!minFound) {
for (HashMap.Entry<Integer,Integer> copy : map.entrySet()) {
if (copy.getValue()==min) {
minFound = true;
if(!firstByte) {
result = copy.getKey().toString();
firstByte = true;
}
else {
result = result + " " + copy.getKey().toString();
}
}
}
if(!minFound) {
min++;
}
}
System.out.println(result);
}
public static String getFileName () throws Exception {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
// String fileLocation = "/Users/peter.schrijver/Tmp/";
String entry = reader.readLine();
// String file = fileLocation + entry;
// return file;
return entry;
}
}