Skip to content
Advertisement

How to sort numbers in an array into different arrays based off of their last two digits

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:

JavaScript

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…

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement