I cant figure this box array challenge

179 Views Asked by At

Task Description: you are given an unordered list of comma-separated strings with the order of values corresponding to the following: 0: unique identifier 1: x coordinates of the top left corner of a box 2: y coordinates of the top left corner of a box 3: height of a box 4: width of a box

Create a function that will return a sorted list of valid comma separated strings. sort first by the y coordinate, if y coordinates are equal, then sort by x coordinate. Complete the 'NavigationSort' function below. The function is expected to return a STRING_ARRAY. The function accepts STRING_ARRAY boxArray as parameter.

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();
    }
}
1

There are 1 best solutions below

0
On

You just need to write an appropriate Comparator.
This is just the implementation of the navigationSort method. It's not clear how to obtain the source list but if you need to read it from a file, then simply use method readAllLInes in class java.nio.file.Files. Also note that the below code assumes that the method parameter, i.e. boxArray, contains valid data according to the problem description.

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());
    }
}