Created
August 23, 2018 03:14
-
-
Save WolfDan/3257ed42164f002a92a6b617b72d61ff to your computer and use it in GitHub Desktop.
First UNAL exercise...
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.first; | |
import java.io.BufferedReader; | |
import java.io.FileReader; | |
import java.io.IOException; | |
import java.util.Collections; | |
import java.util.Comparator; | |
import java.util.HashMap; | |
import java.util.Map; | |
public class Main { | |
private static final String FILENAME = "c::\\path-to\\text.txt"; | |
private static Map<String, Integer> counter = new HashMap<String, Integer>(); | |
public static void main(String[] args) { | |
try (BufferedReader br = new BufferedReader(new FileReader(FILENAME))) { | |
String sCurrentLine; | |
int i = 0; | |
int maxLines = -1; | |
while ((sCurrentLine = br.readLine()) != null) { | |
if (maxLines == -1) { | |
maxLines = Integer.parseInt(sCurrentLine); | |
continue; | |
} | |
if (i < maxLines) { | |
String maxLetter = readLine(sCurrentLine); | |
System.out.println("The most selected option in the question # " + Integer.toString(i) + " is " | |
+ maxLetter + " with " + Integer.toString(counter.get(maxLetter)) + " selections"); | |
counter.clear(); | |
} | |
i++; | |
} | |
} catch (IOException e) { | |
e.printStackTrace(); | |
} | |
} | |
private static String readLine(String line) { | |
String[] letters = line.split(""); | |
for (String letter : letters) { | |
counter.put(letter, counter.getOrDefault(letter, 0) + 1); | |
} | |
return Collections.max(counter.entrySet(), Comparator.comparingInt(Map.Entry::getValue)).getKey(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment