Skip to content

Instantly share code, notes, and snippets.

@yt8492
Created August 7, 2020 02:57
Show Gist options
  • Save yt8492/b036eee1fc9281c12b41724d79592d6d to your computer and use it in GitHub Desktop.
Save yt8492/b036eee1fc9281c12b41724d79592d6d to your computer and use it in GitHub Desktop.
sealed class HuffmanNode {
abstract val codeSize: Int
data class CodeInfo(val code: Char, override val codeSize: Int) : HuffmanNode()
data class TreeNode(val left: HuffmanNode, val right: HuffmanNode, override val codeSize: Int) : HuffmanNode()
}
fun main() {
val text = "HELLO"
val result = huffman(text)
println(result)
}
fun huffman(text: String): HuffmanNode {
val huffmanNodes = text.fold(mutableMapOf<Char, Int>()) { acc, c ->
val n = acc[c] ?: 0
acc[c] = n + 1
acc
}.asSequence()
.fold(PriorityQueue<HuffmanNode>(
Comparator { o1, o2 ->
o1.codeSize.compareTo(o2.codeSize)
})
) { acc, entry ->
acc.add(HuffmanNode.CodeInfo(entry.key, entry.value))
acc
}
return when (huffmanNodes.size) {
1 -> huffmanNodes.first()
else -> {
while (huffmanNodes.size != 1) {
val left = huffmanNodes.poll()
val right = huffmanNodes.poll()
val node = HuffmanNode.TreeNode(left, right, left.codeSize + right.codeSize)
huffmanNodes.add(node)
}
huffmanNodes.poll()
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment