From 4cf960b73b9c73f81ff1869eaecc403fa5b4d3b6 Mon Sep 17 00:00:00 2001 From: Matej Focko Date: Wed, 24 Jul 2024 13:28:21 +0200 Subject: [PATCH] =?UTF-8?q?java:=20add=20=C2=AB2191.=20Sort=20the=20Jumble?= =?UTF-8?q?d=20Numbers=C2=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Matej Focko --- java/sort-the-jumbled-numbers.java | 35 ++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 java/sort-the-jumbled-numbers.java 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; + } +}