我正在尝试为我的编码挑战之一计算给定分数的排名,但是我对收到的输出感到惊讶。
我必须为给定分数创建排行榜(假设分数按排序顺序位于array
中)。我创建了一种方法,可以给出给定分数的排名,
private static int[] assignCurrentRanks(int[] scores) {
int[] currentRanks=new int[scores.length];
currentRanks[0]=1;//by default the first score will be rank 1
for(int i=1;i<currentRanks.length;i++) {
currentRanks[i]=(scores[i]==scores[i-1])?currentRanks[i-1]:++currentRanks[i-1];
System.out.println("Inside the loop : ["+i+"] "+scores[i]+" "+currentRanks[i]);
}
return currentRanks;
}
示例输入:100,100,50,40,40,20,10
预期排名:1、1、2、3、3、4、5
我可以看到在循环期间已经正确分配了等级,当我在main方法中返回的数组不同之后打印等级时。
我知道逻辑上有问题,但是我找不到。请帮忙!
下面是我的main
方法,
public static void main(String[] args) {
int[] scores=new int[]{100,100,50,40,40,20,10};
int[] currentRanks=assignCurrentRanks(scores);
System.out.println("Printing after the loop");
for(int i=0;i<scores.length;i++)
System.out.println("["+i+"]"+scores[i]+" "+currentRanks[i]);
}
我得到的结果是
//index 0 is already assigned with 1 by default
Inside the loop : [1] 100 1
Inside the loop : [2] 50 2
Inside the loop : [3] 40 3
Inside the loop : [4] 40 3
Inside the loop : [5] 20 4
Inside the loop : [6] 10 5
Printing after the loop
[0]100 1
[1]100 2
[2]50 3
[3]40 3
[4]40 4
[5]20 5
[6]10 5
答案 0 :(得分:4)
++currentRanks[i-1];\\this increments the value of array element i-1
您增加了循环内使用的优先级,从而产生了意外的行为。应该将预期行为更改为:
currentRanks[i]=(scores[i]==scores[i-1])?currentRanks[i-1]:currentRanks[i-1] + 1;
答案 1 :(得分:1)
很可能++currentRanks[i-1]
正在改变结果。
尝试以下方法:
currentRanks[i]=(scores[i]==scores[i-1])?currentRanks[i-1]:currentRanks[i-1]+1;