gpt4 book ai didi

Java数组相加算法

转载 作者:塔克拉玛干 更新时间:2023-11-03 06:19:37 24 4
gpt4 key购买 nike

目前我将这组数据放在一个排序数组中,从最低价格到最高价格。

Line 1 in the user container need Basic( Special : true) - Ship name: Titanic

The Price is: 10.0 Capacity: 300.0

Line 1 in the user container need Basic( Special : true) - Ship name: Ace

The Price is: 10.0 Capacity: 400.0

Line 1 in the user container need Basic( Special : true) - Ship name: Adda

The Price is: 5.0 Capacity: 130.0

Line 1 in the user container need Basic( Special : true) - Ship name: mutha

The Price is: 6.0 Capacity: 350.0

Line 1 in the user container need Basic( Special : true) - Ship name: spade

The Price is: 10.0 Capacity: 450.0

第一个排序数组的结果**[5.0,6.0,10.0,10.0,10.0]**每个数据都与船名配对。

我的目标(创建一个新的字符串数组):[Adda,mutha,spade,ace,Titanic]Adda 是 mutha 之后最便宜的。对于 spade、ace 和 titanic,它们按容量排序,因为它们具有相同的价格这是我的代码

Map<Ships, Double> sortedMap = sortByComparator(shipsarray);
LinkedHashSet<String> uniqueStrings = new LinkedHashSet<String>();
double tempprice=0,tempcap=0;
String tempship = null;

for (Map.Entry<Ships, Double> entry : sortedMap.entrySet()) {//loop for fill in
if((double)entry.getValue() == tempprice){
if(entry.getKey().getAvailableCapacityForType(user.getContainers().get(i).getClass())>tempcap){
System.out.println(uniqueStrings);
uniqueStrings.remove(tempship);
uniqueStrings.add(entry.getKey().getship().getShipName());
uniqueStrings.add(tempship);
System.out.println(uniqueStrings);
}
else{
System.out.println(uniqueStrings);
uniqueStrings.add(entry.getKey().getship().getShipName());
}
}
else{
uniqueStrings.add(entry.getKey().getship().getShipName());
tempprice = (double)entry.getValue();
tempship = entry.getKey().getship().getShipName();
tempcap = entry.getKey().getAvailableCapacityForType(user.getContainers().get(i).getClass());
}



}

目前结果是[Adda, mutha, spade, Titanic]缺少王牌。

感谢帮助

最佳答案

您可以尝试实现自定义比较器并将其与 Arrays.sort() 一起使用以获得所需的排序。像这样:

public class Main {

public static void main(String[] args) {

Ship a = new Ship("A", 5, 100);
Ship b = new Ship("B", 6, 400);
Ship c = new Ship("C", 6, 300);
Ship[] ships = {a,c,b};

System.out.println(Arrays.toString(ships));

Arrays.sort(ships, new Comparator<Ship>() {
@Override
public int compare(Ship o1, Ship o2) {
if (o1.price < o2.price) return -1;
if (o1.price > o2.price) return 1;
else return o1.capacity > o2.capacity ? -1 : 1;
}
});

System.out.println(Arrays.toString(ships));

}

public static class Ship {
public final String name;
public final int price;
public final int capacity;
public Ship(String name, int price, int capacity) {
this.name = name;
this.price = price;
this.capacity = capacity;
}
@Override
public String toString() {
return String.format("(%s | price=%d, capacity=%d)", name, price, capacity);
}
}

}

关于Java数组相加算法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35527513/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com