bin*_*101 8 java integer batching
我想知道在处理时间方面批处理给定数字的最佳方法是什么.取物品:(第9, 18, 7, 8, 4, 9, 11, 15, 3, 8,
1项处理时间为9,第2项处理时间为18,等等)
如果批处理时间限制设置为20,则可能将项目分组为批次:( {1, 3, 5} {2} {4, 6} {8, 9} {7, 10}组1为9 + 7 + 4 = 20)等,因此已经制作了5批项目,其中内容为< = 20.
理想情况下,我希望它将它们分组为尽可能少的组.以上情况至少有5组,内容限制为20 ...
谢谢
如果批处理时间限制设置为20,...
所以我假设没有元素大于批处理时间限制。这是我的方法:
Java中的实现:
int[] input = { 9, 18, 7, 8, 4, 9, 11, 15, 3, 8 }; // Input items.
Arrays.sort(input); // Sort the items.
int left = 0, right = input.length - 1; // Left and right pointers.
int remainder = 0, limit = 20;
// list of groups.
ArrayList<ArrayList<Integer>> list = new ArrayList<ArrayList<Integer>>();
while (right >= left)
{
ArrayList<Integer> subList = new ArrayList<Integer>();
list.add(subList);
// Add the current maximum element.
subList.add(input[right]);
if (right == left)
break;
remainder = limit - input[right];
right--;
// Add small elements until limit is reached.
while (remainder > input[left]) {
subList.add(input[left]);
remainder = remainder - input[left];
left++;
}
remainder = 0; // Reset the remainder.
}
Run Code Online (Sandbox Code Playgroud)
打印组:
for (ArrayList<Integer> subList : list)
{
for (int i : subList)
System.out.print(i + " ");
System.out.println();
}
Run Code Online (Sandbox Code Playgroud)
输出:(每行代表一组数字)
18
15 3
11 4
9 7
9 8
8
Run Code Online (Sandbox Code Playgroud)