-
Notifications
You must be signed in to change notification settings - Fork 0
Java05. ДЗ 05, Егоров Антон #5
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
Open
pvktk
wants to merge
2
commits into
master
Choose a base branch
from
hw_stream
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or 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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,5 @@ | ||
| abracdadabra dmvdhg | ||
| tksdl | ||
|
|
||
| askdlcewline kabra | ||
|
|
This file contains hidden or 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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,45 @@ | ||
| <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" | ||
| xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> | ||
| <modelVersion>4.0.0</modelVersion> | ||
|
|
||
| <groupId>1</groupId> | ||
| <artifactId>hw_05</artifactId> | ||
| <version>0.0.1-SNAPSHOT</version> | ||
| <packaging>jar</packaging> | ||
|
|
||
| <name>hw_05</name> | ||
| <url>http://maven.apache.org</url> | ||
|
|
||
| <properties> | ||
| <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> | ||
| </properties> | ||
|
|
||
|
|
||
| <build> | ||
| <plugins> | ||
| <plugin> | ||
| <artifactId>maven-compiler-plugin</artifactId> | ||
| <configuration> | ||
| <source>1.8</source> | ||
| <target>1.8</target> | ||
| <encoding>UTF-8</encoding> | ||
| </configuration> | ||
| </plugin> | ||
| </plugins> | ||
| </build> | ||
|
|
||
| <dependencies> | ||
| <dependency> | ||
| <groupId>junit</groupId> | ||
| <artifactId>junit</artifactId> | ||
| <version>4.12</version> | ||
| <scope>test</scope> | ||
| </dependency> | ||
| <dependency> | ||
| <groupId>com.google.guava</groupId> | ||
| <artifactId>guava</artifactId> | ||
| <version>19.0</version> | ||
| <scope>test</scope> | ||
| </dependency> | ||
| </dependencies> | ||
| </project> |
This file contains hidden or 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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,29 @@ | ||
| package hw_05; | ||
|
|
||
| import java.util.Arrays; | ||
| import java.util.List; | ||
|
|
||
| public class Album { | ||
|
|
||
| private final String name; | ||
| private final List<Track> tracks; | ||
| private final Artist artist; | ||
|
|
||
| public Album(Artist artist, String name, Track... tracks) { | ||
| this.name = name; | ||
| this.tracks = Arrays.asList(tracks); | ||
| this.artist = artist; | ||
| } | ||
|
|
||
| public String getName() { | ||
| return name; | ||
| } | ||
|
|
||
| public List<Track> getTracks() { | ||
| return tracks; | ||
| } | ||
|
|
||
| public Artist getArtist() { | ||
| return artist; | ||
| } | ||
| } |
This file contains hidden or 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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,14 @@ | ||
| package hw_05; | ||
|
|
||
| public class Artist { | ||
|
|
||
| private final String name; | ||
|
|
||
| public Artist(String name) { | ||
| this.name = name; | ||
| } | ||
|
|
||
| public String getName() { | ||
| return name; | ||
| } | ||
| } |
This file contains hidden or 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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,98 @@ | ||
| package hw_05; | ||
|
|
||
| import java.util.Arrays; | ||
| import java.util.Comparator; | ||
| import java.util.List; | ||
| import java.util.Map; | ||
| import java.util.Optional; | ||
| import java.util.stream.Collectors; | ||
| import java.util.stream.IntStream; | ||
| import java.util.stream.Stream; | ||
|
|
||
| public final class FirstPartTasks { | ||
|
|
||
| private FirstPartTasks() {} | ||
|
|
||
| // Список названий альбомов | ||
| public static List<String> allNames(Stream<Album> albums) { | ||
| return albums.map(Album::getName).collect(Collectors.toList()); | ||
| } | ||
|
|
||
| // Список названий альбомов, отсортированный лексикографически по названию | ||
| public static List<String> allNamesSorted(Stream<Album> albums) { | ||
| return albums | ||
| .map(Album::getName) | ||
| .sorted() | ||
| .collect(Collectors.toList()); | ||
| } | ||
|
|
||
| // Список треков, отсортированный лексикографически по названию, включающий все треки альбомов из 'albums' | ||
| public static List<String> allTracksSorted(Stream<Album> albums) { | ||
| return albums | ||
| .flatMap(a -> a.getTracks().stream()) | ||
| .map(Track::getName) | ||
| .sorted() | ||
| .collect(Collectors.toList()); | ||
| } | ||
|
|
||
| // Список альбомов, в которых есть хотя бы один трек с рейтингом более 95, отсортированный по названию | ||
| public static List<Album> sortedFavorites(Stream<Album> s) { | ||
| return s.filter(a -> a.getTracks().stream().anyMatch(t -> t.getRating() > 95)) | ||
| .sorted(Comparator.comparing(Album::getName)) | ||
| .collect(Collectors.toList()); | ||
| } | ||
|
|
||
| // Сгруппировать альбомы по артистам | ||
| public static Map<Artist, List<Album>> groupByArtist(Stream<Album> albums) { | ||
| return albums.collect(Collectors.groupingBy(Album::getArtist, Collectors.toList())); | ||
| } | ||
|
|
||
| // Сгруппировать альбомы по артистам (в качестве значения вместо объекта 'Artist' использовать его имя) | ||
| public static Map<Artist, List<String>> groupByArtistMapName(Stream<Album> albums) { | ||
| return albums.collect(Collectors | ||
| .groupingBy(Album::getArtist, | ||
| Collectors.mapping(Album::getName, | ||
| Collectors.toList()))); | ||
| } | ||
|
|
||
| // Число повторяющихся альбомов в потоке | ||
| public static long countAlbumDuplicates(Stream<Album> albums) { | ||
| return albums | ||
| .collect(Collectors.groupingBy(Album::getName, Collectors.counting())) | ||
| .entrySet().stream().filter(en -> en.getValue() > 1).count(); | ||
| } | ||
|
|
||
| // Альбом, в котором максимум рейтинга минимален | ||
| // (если в альбоме нет ни одного трека, считать, что максимум рейтинга в нем --- 0) | ||
| public static Optional<Album> minMaxRating(Stream<Album> albums) { | ||
| return albums.min(Comparator | ||
| .comparingInt( | ||
| a -> a.getTracks() | ||
| .stream() | ||
| .mapToInt(Track::getRating) | ||
| .max().orElse(0))); | ||
| } | ||
|
|
||
| // Список альбомов, отсортированный по убыванию среднего рейтинга его треков (0, если треков нет) | ||
| public static List<Album> sortByAverageRating(Stream<Album> albums) { | ||
| return albums.sorted(Comparator.comparingDouble(a -> a.getTracks() | ||
| .stream().mapToInt(t -> -t.getRating()).average().orElse(0))).collect(Collectors.toList()); | ||
| } | ||
|
|
||
| // Произведение всех чисел потока по модулю 'modulo' | ||
| // (все числа от 0 до 10000) | ||
| public static int moduloProduction(IntStream stream, int modulo) { | ||
| return stream.reduce(1, (a, b) -> a * b % modulo); | ||
| } | ||
|
|
||
| // Вернуть строку, состояющую из конкатенаций переданного массива, и окруженную строками "<", ">" | ||
| // см. тесты | ||
| public static String joinTo(String... strings) { | ||
| return Arrays.stream(strings).collect(Collectors.joining(", ", "<", ">")); | ||
| } | ||
|
|
||
| // Вернуть поток из объектов класса 'clazz' | ||
| public static <R> Stream<R> filterIsInstance(Stream<?> s, Class<R> clazz) { | ||
| return (Stream<R>) s.filter(cl -> clazz.isInstance(cl)); | ||
| } | ||
| } |
This file contains hidden or 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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,73 @@ | ||
| package hw_05; | ||
|
|
||
| import java.io.IOException; | ||
| import java.nio.file.Files; | ||
| import java.nio.file.Paths; | ||
| import java.util.Comparator; | ||
| import java.util.List; | ||
| import java.util.Map; | ||
| import java.util.Map.Entry; | ||
| import java.util.Random; | ||
| import java.util.function.Supplier; | ||
| import java.util.stream.Collector; | ||
| import java.util.stream.Collectors; | ||
| import java.util.stream.Stream; | ||
|
|
||
| public final class SecondPartTasks { | ||
|
|
||
| private SecondPartTasks() {} | ||
|
|
||
| // Найти строки из переданных файлов, в которых встречается указанная подстрока. | ||
| public static List<String> findQuotes(List<String> paths, CharSequence sequence) { | ||
| return paths.stream() | ||
| .flatMap(p -> { | ||
| try { | ||
| return Files.lines(Paths.get(p)); | ||
| } catch (IOException e) { | ||
| return null; | ||
| } | ||
| }) | ||
| .filter(s -> s.contains(sequence.toString())) | ||
| .collect(Collectors.toList()); | ||
| } | ||
|
|
||
| // В квадрат с длиной стороны 1 вписана мишень. | ||
| // Стрелок атакует мишень и каждый раз попадает в произвольную точку квадрата. | ||
| // Надо промоделировать этот процесс с помощью класса java.util.Random и посчитать, какова вероятность попасть в мишень. | ||
| public static double piDividedBy4() { | ||
| //Random.doubles(10000).collect(() -> new) | ||
| Random r = new Random(12345); | ||
| final int numberOfExperiments = 10000; | ||
|
|
||
| double experimentCount = | ||
| Stream.generate((Supplier<double[]>) () -> | ||
| new double[] {r.nextDouble(), r.nextDouble()}) | ||
| .limit(numberOfExperiments) | ||
| .filter(p -> Math.pow(p[0] - 0.5, 2) + Math.pow(p[1] - 0.5, 2) <= 0.25) | ||
| .count(); | ||
|
|
||
| return experimentCount / numberOfExperiments; | ||
| } | ||
|
|
||
| // Дано отображение из имени автора в список с содержанием его произведений. | ||
| // Надо вычислить, чья общая длина произведений наибольшая. | ||
| public static String findPrinter(Map<String, List<String>> compositions) { | ||
| return compositions | ||
| .entrySet() | ||
| .stream() | ||
| .max(Comparator.comparingInt(entr -> entr.getValue() | ||
| .stream() | ||
| .collect(Collectors.summingInt(String::length)))) | ||
| .map(Entry::getKey) | ||
| .orElse(null); | ||
| } | ||
|
|
||
| // Вы крупный поставщик продуктов. Каждая торговая сеть делает вам заказ в виде Map<Товар, Количество>. | ||
| // Необходимо вычислить, какой товар и в каком количестве надо поставить. | ||
| public static Map<String, Integer> calculateGlobalOrder(List<Map<String, Integer>> orders) { | ||
| return orders.stream() | ||
| .flatMap(m -> m.entrySet().stream()) | ||
| .collect(Collectors.groupingBy(ent -> ent.getKey(), | ||
| Collectors.summingInt(ent -> ent.getValue()))); | ||
| } | ||
| } | ||
This file contains hidden or 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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,20 @@ | ||
| package hw_05; | ||
|
|
||
| public class Track { | ||
|
|
||
| private final String name; | ||
| private final int rating; | ||
|
|
||
| public Track(String name, int rating) { | ||
| this.name = name; | ||
| this.rating = rating; | ||
| } | ||
|
|
||
| public String getName() { | ||
| return name; | ||
| } | ||
|
|
||
| public int getRating() { | ||
| return rating; | ||
| } | ||
| } |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
.mapToInt(String::length).sum()