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.
Advertisement
Answer
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…