diff --git a/java/sort-the-jumbled-numbers.java b/java/sort-the-jumbled-numbers.java new file mode 100644 index 0000000..1bb4fd7 --- /dev/null +++ b/java/sort-the-jumbled-numbers.java @@ -0,0 +1,35 @@ +class Solution { + private class Jumble { + public int original; + public int mapped; + + public Jumble(int[] mapping, int original) { + this.original = original; + map(mapping, original); + } + + private void map(int[] mapping, int original) { + mapped = mapping[original % 10]; + original /= 10; + + for (int power = 10; original > 0; power *= 10, original /= 10) { + mapped += power * mapping[original % 10]; + } + } + } + + public int[] sortJumbled(int[] mapping, int[] nums) { + var jumbled = new Jumble[nums.length]; + for (int i = 0; i < nums.length; ++i) { + jumbled[i] = new Jumble(mapping, nums[i]); + } + + Arrays.sort(jumbled, Comparator.comparing(k -> ((Jumble) k).mapped)); + + for (int i = 0; i < nums.length; ++i) { + nums[i] = jumbled[i].original; + } + + return nums; + } +}