首页 > 解决方案 > 我想不出这个盒子阵列挑战

问题描述

任务描述:给你一个以逗号分隔的字符串的无序列表,其值的顺序对应于以下内容: 0:唯一标识符 1:框左上角的 x 坐标 2:框左上角的 y 坐标一个盒子 3:盒子的高度 4:盒子的宽度

创建一个函数,该函数将返回有效逗号分隔字符串的排序列表。先按y坐标排序,如果y坐标相等,再按x坐标排序。完成NavigationSort下面的''功能。该函数应返回一个STRING_ARRAY. 该函数接受 STRING_ARRAY boxArray 作为参数。

public static List<String> NavigationSort(List<String> boxArray) {

        // write your code here

        return NavigationSort;

    }
}

`

public class Solution {
    public static void main(String[] args) throws IOException {
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
        BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH")));

        int boxArrayCount = Integer.parseInt(bufferedReader.readLine().trim());

        List<String> boxArray = IntStream.range(0, boxArrayCount).mapToObj(i -> {
            try {
                return bufferedReader.readLine();
            } catch (IOException ex) {
                throw new RuntimeException(ex);
            }
        }).collect(toList());

        List<String> result = Result.NavigationSort(boxArray);

        bufferedWriter.write(result.stream().collect(joining("\n")) + "\n");

        bufferedReader.close();
        bufferedWriter.close();
    }
}

标签: javachallenge-response

解决方案


你只需要写一个合适的Comparator.
这只是navigationSort方法的实现。目前尚不清楚如何获取源列表,但如果您需要从文件中读取它,那么只需使用class 中的方法readAllLInesjava.nio.file.Files即可。另请注意,以下代码假定方法参数 ieboxArray包含根据问题描述的有效数据。

import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

public class Solution {
    public static List<String> navigationSort(List<String> boxArray) {
        Comparator<String> c = (s1, s2) -> {
            String[] s1parts = s1.split(",");
            String[] s2parts = s2.split(",");
            int y1 = Integer.parseInt(s1parts[2]);
            int y2 = Integer.parseInt(s2parts[2]);
            int diff = y1 - y2;
            if (diff == 0) {
                int x1 = Integer.parseInt(s1parts[1]);
                int x2 = Integer.parseInt(s2parts[1]);
                diff = x1 - x2;
            }
            return diff;
        };
        return boxArray.stream()
                       .sorted(c)
                       .collect(Collectors.toList());
    }
}

推荐阅读