Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- @kotlinx.serialization.Serializable
- open class Node(val frequency: Int, var code: String = "", val left: Node, val right: Node): Comparable<Node>{
- override fun compareTo(other: Node): Int {
- return Integer.compare(frequency, other.frequency)
- }
- open fun createCode(code_: String){
- code = code_
- }
- }
- @kotlinx.serialization.Serializable
- class NodeTwoLeaf(val l: Node, val r: Node): Node(l.frequency+r.frequency, "", l, r){
- override fun createCode(code_: String) {
- super.createCode(code_)
- left.createCode(code + "0")
- right.createCode(code + "1")
- }
- }
- class Leaf(val symb: Char, count: Int): Node(count){
- override fun createCode(code_: String) {
- super.createCode(code_)
- }
- }
- import java.util.*
- class Haff(strings: List<String>){
- val countChars = hashMapOf<Char, Int>()
- val priorityQuenue: PriorityQueue<Node> = PriorityQueue()
- val codes = hashMapOf<Char, Node>()
- init {
- for(line in strings)
- createCountChars(line)
- leafAndQuenue()
- createTreeCodes()
- }
- fun createCountChars(text: String){
- for(char in text){
- if (countChars[char] != null)
- countChars.set(char, countChars[char]!!.inc())
- else {
- countChars.set(char, 1)
- }
- }
- }
- fun leafAndQuenue(){
- for(el in countChars){
- val leaf = Leaf(el.key, el.value)
- codes.set(el.key, leaf)
- priorityQuenue.add(leaf)
- }
- }
- fun createTreeCodes(){
- while(priorityQuenue.size > 1){
- val first: Node = priorityQuenue.poll()
- val second: Node = priorityQuenue.poll()
- val node = NodeTwoLeaf(first, second)
- priorityQuenue.add(node)
- }
- val root: Node = priorityQuenue.poll()
- if(countChars.size == 1){
- root.code = "0"
- } else {
- root.createCode("")
- }
- }
- val jsonData = Json.stringify(Leaf.serializer(), a.root)
Add Comment
Please, Sign In to add comment