Hello friends.
Can anyone help me with my code ?
It seems to work perfectly with every file I put through.
I've also tried to manually add some bytes matching the amount of maximum repetition in the HashMap and everything was displayed perfectly.
What is wrong ?
Thanks.
package fr.codegym.task.task18.task1803;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
/*
Les octets les plus fréquents
*/
public class Solution {
public static void main(String[] args) throws Exception {
//Reading a file path from the console.
BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
FileInputStream fileInputStream = new FileInputStream(bf.readLine());
// Adding every byte of the file to an array.
ArrayList <Integer> listOfByte = new ArrayList <>();
while (fileInputStream.available() > 0) {
listOfByte.add(fileInputStream.read());
}
HashMap <Integer, Integer> listOfMaxRepeatedBytes = new HashMap <>();
int maxRepetition = 0;
int byteWithMaxRepetition;
//Counting the repetition of every byte.
for (Integer byte1 : listOfByte) {
int repetitionCounter = 0;
for (Integer byte2 : listOfByte) {
if (byte2.equals(byte1)) {
repetitionCounter++;
}
// Adding the byte to the HashMap if its number of repetition equals the maximum repetition value.
// Some bytes might be added in the beginning of the process even though their repetition is not equal
// to what the final maximumRepetition value is going to be.
else if (repetitionCounter >= maxRepetition) {
maxRepetition = repetitionCounter;
byteWithMaxRepetition = byte1;
listOfMaxRepeatedBytes.put(byteWithMaxRepetition, maxRepetition);
}
}
}
// Displaying the bytes if their repetition equals the final maximum repetition ONLY.
for (Map.Entry <Integer, Integer> entry : listOfMaxRepeatedBytes.entrySet()) {
if (entry.getValue() == maxRepetition) {
System.out.print(entry.getKey() + " ");
}
}
fileInputStream.close();
bf.close();
}
}