package com.dky.calculate; import com.dky.utils.entity.DevSpec; import com.dky.utils.entity.DevPrice; import com.dky.utils.result.MatchedDevice; import com.dky.utils.result.MatchedDeviceResult; import java.util.*; public class RequireDevice { public static MatchedDeviceResult matchDevices(double demandCapacity,List deviceList,List priceList) { // 对设备按照容量从大到小排序 deviceList.sort((d1, d2) -> Double.compare(d2.getCapacity(), d1.getCapacity())); double remainingCapacity = demandCapacity; double totalPrice = 0; List matchedDevices = new ArrayList<>(); // 遍历设备列表.根据需求容量匹配设备 for (DevSpec spec : deviceList) { if (spec.getCapacity() <= remainingCapacity) { int count = (int) Math.floor(remainingCapacity / spec.getCapacity()); remainingCapacity = remainingCapacity - (spec.getCapacity() * count); matchedDevices.add(new MatchedDevice(spec, count)); if (count > 0) { DevPrice price = priceList.stream() .filter(p -> p.getId().equals(spec.getId())) .findFirst() .orElse(null); if (price != null) { double devicePrice = price.getDevPrice() * count; totalPrice += devicePrice; } } }else { for (int i = deviceList.size()-1; i >= 0; i--){ if (deviceList.get(i).getCapacity() >= remainingCapacity){ matchedDevices.add(new MatchedDevice(deviceList.get(i), 1)); int finalI = i; DevPrice price = priceList.stream() .filter(p -> p.getId().equals(deviceList.get(finalI).getId())) .findFirst() .orElse(null); if (price != null) { double devicePrice = price.getDevPrice(); totalPrice += devicePrice; } break; } } break; } if (remainingCapacity <= 0) { break; // 当总容量已经满足需求时,跳出循环,不再选择其他设备 } } return new MatchedDeviceResult(matchedDevices, Math.round(totalPrice*100.0)/100.0); } }