Created
April 8, 2025 12:54
-
-
Save shvyrev/a5ec439a874afbe4ee3c7122b2ff3b07 to your computer and use it in GitHub Desktop.
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
package org.acme; | |
import java.util.ArrayList; | |
import java.util.Collection; | |
import java.util.Collections; | |
import java.util.List; | |
import java.util.stream.Collectors; | |
import java.util.stream.Stream; | |
import static java.util.function.Predicate.not; | |
/** | |
* | |
* Задача 1. | |
* Есть массив слов в котором может быть любое число элементов разной длины. | |
* Необходимо этот массив преобразовать в массив строк всех возможных комбинаций букв из этих слов пример: | |
* | |
* Пример входящего массива ["on", "job", "lake"]. | |
* Результат выходящего: | |
* [ | |
* "ojl", | |
* "oja", | |
* "ojk", | |
* "oje", | |
* "ool", | |
* "ooa", | |
* "ook", | |
* "ooe", | |
* "obl", | |
* "oba", | |
* "obk", | |
* "obe", | |
* "njl", | |
* "nja", | |
* "njk", | |
* "nje", | |
* .... | |
* ] | |
* | |
* function run(words: string[]): string[] { | |
* // напишите свой код | |
* } | |
*/ | |
public class Alg { | |
public static void main(String[] args) { | |
var result = run("on", "job", "lake"); | |
result.forEach(System.out::println); | |
} | |
/** | |
* В качестве реализации выбрал обычный map-reduce, т.к. все элементы уже приходят как массив символов, | |
* @param words - входящий массив слов | |
* @return список строк всех возможных комбинаций букв из этих слов | |
*/ | |
public static List<String> run(String... words) { | |
return Stream.of(words) | |
.filter(not(String::isEmpty) | |
.and(not(String::isBlank))) | |
.map(w -> w.chars().mapToObj(c -> (char) c) | |
.map(c -> Stream.of(c).collect(Collectors.toCollection(ArrayList::new))) | |
.collect(Collectors.toList())) | |
.reduce((col1, col2) -> col1.stream() | |
.flatMap(inner1 -> col2.stream() | |
.map(inner2 -> Stream.of(inner1, inner2) | |
.flatMap(Collection::stream) | |
.collect(Collectors.toCollection(ArrayList::new)))) | |
.collect(Collectors.toCollection(ArrayList::new))) | |
.map(v -> v.stream() | |
.map(col -> col.stream().map(String::valueOf).collect(Collectors.joining())) | |
.collect(Collectors.toList())) | |
.orElseGet(Collections::emptyList); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment