Skip to content

Instantly share code, notes, and snippets.

@kubukoz
Last active May 22, 2016 21:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kubukoz/c81a713e767b24b6674c14f20741798a to your computer and use it in GitHub Desktop.
Save kubukoz/c81a713e767b24b6674c14f20741798a to your computer and use it in GitHub Desktop.
fun <T> List<T>.histogram(map: (T) -> Int, showAs: (Boolean, T) -> String): String {
val maxHeight = map { map(it) }.max() ?: 0
return (maxHeight downTo 0).map { i ->
this.map {
showAs(i <= map(it), it)
}.joinToString("")
}.joinToString("\n")
}
//Sample usage:
listOf(1, 2, 3, 4, 1, 2, 4).histogram({ it }, { it, e ->
if (it) "#" else " "
})
/* sample output
# #
## #
### ##
####### */
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment