Home > Back-end >  How to sort numbers in an array into different arrays based off of their last two digits
How to sort numbers in an array into different arrays based off of their last two digits

Time:10-14

Trying to write a program that takes a set of doubles and then sorts these values into different arrays based on their tenths and hundredths places after the decimal. So for an array [1.25, 2.25, 3.5, 10.5, 7.75, 4.75] sort the .25's .5's .75's into separate arrays so that calculations may be done.

CodePudding user response:

You use the term 'sort' but I think you are really talking about grouping the values into collections based on their first 2 decimal values. If that's correct then you can use:

values.stream().collect(Collectors.groupingBy(v -> (int)(v % 1 * 100));

This will generate a map from each fraction (expressed as a /100 int) to a list of values that have that fraction. If you particularly need arrays you can use .toArray().

CodePudding user response:

My solution is a little grouping algorithm:

public static List<List<Float>> getSortedArrays(float[] array){
    List<List<Float>> result = new ArrayList<>();
    HashMap<Float, Integer> createdArrays= new HashMap<>();
    for (float f : array) {
        float ending = f-((int)f);
        if(createdArrays.containsKey(ending)){
            result.get(createdArrays.get(ending)).add(f);
        }else{
            createdArrays.put(ending, result.size());
            List<Float> newList = new ArrayList<>();
            newList.add(f);
            result.add(newList);
        }
    }
    return result;
}

I am basically looping through the float array and with this trick float ending = f-((int)f); I am separating just the numbers after the decimal. Than I am checking if there is already created array for that ending, if yes I add currently processed float, if not I create it and also add that float there. HashMap is there to keep track of already created Arrays.

Again use .toArray() if you need array...

  • Related