java 存在平局时输出选举赢家

eqoofvh9  于 2023-01-07  发布在  Java
关注(0)|答案(3)|浏览(107)

我已经编写了一个有效的投票系统,但是它需要更多的决策。如果两个或更多的候选人有相同的票数,这个程序就需要工作。
以下是我所拥有的,但我认为这是非常冗长的,它只会与2名候选人有相同的票数。有没有一个更有效的方法来做到这一点,而与2名或更多的候选人有相同的票数。
在此场景中只有5个候选人可用,但如果添加更多候选人,则应起作用。

public static void displayFinalResults(String[] stringArray, int[] numArray){
        if(numArray[0] == numArray[1]){
            System.out.println("\nIn third place: " + stringArray[3]);
            System.out.println("In second place: " + stringArray[2]);
            System.out.println("And the winner is: " + stringArray[0] + " and " + stringArray[1]);

        }else if(numArray[1] == numArray[2]){
            System.out.println("\nIn third place: " + stringArray[3]);
            System.out.println("In second place: " + stringArray[1] + " and " + stringArray[2]);
            System.out.println("And the winner is: " + stringArray[0]);
        }else if(numArray[2] == numArray[3]){
            System.out.println("\nIn third place: " + stringArray[2] + " and " + stringArray[3]);
            System.out.println("In second place: " + stringArray[1]);
            System.out.println("And the winner is: " + stringArray[0]);
        }else{
            System.out.println("\nIn third place: " + stringArray[2]);
            System.out.println("In second place: " + stringArray[1]);
            System.out.println("And the winner is: " + stringArray[0]);
        }

    }
t3irkdon

t3irkdon1#

我首先检查得分是多少,最高,第二高,第三高,然后选择具有这些值的名称

public static void displayFinalResults(String[] stringArray, int[] numArray){
    int highestScore = max(numArray, Integer.MAX_VALUE);
    int secondHighestScore = max(numArray, highestScore);
    int thirdHighestScore = max(numArray, secondHighestScore);

    System.out.println("\nIn third place: ");
    for (int i = 0; i < numArray.length; i++) {
        if (numArray[i] == thirdHighestScore) {
            System.out.println(stringArray[i]);
        }
    }

    System.out.println("In second place: ");
    for (int i = 0; i < numArray.length; i++) {
        if (numArray[i] == secondHighestScore) {
            System.out.println(stringArray[i]);
        }
    }

    System.out.println("And the winner: ");
    for (int i = 0; i < numArray.length; i++) {
        if (numArray[i] == highestScore) {
            System.out.println(stringArray[i]);
        }
    }

}

public static int max(int[] scores, int lessThan) {
    int max = Integer.MIN_VALUE;
    for (int score : scores) {
        if (score > max && score < lessThan) {
            max = score;
        }
    }

    return max;
}
mzmfm0qo

mzmfm0qo2#

这是我会采取的方法。我会创建一个结构来保存候选人的名字和选票数量,因为跟踪跨2个数组是复杂的,可能会混淆。我还建议使用不同的数据结构比数组作为方法输入,我在例子中转换为Candidate的输入流,其中有2个字段名称和numVotes:

record Candidate(String name, int numVotes) {
    }

    public static void displayFinalResults(String[] stringArray, int[] numArray) {
        //make sure that 2 arrays match in size
        assert numArray.length == stringArray.length;
        //zip arrays and convert to the stream of Candidate
        var candidates = IntStream.range(0, stringArray.length).mapToObj(i -> new Candidate(stringArray[i], numArray[i]));
        //group by number of votes
        var groupedByNumVotes = candidates.collect(Collectors.groupingBy(c -> c.numVotes));
        //sort by number of votes descending
        var sorded = groupedByNumVotes.entrySet().stream().sorted((e1, e2) -> Integer.compare(e2.getKey(), e1.getKey()));
        //take first 3 places
        var winners = sorded.limit(3).toList();

        //Loop through the list of winners with index and print it
        for (int i = 0; i < winners.size(); i++) {
            //List is indexed from 0 so the place number needs to be increased by one
            System.out.println("Place " + (i + 1));  
            winners.get(i).getValue().forEach(System.out::println);
            System.out.println();
        }
    }
2exbekwf

2exbekwf3#

坦率地说,你的方法没有什么根本性的错误(除了,按照惯例,如果第一名打成平手,第二名通常会被跳过;即:有两个并列的第一名候选人和一个第三名,但没有第二名)。您只需为三个并列的候选人再添加一个案例。
也就是说,可以通过合并输出格式中的冗余来稍微缩短代码:

public static void displayFinalResults(String[] names, int[] scores) {
    final String[] winners = new String[3];

    if (scores[0] == scores[1] && scores[1] == scores[2]) {
        winners[0] = String.format("%s, %s and %s", names[0], names[1], names[2]);
    } else if (scores[0] == scores[1]) {
        winners[0] = String.format("%s and %s", names[0], names[1]);
        winners[2] = names[2];
    } else if (scores[1] == scores[2]) {
        winners[0] = names[0];
        winners[1] = String.format("%s and %s", names[1], names[2]);
    } else {
        System.arraycopy(names, 0, winners, 0, 3);
    }

    System.out.println();
    if (winners[2] != null) System.out.printf("In third place: %s\n", winners[2]);
    if (winners[1] != null) System.out.printf("In second place: %s\n", winners[1]);
    final String prefix = winners[2] == null && winners[1] == null ? "T" : "And t";
    System.out.printf("%she winner is: %s\n", prefix, winners[0]);
}

相关问题