题目描述:
1.1.15 Write a static method histogram() that takes an array a[] of int values and an integer M as arguments and returns an array of length M whose ith entry is the number of times the integer i appeared in the argument array. If the values in a[] are all between 0 and M–1, the sum of the values in the returned array should be equal to a.length.
(编写一个静态方法 histogram(), 接受一个整型数组 a[] 和一个整数 M 为参数并返回一个大小为M的数组,其中第 i个元素的值为整数i在参数数组中出现的次数。如果 a[]中的值均在 0到M-1之间, 返回数组中所有元素之和应该和 a.length 相等。)
Kotlin 实现
fun main(args: Array<String>) {
val a = intArrayOf(3, 5, 1, 8, 0, 3, 1, 5, 6, 2, 6, 8, 2, 2, 4, 6)
val M = 9
println(histogram(a,M).toList() )
//求和
val sum = histogram(a, M).reduce { acc, i -> acc + i }
println(a.size == sum)
}
fun histogram(a: IntArray, M: Int): IntArray {
val array = IntArray(M) { 0 }
a.forEach {
(0 until M)
.filter { i -> it == i }
.forEach { array[it] += 1 }
}
return array
}
网友评论