题目
你班上有一个考试,你通过了。恭喜你!
但你是一个雄心勃勃的人。你想知道你是否比你班上的普通学生更好。
你获得一个你同学分数的数组来计算平均分!
如果你还好返回True
,否则返回False
吧!
注意:
您的积分不包含在班级分数组中。要计算平均分,您可以将您的分数添加到给定数组!
测试用例:
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import org.junit.runners.JUnit4;
public class KataExampleTests {
@Test
public void tests() {
assertEquals(true, Kata.betterThanAverage(new int[] {2, 3}, 5));
assertEquals(true, Kata.betterThanAverage(new int[] {100, 40, 34, 57, 29, 72, 57, 88}, 75));
assertEquals(true, Kata.betterThanAverage(new int[] {12, 23, 34, 45, 56, 67, 78, 89, 90}, 69));
assertEquals(false, Kata.betterThanAverage(new int[] {100, 90}, 11));
}
}
解题
My
public class Kata {
public static boolean betterThanAverage(int[] classPoints, int yourPoints) {
int sum = 0;
for (int i = 0; i < classPoints.length ;i++) {
sum += classPoints[i];
}
sum += yourPoints;
return sum/(classPoints.length+1)<yourPoints;
}
}
Other
import java.util.Arrays;
class Kata {
static boolean betterThanAverage(final int[] classPoints, final int yourPoints) {
return Arrays.stream(classPoints).average().orElse(0) < yourPoints;
}
}
import java.util.stream.*;
public class Kata {
public static boolean betterThanAverage(int[] classPoints, int yourPoints) {
return IntStream.of(classPoints).sum()/classPoints.length < yourPoints;
}
}
后记
还是我的笨方法看着自然些。