Search code examples
javaalgorithmsortinganagram

Finding Groups of Rearranged Strings from a txt With Strings on Seperate Lines


What I would like to do is take an input txt file of any length which looks like this

bob
joe
obb
oej

and produce an output txt file which sorts groups of re-arranged words on a single line and alphabetically in an output txt file.

bob obb
joe oej

Here is what I have attempted so far where args[0] is a file called input.txt passed in the command line.

   public static void main(String[] args) {
    File file = new File(args[0]):
    Scanner scan = new Scanner(file);
    List<char[]> anagrams = new ArrayList();

    while (scan.hasNextLine()) {
        Scanner scan2 = new Scanner(file);
        String line = scan.nextLine();
        char[] arr = line.toCharArray();

        if (containsAnagram(anagrams, line))
            continue;
        else anagrams.add(line);

        while (scan2.hasNextLine()) {
            String line2 = scan2.nextLine();
   
            if (isAnagram(arr, line2))
                fileContent2+=” ”+line2;
        }
        fileContent+=fileContent2+”\n”;
    }
}

private static boolean isAnagram(char[] arr, String line) {
    for (int i=0; i<arr.length; i++) {
        if (!Arrays.asList(line).contains(arr(i))
            break;
        if (i=arr.length-1)
            return true;
    }

Solution

  • Here is a compact way to achieve what you need using java.nio Files , Streams and a Function:

    import java.io.IOException;
    import java.nio.charset.Charset;
    import java.nio.file.Files;
    import java.nio.file.Paths;
    import java.util.List;
    import java.util.function.Function;
    import java.util.regex.Pattern;
    import java.util.stream.Collectors;
    
    public class NewClass {
    
        public static void main(String[] args) throws IOException {
             // (1)
            List<String> input = Files.readAllLines(Paths.get("path to your input file"));
            // (2)
            Function<String,String> func = s -> Pattern.compile("")                     
                                                        .splitAsStream(s)
                                                        .sorted()
                                                        .collect(Collectors.joining());
            // (3)
            List<String> output = input.stream()                                       
                                        .collect(Collectors.groupingBy(func))
                                        .values()
                                        .stream()                
                                        .map(list -> list.stream().sorted().collect(Collectors.joining(" ")))
                                        .sorted()
                                        .collect(Collectors.toList());
            // (4)
            Files.write(Paths.get("path to your output file"), output, Charset.forName("UTF-8"));
        }
    }
    
    1. Read all lines of input file into a list
    2. Define a function which accepts a string and returns a string with sorted chars of the input, e.g bob -> bbo
    3. group your input list by above function, stream over the values of the resulting map maping each list to a space delimited string to form a line of output text, collect all strings to an output list
    4. write to output file