ANAGRAMS URL UTP

PHOTO EMBED

Wed Dec 06 2023 08:54:26 GMT+0000 (Coordinated Universal Time)

Saved by @KutasKozla #java

import java.net.*;
import java.io.*;
import java.util.*;
import java.util.stream.Collectors;

public class Main {

    public static void main(String[] args) {
        try {
            // Step 1: Open a connection to the URL and create a BufferedReader to read from it
            URL url = new URL("http://wiki.puzzlers.org/pub/wordlists/unixdict.txt");
            BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream()));

            // Step 2: Group words by sorted characters (anagrams)
            Map<String, List<String>> anagrams = reader.lines()
                    .collect(Collectors.groupingBy(Main::sortedString));

            // Step 3: Find the maximum number of anagrams in a single group
            int maxAnagrams = anagrams.values().stream()
                    .mapToInt(List::size)
                    .max()
                    .orElse(0);
          
			// Step 4: Print the group(s) with the maximum number of anagrams, sorted lexicographically

		// Stream through the values of the 'anagrams' map, which represent groups of anagrams
anagrams.values().stream()
        // Filter to include only groups with the maximum number of anagrams
        .filter(group -> group.size() == maxAnagrams)
        
        // For each qualifying group, sort its elements lexicographically
        .peek(Collections::sort)
        
        // Sort the groups based on the lexicographically first element of each group
        .sorted(Comparator.comparing(list -> list.get(0)))
        
        // For each sorted group, print it as a space-separated string
        .forEach(group -> System.out.println(String.join(" ", group)));
          
          
                // Step 5: Close the BufferedReader
            reader.close();
        } catch (IOException e) {
            // Handle IOException if it occurs
            e.printStackTrace();
        }
    }

private static String sortedString(String word) {
    // Step 1: Convert the word to a character array
    char[] letters = word.toCharArray();
    
    // Step 2: Sort the characters in lexicographic order
    Arrays.sort(letters);
    
    // Step 3: Create a new string from the sorted character array
    return new String(letters);
}
content_copyCOPY