Java – how to divide an ordered list of integers into sub lists of uniform size?
•
Java
Does anyone have a good algorithm to get an ordered list of integers, that is:
In a given number of ordered sublists of uniform size, that is, for 4, it will be: [1,6] [7,11] [13,19] [23,28]
The requirement is that each sub list is ordered and as similar in size as possible
Solution
Splitting the list evenly means that you will have a list of two sizes – s and S 1
Using the N sublist and the original x element, you will get:
(E / N) the number of elements in the smaller sublist (s) (x / N), and X% n is the number of larger sublist (S1)
Then iterate over the original array and (see your example) create a small list first
Such things may be:
private static List<Integer[]> splitOrderedDurationsIntoIntervals(Integer[] durations,int numberOfIntervals) { int sizeOfSmallSublists = durations.length / numberOfIntervals; int sizeOfLargeSublists = sizeOfSmallSublists + 1; int numberOfLargeSublists = durations.length % numberOfIntervals; int numberOfSmallSublists = numberOfIntervals - numberOfLargeSublists; List<Integer[]> sublists = new ArrayList(numberOfIntervals); int numberOfElementsHandled = 0; for (int i = 0; i < numberOfIntervals; i++) { int size = i < numberOfSmallSublists ? sizeOfSmallSublists : sizeOfLargeSublists; Integer[] sublist = new Integer[size]; System.arraycopy(durations,numberOfElementsHandled,sublist,size); sublists.add(sublist); numberOfElementsHandled += size; } return sublists; }
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码