題目描述:
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.
(編寫(xiě)一個(gè)靜態(tài)方法 histogram(), 接受一個(gè)整型數(shù)組 a[] 和一個(gè)整數(shù) M 為參數(shù)并返回一個(gè)大小為M的數(shù)組,其中第 i個(gè)元素的值為整數(shù)i在參數(shù)數(shù)組中出現(xiàn)的次數(shù)。如果 a[]中的值均在 0到M-1之間, 返回?cái)?shù)組中所有元素之和應(yīng)該和 a.length 相等。)
Kotlin 實(shí)現(xiàn)
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
}
運(yùn)行結(jié)果
