首页 > 解决方案 > 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;
    }

标签: javaalgorithmsortinganagram

解决方案


这是使用 java.nio 文件、流和函数实现所需功能的紧凑方法:

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. 将输入文件的所有行读入列表
  2. 定义一个函数,它接受一个字符串并返回一个带有输入的排序字符的字符串,例如 bob -> bbo
  3. 按上述函数对输入列表进行分组,将结果映射的值流式传输,将每个列表映射到空格分隔的字符串以形成一行输出文本,将所有字符串收集到输出列表
  4. 写入输出文件

推荐阅读