Untitled

mail@pastecode.io avatar
unknown
plain_text
8 days ago
1.8 kB
7
Indexable
Never
import java.util.*;

class Result {
    public static List<Integer> sortBinaryNumbers(List<List<Integer>> bitArrays) {
        // Store the decimal values and corresponding indices in an array of int[]
        int n = bitArrays.size();
        int[][] decimalWithIndex = new int[n][2]; // [decimal_value, original_index]

        // Convert each list of bits to its decimal equivalent
        for (int i = 0; i < n; i++) {
            int decimalValue = 0;
            for (int bit : bitArrays.get(i)) {
                decimalValue |= (1 << bit); // Same as decimalValue += (1 << bit);
            }
            decimalWithIndex[i][0] = decimalValue;
            decimalWithIndex[i][1] = i; // Store the original index
        }

        // Sort based on decimal values in descending order
        Arrays.sort(decimalWithIndex, (a, b) -> Integer.compare(b[0], a[0]));

        // Prepare the result list
        List<Integer> result = new ArrayList<>();
        for (int[] pair : decimalWithIndex) {
            result.add(pair[1]); // Add the original index of sorted elements
        }

        return result;
    }
}

public class Solution {
    public static void main(String[] args) {
        // Example input
        List<List<Integer>> bitArrays = Arrays.asList(
            Arrays.asList(0, 2),   // Binary: 101 -> Decimal: 5
            Arrays.asList(2, 3),   // Binary: 1100 -> Decimal: 12
            Arrays.asList(1, 2)    // Binary: 110 -> Decimal: 6
        );

        // Get the sorted indices
        List<Integer> sortedIndices = Result.sortBinaryNumbers(bitArrays);

        // Output the sorted indices
        System.out.println(sortedIndices); // Expected output: [1, 2, 0]
    }
}
Leave a Comment