Skip to content
Open
Show file tree
Hide file tree
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
9 changes: 4 additions & 5 deletions task01/src/com/example/task01/Task01Main.java
Original file line number Diff line number Diff line change
@@ -1,20 +1,17 @@
package com.example.task01;

import java.io.IOException;
import java.util.Objects;
import java.util.function.Function;
import java.util.function.Predicate;

public class Task01Main {
public static void main(String[] args) throws IOException {

// TODO С корректно реализованным методом ternaryOperator должен компилироваться и успешно работать следующий код:

/*
Predicate<Object> condition = Objects::isNull;
Function<Object, Integer> ifTrue = obj -> 0;
Function<CharSequence, Integer> ifFalse = CharSequence::length;
Function<String, Integer> safeStringLength = ternaryOperator(condition, ifTrue, ifFalse);
*/

}

Expand All @@ -23,7 +20,9 @@ public static <T, U> Function<T, U> ternaryOperator(
Function<? super T, ? extends U> ifTrue,
Function<? super T, ? extends U> ifFalse) {

return null; // your implementation here
if (condition == null || ifTrue == null || ifFalse == null)
throw new NullPointerException();

return c -> condition.test(c) ? ifTrue.apply(c) : ifFalse.apply(c); // your implementation here
}
}
12 changes: 7 additions & 5 deletions task02/src/com/example/task02/Task02Main.java
Original file line number Diff line number Diff line change
Expand Up @@ -5,19 +5,21 @@
public class Task02Main {

public static void main(String[] args) {

/*
cycleGrayCode(2)
.limit(10)
.forEach(System.out::println);
*/

}

public static IntStream cycleGrayCode(int n) {
if (n < 1 || n > 16) {
throw new IllegalArgumentException();
}

return null; // your implementation here
// количество кодов Грея (2^n)
final int N = 1 << n;

return IntStream.iterate(0, i -> (i + 1) % N)
.map(i -> i ^ (i >> 1));
}

}
29 changes: 28 additions & 1 deletion task03/src/com/example/task03/Task03Main.java
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package com.example.task03;

import java.util.Comparator;
import java.util.Iterator;
import java.util.function.BiConsumer;
import java.util.stream.Stream;

Expand All @@ -22,6 +23,32 @@ public static <T> void findMinMax(
Comparator<? super T> order,
BiConsumer<? super T, ? super T> minMaxConsumer) {

// your implementation here
// 1. Получаем Iterator из Stream. Это терминальная/потребляющая операция.
Iterator<? extends T> iterator = stream.iterator();

T min = null;
T max = null;

// 2. Инициализация: Если стрим не пуст, берем первый элемент.
if (iterator.hasNext()) {
T firstElement = iterator.next();
min = firstElement;
max = firstElement;
}

// 3. Обход: Проходим по оставшимся элементам, обновляя min и max.
while (iterator.hasNext()) {
T currentElement = iterator.next();

// Сравниваем с max
// order.compare(a, b) > 0 означает, что 'a' больше 'b'
if (order.compare(currentElement, max) > 0) max = currentElement;


// Сравниваем с min
// order.compare(a, b) < 0 означает, что 'a' меньше 'b'
if (order.compare(currentElement, min) < 0) min = currentElement;
}
minMaxConsumer.accept(min, max);
}
}
25 changes: 21 additions & 4 deletions task04/src/com/example/task04/Task04Main.java
Original file line number Diff line number Diff line change
@@ -1,11 +1,28 @@
package com.example.task04;

import java.io.*;
import java.util.Comparator;
import java.util.Map;
import java.util.function.ToLongFunction;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class Task04Main {

public static void main(String[] args) {

// your implementation here

// Читаем строки из System.in (BufferedReader не нужен, lines() делает это за нас)
new BufferedReader(new InputStreamReader(System.in))
.lines()
.map(String::toLowerCase)
.flatMap(x -> Stream.of(x.split("[^a-zа-яё0-9]")))
.filter(x -> !x.isEmpty())
.collect(Collectors.groupingBy( x -> x, Collectors.counting()))
.entrySet()
.stream()
.sorted(Map.Entry.<String, Long>comparingByValue().reversed()
.thenComparing(Map.Entry.comparingByKey()))
.limit(10)
.forEach(i -> System.out.print(i.getKey() + "\n"));
}

}
}
27 changes: 27 additions & 0 deletions task05/src/com/example/task05/MailMessage.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
package com.example.task05;

public class MailMessage implements Sendable<String> {
private final String from;
private final String to;
private final String content;

public MailMessage(String from, String to, String content) {
this.from = from;
this.to = to;
this.content = content;
}

public String getFrom() {
return from;
}

@Override
public String getTo() {
return to;
}

@Override
public String getContent() {
return content;
}
}
53 changes: 53 additions & 0 deletions task05/src/com/example/task05/MailService.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
package com.example.task05;

import java.util.*;
import java.util.function.Consumer;

public class MailService<T> implements Consumer<Sendable<T>> {

// Почтовый ящик: Получатель -> Список содержимого T
private final Map<String, List<T>> mailBox;

public MailService() {
// Инициализируем Map с использованием HashMap.
// Используем Collectors.groupingBy, чтобы упростить обработку в accept,
// но здесь достаточно обычной HashMap.
this.mailBox = new HashMap<>();
}

public Map<String, List<T>> getMailBox() {
// Мы возвращаем Map, которая перехватывает вызов get(key)
// и возвращает пустой список, если ключ отсутствует, вместо null.

return new AbstractMap<String, List<T>>() {
@Override
public List<T> get(Object key) {
if (mailBox.containsKey(key)) {
return mailBox.get(key);
}
// если ключ не существует, возвращаем пустой список (вместо null).
return Collections.emptyList();
}

// минимальный набор для AbstractMap)
@Override
public Set<Entry<String, List<T>>> entrySet() {
return mailBox.entrySet();
}
};
}

// Реализация Consumer.accept для обработки одного элемента (сообщения/зарплаты)
@Override
public void accept(Sendable<T> item) {
String recipient = item.getTo();
T content = item.getContent();

// Если получателя нет в Map, добавляем его с новым списком.
// В противном случае, получаем список и добавляем в него.

// Map.computeIfAbsent — самый чистый способ для такой логики
this.mailBox.computeIfAbsent(recipient, k -> new ArrayList<>())
.add(content);
}
}
27 changes: 27 additions & 0 deletions task05/src/com/example/task05/Salary.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
package com.example.task05;

public class Salary implements Sendable<Integer> {
private final String from; // Имя организации
private final String to; // Имя получателя
private final int salary; // Сумма

public Salary(String from, String to, int salary) {
this.from = from;
this.to = to;
this.salary = salary;
}

public String getFrom() {
return from;
}

@Override
public String getTo() {
return to;
}

@Override
public Integer getContent() {
return salary;
}
}
3 changes: 1 addition & 2 deletions task05/src/com/example/task05/Task05Main.java
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@ public class Task05Main {

public static void main(String[] args) {

/*

// Random variables
String randomFrom = "..."; // Некоторая случайная строка. Можете выбрать ее самостоятельно.
Expand Down Expand Up @@ -88,7 +87,7 @@ public static void main(String[] args) {
assert salaries.get(randomTo).equals(Arrays.asList(randomSalary)) : "wrong salaries mailbox content (3)";


*/


}

Expand Down