简体   繁体   中英

Sorting an array based on calculated values

For a recent java coding test I had a question similar to the following:

A function receives a string of comma separated values. Add the digits of each number contained to create a single value for that number. Order these in ascending order Return the original values (ie not the calculated ones) in this sorted order.

Hence if the string input is:

{"91,15,20"} The digits after adding would be: 10, 6, 2 since (9+1 == 10, 1+5 == 6, 2+0 == 2)

After sorting into ascending order: 2,6,10

We would thus return the original string sorted as above as as: 20,15,91

From a coding perspective this means we would split the string on the comma into a string array

For each item, convert the string to an int and then calculate its 'value'

Now, this is where I'm foxed!

At first I added the calculated item to an array list and then sorted it but realised that since I needed to return the original strings (not the calculated values), this was no good.

As such I'm looking for advise for future knowledge.

I don't actually specifically want code but more so advice on the approach.

Would using a map have been the best way? I contemplated that but can't see how that work, especially if there could be duplicate values in the string. Would it have been better to have two arrays? Is it best to sort as I parse the string array?

Although I've failed that question I want to still complete it so that I'll know.. I need to learn from failure after all.

Would be grateful for advice in the best approach please.

Here is some advice. I assume you are using Java 8.

Instead of putting your values in a data structure like a map or something, why not discarding them after the calculation, if you don't care about performance?

Since JDK 1.8, there is this sort method on ArrayList that accepts a comparator. A Comparator<Integer> has this method:

public int compare(Integer o1, Integer o2) {
    
}

If you just fill in this method with something like this...

public int compare(Integer o1, Integer o2) {
    Integer a = // add up the digits in o1
    Integer b = // add up the digits in o2
    return a.compareTo(b);
}

The sort will work! You can then prettify your code by turning this into a lambda:

list.sort(
        (o1, o2) -> {
                Integer a = <calculation>;
                Integer b = <calculation>;
                return a.compareTo(b);
        }
);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM