Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

P3123 Asvarisch Michael Task-2 #108

Open
wants to merge 1 commit into
base: task-2
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
63 changes: 53 additions & 10 deletions src/main/java/ru/ifmo/cet/javabasics/WarAndPeaceExercise.java
Original file line number Diff line number Diff line change
@@ -1,21 +1,64 @@
package ru.ifmo.cet.javabasics;

import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.Path;
import java.nio.file.Paths;

import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.util.*;


public class WarAndPeaceExercise {

public static String warAndPeace() {
public static String warAndPeace() throws IOException {
final Path tome12Path = Paths.get("src", "main", "resources", "WAP12.txt");
final Path tome34Path = Paths.get("src", "main", "resources", "WAP34.txt");

// TODO map lowercased words to its amount in text and concatenate its entries.
// TODO If word "котик" occurred in text 23 times then its entry would be "котик - 23\n".
// TODO Entries in final String should be also sorted by amount and then in alphabetical order if needed.
// TODO Also omit any word with lengths less than 4 and frequency less than 10
List<String> rows;

throw new UnsupportedOperationException();
}
rows = Files.readAllLines(tome12Path, Charset.forName("windows-1251"));
rows.addAll(Files.readAllLines(tome34Path, Charset.forName("windows-1251")));
String[] words = Arrays.toString(rows.toArray()).toLowerCase().split("[^a-zа-я]+");

Map<String, Integer> wordsMap = new HashMap<>();

for (String word : words) {
if (word.length() >= 4) {
wordsMap.put(word, wordsMap.getOrDefault(word, 0) + 1);
}
}

SortedSet<Map.Entry<String, Integer>> sorted = new TreeSet<>(


new Comparator<Map.Entry<String, Integer>>() {
public int compare(Map.Entry<String, Integer> a, Map.Entry<String, Integer> b) {

if (a.getValue().equals(b.getValue())) {
return a.getKey().compareTo(b.getKey());
}
else {
return b.getValue() - a.getValue();
}
}
}
);

}

sorted.addAll(wordsMap.entrySet());


StringBuilder result = new StringBuilder();


for (Map.Entry<String, Integer> entry : sorted) {

if (entry.getValue() >= 10) {
result.append(entry.getKey()).append(" - ").append(entry.getValue()).append("\n");
}
}

return result.deleteCharAt(result.length()-1).toString();
}
}