Initial data commit
This commit is contained in:
parent
72d218235f
commit
f23f22d71c
199087 changed files with 3378941 additions and 0 deletions
50
Task/Huffman-coding/Groovy/huffman-coding-1.groovy
Normal file
50
Task/Huffman-coding/Groovy/huffman-coding-1.groovy
Normal file
|
|
@ -0,0 +1,50 @@
|
|||
import groovy.transform.*
|
||||
|
||||
@Canonical
|
||||
@Sortable(includes = ['freq', 'letter'])
|
||||
class Node {
|
||||
String letter
|
||||
int freq
|
||||
Node left
|
||||
Node right
|
||||
boolean isLeaf() { left == null && right == null }
|
||||
}
|
||||
|
||||
Map correspondance(Node n, Map corresp = [:], String prefix = '') {
|
||||
if (n.isLeaf()) {
|
||||
corresp[n.letter] = prefix ?: '0'
|
||||
} else {
|
||||
correspondance(n.left, corresp, prefix + '0')
|
||||
correspondance(n.right, corresp, prefix + '1')
|
||||
}
|
||||
return corresp
|
||||
}
|
||||
|
||||
Map huffmanCode(String message) {
|
||||
def queue = message.toList().countBy { it } // char frequencies
|
||||
.collect { String letter, int freq -> // transformed into tree nodes
|
||||
new Node(letter, freq)
|
||||
} as TreeSet // put in a queue that maintains ordering
|
||||
|
||||
while(queue.size() > 1) {
|
||||
def (nodeLeft, nodeRight) = [queue.pollFirst(), queue.pollFirst()]
|
||||
|
||||
queue << new Node(
|
||||
freq: nodeLeft.freq + nodeRight.freq,
|
||||
letter: nodeLeft.letter + nodeRight.letter,
|
||||
left: nodeLeft, right: nodeRight
|
||||
)
|
||||
}
|
||||
|
||||
return correspondance(queue.pollFirst())
|
||||
}
|
||||
|
||||
String encode(CharSequence msg, Map codeTable) {
|
||||
msg.collect { codeTable[it] }.join()
|
||||
}
|
||||
|
||||
String decode(String codedMsg, Map codeTable, String decoded = '') {
|
||||
def pair = codeTable.find { k, v -> codedMsg.startsWith(v) }
|
||||
pair ? pair.key + decode(codedMsg.substring(pair.value.size()), codeTable)
|
||||
: decoded
|
||||
}
|
||||
10
Task/Huffman-coding/Groovy/huffman-coding-2.groovy
Normal file
10
Task/Huffman-coding/Groovy/huffman-coding-2.groovy
Normal file
|
|
@ -0,0 +1,10 @@
|
|||
def message = "this is an example for huffman encoding"
|
||||
|
||||
def codeTable = huffmanCode(message)
|
||||
codeTable.each { k, v -> println "$k: $v" }
|
||||
|
||||
def encoded = encode(message, codeTable)
|
||||
println encoded
|
||||
|
||||
def decoded = decode(encoded, codeTable)
|
||||
println decoded
|
||||
Loading…
Add table
Add a link
Reference in a new issue