如何比较对象数组中对象的值?

时间:2019-08-26 05:01:36

标签: java

我的代码输出以下内容:

s = ["21", "36"]

#if values of Salary are strings
#df = pd.read_csv(file, thousands=',')
#or
#df['Salary'] = df['Salary'].str.replace(',','').astype(int)

#ID are converted to strings by `astype`, because valus in list s are strings
df.loc[df['ID'].astype(str).isin(s), 'Salary'] *= 2.5
#if s are numeric
#df.loc[df['ID'].isin(s), 'Salary'] *= 2.5
print (df)
    Name  ID   Salary
0  James  21  62500.0
1    Sam  12  15000.0

我想创建一个方法“ displayWinners()”,该方法比较此数组中所有对象的投注值,并返回所有具有最高投注值的对象ID,在这种情况下,它将是计算机2和5,下注8。我该怎么做?

Computer 1 bets 5
Computer 2 bets 8
Computer 3 bets 4
Computer 4 bets 3
Computer 5 bets 8

4 个答案:

答案 0 :(得分:1)

为什么不为最大值的索引和值本身分配变量,并在执行函数bet()时不断检查并重写该变量。

下面的代码未正确验证,请仔细检查。

public class Computer {
Computer[] c;
private int id;
private int bet;
private List<Integer> maxId;
private int maxBet;

public void create(int numComps) {
    int i;
    c = new Computer[numComps];
    maxId = new ArrayList<Integer>();
    maxBet = 0;

    for (i = 0; i < numComps; i++) {

        c[i] = new Computer();
        c[i].id = i+1;
        c[i].bet = bet();
        c[i].display();

        if(c[i].bet > maxBet) {
            maxId = new ArrayList<Integer>();
            maxId.add(c[i].id);
            maxBet = c[i].bet;
        }
        else if(c[i].bet == maxBet) {
            maxId.add(c[i].id);
        }
    }
    displayWinners();
}

public int bet() {
    return (int) (Math.random() * 10) + 1;
}

public void display() {
    String name = "Computer " + id;
    System.out.println(name + " bets " + bet);
}

public void displayWinners() {
    System.out.format("Computer %d", maxId.get(0));
    if(maxId.size() > 1) {
        for(int i=1; i<maxId.size(); i++) {
            System.out.format(" and %d", maxId.get(i));
        }
    }
    System.out.format(" with a bet of %d\n", maxBet);
}

public static void main(String[] args) {
    Computer c = new Computer();
    c.create(5);
}

}

答案 1 :(得分:0)

好吧,很有趣,为此提供了一个小技巧。

您只需迭代数组即可。 然后,我将当前下注与使用Integer.compare已知的最大值进行比较,并根据结果进行以下选择:

  • r > 0-清除列表并将实例添加到列表
  • r == 0-将实例添加到列表中
  • r < 0-不执行任何操作

很高兴知道,该方法返回的实际值更简单[-1, 0, 1],很快就可以了。

现在,我们可以看到在列表中添加了一些冗余,为减少这一点,我们可以使用switch而不是if s。

List<Computer> winners = new ArrayList<Computer>();
for ( Computer c : computers ){
    int r = Integer.compare(c.getBet(), maxBet);
    switch(r){
        case 1: //Current bet is higher
            maxIds.clear();
            maxBet = c.getBet();
        case 0: //Current bet is equals
            winners.add(c);
        case -1: //Current bet is lower (optional line, just for the explanation)
    }
}

由于我不使用break,因此清除list之后,我们将其添加到其中。

注意:如果Integer.compare实现更改,则应添加故障保护。文档指出它将返回任何值,而不是-1、0或1。但是当前的实现更为简单:

public static int compare(int x, int y) {
    return (x < y) ? -1 : ((x == y) ? 0 : 1);
}

答案 2 :(得分:0)

首先,我建议您拆分存储和业务逻辑。将显示Computer类的所有方法移出。

要找到获奖者,您必须执行以下步骤:

  1. 创建计算机列表(可以创建阵列或列表);
  2. 对集合进行一次迭代以找到最高的赌注;
  3. 第二次遍历集合,以过滤掉所有具有最高赌注的计算机。

如果您问这样的问题,那么我想,您现在不需要提供不同的排序算法或特殊的数据结构(它们都可以执行相同的操作,但是对于大的输入数据要快得多)。

这是可能的解决方案之一(我试图保持简单):

public class Foo {

    public static void main(String[] args) throws IOException {
        Computer[] computers = createComputer(5);
        int highestBet = getHighestBet(computers);
        List<Integer> ids = getIdsWithBet(computers, highestBet);
        System.out.println(ids.stream().map(String::valueOf).collect(Collectors.joining(",")));
    }

    private static int getHighestBet(Computer... computers) {
        int max = 0;

        for (Computer computer : computers)
            max = Math.max(max, computer.getBet());

        return max;
    }

    private static List<Integer> getIdsWithBet(Computer[] computers, int bet) {
        List<Integer> ids = new ArrayList<>(computers.length);

        for (Computer computer : computers)
            if (computer.getBet() == bet)
                ids.add(computer.getId());

        return ids;
    }

    // you van use List<Computer>
    private static Computer[] createComputer(int total) {
        Random random = new Random();
        Computer[] computers = new Computer[total];

        for (int i = 0; i < computers.length; i++) {
            computers[i] = new Computer(i + 1, random.nextInt(10) + 1);
            System.out.println(computers[i]);
        }

        return computers;
    }
}

// It's better to use unmodifiable objects if you can
final class Computer {

    private final int id;
    private final int bet;

    public Computer(int id, int bet) {
        this.id = id;
        this.bet = bet;
    }

    public int getId() {
        return id;
    }

    public int getBet() {
        return bet;
    }

    @Override
    public String toString() {
        return "Computer " + id + " bets " + bet;
    }

}

答案 3 :(得分:-1)

import java.util.ArrayList at top of file

```
int maxBet = 0;
ArrayList<Integer> maxIds = new ArrayList<Integer>();
// This is a for each loop, it is saying, for each computer in the list of computers
for ( Computer computer : computers ){
    /* if that computer has a higher bet than what we previously thought 
     was the highest, empty our list and set maxBet to that, and add this 
     computer to the list of  computers that have that bet number */
    if (computer.getBet() > maxBet){
       maxIds.clear();
       maxBet = computer.getBet();
       maxIds.add(computer.getId());
    // another computer has the same max bet value
    } else if ( computer.getBet() == maxBet){
       maxIds.add(computer.getId());
    }
}
System.out.println("Max Bet: " + maxBet);
System.out.print("Computers with max bet: ");
// for each id in our list of computers that have the max bet 
for ( int id : maxIds ){
    System.out.print(id + " ");
}