Anagram in list of words

Cette semaine, c'est Nicolas qui vous propose un #KataOfTheWeek : Anagram

Briefing du Kata : Le but de ce kata est d'écrire une méthode prenant un String en entrée composée de mots séparés par des espaces, la sortie de cette méthode est un String contenant tous les couples présents dans l'entrée séparés par des retours à la ligne. Exemple : Input -> portal toto carlo nerve carol tata never coral patrolOutput ->

portal - patrol
carlo - carol
carlo - coral
carol - coral
nerve - never

Saurez-vous résoudre le problème ?

Bon courage !


Et voici une solution proposée par l'auteur en Java :

public class Main {
    private static final String STRING_FOR_TEST = "portal toto carlo nerve carol tata never coral patrol";

    public static void main(String[] args) {
        System.out.println(Anagrammes.findAllCouplesInText(STRING_FOR_TEST));
    }
}

class Anagrammes {
    static String findAllCouplesInText(String text) {
        String[] words = text.split(" ");
        HashMap<String, List<String>> map = new HashMap<>();
        for (String word : words) {
            String sortedLetters = orderLetters(word);
            if (!map.containsKey(sortedLetters)) {
                map.put(sortedLetters, new ArrayList<>());
            }
            map.get(sortedLetters).add(word);
        }
        return map.values().stream().map(Anagrammes::makeCouples).filter(Optional::isPresent).map(Optional::get).collect(Collectors.joining("\n"));
    }

    static Optional<String> makeCouples(List<String> list) {
        if (list == null || list.isEmpty() || list.size() < 2) {
            return Optional.empty();
        }
        List<String> tmpList = new ArrayList<>();
        for (int i = 0; i < list.size(); ++i) {
            String w1 = list.get(i);
            for (int j = i + 1; j < list.size(); ++j) {
                tmpList.add(w1 + " - " + list.get(j));
            }
        }
        return Optional.of(String.join("\n", tmpList));
    }

    static String orderLetters(String word) {
        char[] tempArray = word.toCharArray();
        Arrays.sort(tempArray);
        return new String(tempArray);
    }
}

Votre équipe TakiVeille

TakiVeille

TakiVeille