I'm leaning Kotlin, and I'm wondering if there is a better, simpler and not that complicated way to do this in Kotlin? I need to Write a Kotlin program that loops through an array and generates a histogram based on the numbers in it.The results should look like this(vertically):
1: *****
2: **
3: **
4:
5: *
And this is what I did:
fun main() {
val myArray: IntArray = intArrayOf(1,2,1,3,3,1,2,1,5,1)
for(num in 1..5){
println("")
print("$num: ")
for(element in myArray) {
if(element == num){
print("*")
}
}
}
}
CodePudding user response:
You can use the eachCount
function to find the count of items in a list.
This is what I came up with:
fun main() {
val map = listOf(1,2,1,3,3,1,2,1,5,1)
.groupingBy{ it }
.eachCount()
(1..map.keys.max()).forEach {
print("\n${it}:")
map[it]?.let { count -> repeat(count){ print("*") } }
}
}
You can see the code here: https://pl.kotl.in/91d7pWDGe
Kotlin Koans is a good place you can learn by writing code. Here is the Koans for Collections: https://play.kotlinlang.org/koans/Collections/Introduction/Task.kt
CodePudding user response:
Not sure if it will be simpler, but you can do something like this:
fun main() {
val myArray: IntArray = intArrayOf(1, 2, 1, 3, 3, 1, 2, 1, 5, 1)
for (num in 1..5) {
println("")
val count = myArray.count { it == num }
val entries = if (count > 0) "*".repeat(count) else ""
print("$num: $entries")
}
}