Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package com.company;
- import java.io.IOException;
- import java.util.*;
- import java.util.stream.Collectors;
- public class SolutionWordSequencePermutations {
- public static void main(String[] args) throws IOException {
- List<String> input = Arrays.asList("ojhg", "yuio", "qwerty", "bbb", "zalupa", "anus", "pidor", "soy");
- List<String> usableWords = findUsableWords(input);
- System.out.println("input: " + input);
- System.out.println("usableWords: " + usableWords);
- Set<List<String>> result = new HashSet<>();
- for (List<String> variant : PermutationsGenerator.generatePermutations(usableWords)) {
- int length = checkIfSequence(variant);
- if (length > 1) {
- System.out.println(variant.stream().limit(length).collect(Collectors.toList()));
- result.add(variant.stream().limit(length).collect(Collectors.toList()));
- }
- }
- System.out.println("============COMBINATIONS============");
- result.forEach(System.out::println);
- System.out.println("====================================");
- }
- static class PermutationsGenerator {
- private static List<List<String>> generatePermutations(List<String> input) {
- List<List<String>> result = new ArrayList<>();
- if (input.size() == 1) {
- result.add(input);
- } else {
- for (int i = 0; i < input.size(); i++) {
- for (List<String> tmpPart : generatePermutations(getListCopyExcept(input, i))) {
- List<String> tmp = new ArrayList<>();
- tmp.add(input.get(i));
- tmp.addAll(tmpPart);
- result.add(tmp);
- }
- }
- }
- return result;
- }
- private static List<String> getListCopyExcept(List<String> strings, int except) {
- List<String> result = new ArrayList<>();
- for (int i = 0; i < strings.size(); i++) {
- if (i != except) {
- result.add(strings.get(i));
- }
- }
- return result;
- }
- }
- private static List<String> findUsableWords(List<String> input) {
- Set<String> result = new HashSet<>();
- for (int i = 0; i < input.size(); i++) {
- String firstLetter = input.get(i).substring(0, 1);
- String lastLetter = input.get(i).substring(input.get(i).length() - 1);
- for (int j = 0; j < input.size(); j++) {
- if (i != j) {
- if (input.get(j).endsWith(firstLetter)) {
- result.add(input.get(i));
- break;
- } else if (input.get(j).startsWith(lastLetter)) {
- result.add(input.get(i));
- break;
- }
- }
- }
- }
- return new ArrayList<>(result);
- }
- private static int checkIfSequence(List<String> input) {
- String valueToCompareWith = null;
- int length = 0;
- for (String word : input) {
- if (valueToCompareWith != null) {
- if (valueToCompareWith.equals(word.substring(0, 1))) {
- length++;
- } else {
- return length;
- }
- }
- valueToCompareWith = word.substring(word.length() - 1);
- }
- return length;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement