SHOW:
|
|
- or go back to the newest paste.
| 1 | // Author : Saurav Kalsoor | |
| 2 | - | // Sort By Digit Sum - JAVA |
| 2 | + | // Sort By Indices - JAVA |
| 3 | ||
| 4 | import java.util.*; | |
| 5 | ||
| 6 | public class Test {
| |
| 7 | ||
| 8 | static Scanner sc = new Scanner(System.in); | |
| 9 | public static void main(String[] args) {
| |
| 10 | int n = sc.nextInt(); | |
| 11 | int m = sc.nextInt(); | |
| 12 | ArrayList<Integer> arr = new ArrayList<>(); | |
| 13 | ArrayList<Integer> indices = new ArrayList<>(); | |
| 14 | ||
| 15 | for(int i=0; i < n; i++) {
| |
| 16 | int input = sc.nextInt(); | |
| 17 | arr.add(input); | |
| 18 | - | ArrayList<Integer> result = sortByDigits(arr); |
| 18 | + | |
| 19 | ||
| 20 | for(int i=0; i < m; i++) {
| |
| 21 | int input = sc.nextInt(); | |
| 22 | indices.add(input); | |
| 23 | } | |
| 24 | ||
| 25 | ArrayList<Integer> result = sortByIndices(arr, indices, n, m); | |
| 26 | - | public static ArrayList<Integer> sortByDigits(ArrayList<Integer> arr){
|
| 26 | + | |
| 27 | - | Collections.sort(arr, new SortBySumOfDigits()); |
| 27 | + | |
| 28 | - | return arr; |
| 28 | + | |
| 29 | ||
| 30 | System.out.println(); | |
| 31 | } | |
| 32 | - | class SortBySumOfDigits implements Comparator<Integer> {
|
| 32 | + | |
| 33 | - | |
| 33 | + | public static ArrayList<Integer> sortByIndices(ArrayList<Integer> arr, ArrayList<Integer> indices, int n, int m){
|
| 34 | - | public int compare(Integer a, Integer b){
|
| 34 | + | ArrayList<Integer> sortDesc = new ArrayList<Integer>(); |
| 35 | ArrayList<Integer> sortAsc = new ArrayList<Integer>(); | |
| 36 | - | int sumA = getSum(a), sumB = getSum(b); |
| 36 | + | |
| 37 | - | if(sumA == sumB){
|
| 37 | + | HashSet<Integer> indicesSet = new HashSet<Integer>(); |
| 38 | - | return a - b; |
| 38 | + | |
| 39 | for(int i=0; i < m; i++){
| |
| 40 | - | else{
|
| 40 | + | indicesSet.add(indices.get(i)); |
| 41 | - | return sumA - sumB; |
| 41 | + | |
| 42 | ||
| 43 | for(int i=0; i < n; i++){
| |
| 44 | if(indicesSet.contains(i)){
| |
| 45 | - | public int getSum(int n){
|
| 45 | + | sortDesc.add(arr.get(i)); |
| 46 | - | int sum = 0; |
| 46 | + | }else{
|
| 47 | - | while(n > 0){
|
| 47 | + | sortAsc.add(arr.get(i)); |
| 48 | - | sum = sum + n%10; |
| 48 | + | } |
| 49 | - | n = n/10; |
| 49 | + | |
| 50 | ||
| 51 | - | return sum; |
| 51 | + | Collections.sort(sortDesc, Collections.reverseOrder()); |
| 52 | Collections.sort(sortAsc); | |
| 53 | ||
| 54 | ArrayList<Integer> result = new ArrayList<Integer>(); | |
| 55 | ||
| 56 | int j = 0, k = 0; | |
| 57 | for(int i=0; i < n; i++){
| |
| 58 | if(indicesSet.contains(i)){
| |
| 59 | result.add(sortDesc.get(j)); | |
| 60 | j++; | |
| 61 | }else{
| |
| 62 | result.add(sortAsc.get(k)); | |
| 63 | k++; | |
| 64 | } | |
| 65 | } | |
| 66 | ||
| 67 | return result; | |
| 68 | } | |
| 69 | } | |
| 70 |