- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
对于过去几天我一直在研究的以下代码有两个问题。如果存在多个关系(意味着相同数量的频率),我该如何实现以下规则,使单个字母组优先于多个字母,然后按字母顺序排列?我的第二个问题是,有人可以指出我的编码/解码代码的编写方向吗?我应该通过我的主要声明来实现它还是继续完全编写一个新类?我有点不知道从哪里开始。
import java.util.*;
//The following is code that is hardcoded with two separate arrays consisting of
//characters and their corresponding frequency. The application takes in these two
//arrays and constructs a Huffman Encoding Tree. It begins by showing the user the
//letters, frequency, and the Huffman Code that will be assigned to that letter.
//The application then takes in a .txt file with various strings and encodes them.
//This result is also shown. [still working on this part-- question above]
abstract class HuffmanTree implements Comparable<HuffmanTree> {
public final int frequency; // the frequency of this tree
public HuffmanTree(int freq) { frequency = freq; }
// compares on the frequency
public int compareTo(HuffmanTree tree) {
return frequency - tree.frequency;
}
}
class HuffmanLeaf extends HuffmanTree {
public final char value; // the character this leaf represents
public HuffmanLeaf(int freq, char val) {
super(freq);
value = val;
}
}
class HuffmanNode extends HuffmanTree {
public final HuffmanTree left, right; // subtrees
public HuffmanNode(HuffmanTree l, HuffmanTree r) {
super(l.frequency + r.frequency);
left = l;
right = r;
}
}
public class Huffman {
public static void main(String[] args) {
//Symbols that are given to us to hard code
String letters = "abcdefghijklmnopqrstuvwxyz";
//converting string to character array
char[] letterArray = letters.toCharArray();
//Frequency of the letters given to us above:
int[] letterFreqs = {19, 16, 17, 11, 42, 12, 14, 17, 16, 5, 10, 20, 19, 24, 18, 13,
1, 25, 35, 25, 15, 5, 21, 2, 8, 3};
// build tree
HuffmanTree tree = constructTree(letterFreqs,letterArray);
// print out results
System.out.println("Letter\tFrequency\tEncoding");
printCodes(tree, new StringBuffer());
}
// input is an array of frequencies and a string of letters
public static HuffmanTree constructTree(int[] charFreqs, char[] letters) {
//sets up the priority queue to begin constructing the tree
PriorityQueue<HuffmanTree> trees = new PriorityQueue<HuffmanTree>();
//for loop to take in the characters and there frequencies
for (int i = 0; i < charFreqs.length; i++)
if (charFreqs[i] > 0)
trees.offer(new HuffmanLeaf(charFreqs[i], letters[i]));
assert trees.size() > 0;
// loop until there is only one tree left
while (trees.size() > 1) {
// find the two lowest frequencies
HuffmanTree a = trees.poll();
HuffmanTree b = trees.poll();
// construct a new node and re-insert into queue
trees.offer(new HuffmanNode(a, b));
}
return trees.poll();
}
public static void printCodes(HuffmanTree tree, StringBuffer prefix) {
assert tree != null;
if (tree instanceof HuffmanLeaf) {
HuffmanLeaf leaf = (HuffmanLeaf)tree;
// print out character, frequency, and code for this leaf (which is just the prefix)
System.out.println(leaf.value + "\t" + leaf.frequency + "\t" + "\t" + prefix);
} else if (tree instanceof HuffmanNode) {
HuffmanNode node = (HuffmanNode)tree;
// traverse left
prefix.append('0');
printCodes(node.left, prefix);
prefix.deleteCharAt(prefix.length()-1);
// traverse right
prefix.append('1');
printCodes(node.right, prefix);
prefix.deleteCharAt(prefix.length()-1);
}
}
}
最佳答案
为了回答您的第一个问题,您可以通过实现 compareTo()
来控制优先级队列中的顺序,因此我会执行以下操作:
abstract class HuffmanTree implements Comparable<HuffmanTree> {
public final int frequency; // the frequency of this tree
public HuffmanTree(int freq) {
frequency = freq;
}
@Override
public int compareTo(HuffmanTree tree) {
int comparison = frequency - tree.frequency;
if (0 == comparison) {
comparison = comparisonTieBreaker(tree);
}
return comparison;
}
private int comparisonTieBreaker(HuffmanTree tree) {
int comparison = 0;
if (this.size() == 1) {
if (tree.size() == 1) {
// alphabetical comparison between 2 single-character groups:
Character.compare(this.firstChar(), tree.firstChar());
}
else {
comparison = -1; // single < multiple
}
} else if (tree.size() == 1) {
comparison = 1; // multiple > single
}
return comparison;
}
public abstract int size();
public abstract char firstChar();
}
对于两个抽象方法,在 HuffmanLeaf
中,size()
返回 1,firstChar()
返回其字符。在 HuffmanNode
中,size()
返回 left.size() + right.size()
(基本递归)和 firstChar( )
可以返回 left.firstChar()
,尽管 firstChar()
通常不会在 HuffmanNode
上调用。
针对你的第二个问题,我认为你应该在 Huffman
类中使用 encode()
和 decode()
方法本身或另一个类中。显然,您可以从主方法中调用它们,但我会从主方法中提取任何可以在其他地方重用的内容。
编辑:您要求我详细说明。您的第二个问题不太清楚,但似乎您陷入了如何进行编码和解码的困境。我首先添加到 HuffmanTree
方法 toMapForDecoding()
和 toMapForEncoding()
,每个方法都返回一个 Map (它基本上与两种方法,但键和值相反)。这些映射(在 encode()
和 decode()
方法中使用)允许输入符号和(编码或解码)输出符号之间的恒定时间转换。这些方法的实现与您在 printCodes()
中所做的非常相似。至于把encode()
和decode()
方法放在哪里,不要被那个挡住了。将它们放在您方便的地方,然后在需要时移动它们。
关于java 哈夫曼树优先级,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36710369/
int x = 1; System.out.println( x++ + x++ * --x ); 上面的代码打印出“5”,但我不明白怎么办?我一直为最后一个 x 取零,然后乘以仍然为 0 的第二个
我现在正在尝试使用 Preference 类 首选项 pfrOfThis = Preferences.userNodeForPackage(this) 出现错误: “类 java.util.prefs
用下面的代码 import sys print "Hello " + sys.argv[1] if len(sys.argv) > 1 else "Joe" + "." 当我运行时 python he
我的网页包含: td { padding-left:10px; } 引用的样式表包含: .rightColumn * {margin: 0; padding: 0;} 我在 rightc
使用 JPA 我有一个关于 CascadeTypes 的问题。 例如: @ManyToMany(fetch=FetchType.LAZY, cascade={CascadeType.PERSIST,
下面的“括号”是怎么写的? val words = List("foo", "bar", "baz") val phrase = "These are upper case: " + words ma
我只是想知道,对于以下代码,编译器是否单独使用关联性/优先级或其他一些逻辑来评估。 int i = 0, k = 0; i = k++; 如果我们根据关联性和优先级进行评估,postfix ++具有比
我设置了一个 Azure FrontDoor 服务,以主/备份类型的方式将流量分配给两个 API 管理服务。就像我希望所有流量都流向我的主要 APIM 服务一样,如果我碰巧关闭该服务(假装中断),那么
这是一个简单的 CSS: /* Smartphones (portrait and landscape) ----------- */ @media only screen and (min-devi
我设置了一个 Azure FrontDoor 服务,以主/备份类型的方式将流量分配给两个 API 管理服务。就像我希望所有流量都流向我的主要 APIM 服务一样,如果我碰巧关闭该服务(假装中断),那么
来自 Programming Perl pg 90,他说: @ary = (1, 3, sort 4, 2); print @ary; 排序右侧的逗号在排序之前求值,而左侧的逗号在排序之
+----+------------+------+ | id | title | lang | +----+------------+------+ | 1 | title 1 EN |
如何使用 Java 获取 DiffServe 代码点 (DSCP) 整数的优先级部分?我预计它涉及位移位,但由于某种原因,我似乎无法获得我期望的值。 最佳答案 假设我理解正确,只需向右执行 3 位逻辑
我有下一个运行良好的 js 函数: $(function () { $(".country").click(function () { var countries = Arra
int a[3]={10,20,30}; int* p = a; cout << *p++ << endl; 根据 wikipedia ,后缀++的优先级高于解引用,*p++应该先运行p++再解引用结
我想在优先读取归档后解决这种类型的表达式 2+3/5*9+3-4 这是我尝试解决该任务的代码我该如何解决这个问题 while ( !inputFile.eof() ) { getline( inp
我正在玩 Rhino 并注意到这种奇怪的行为似乎是运算符优先级: js> {}+{} NaN js> ''+{}+{} [object Object][object Object] js> ''+({
我想遍历文件列表并检查它们是否存在,如果文件不存在则给出错误并退出。我写了下面的代码: FILES=( file1.txt file2.txt file3.txt ) for file in ${FI
我正在执行级联 SELECT: SELECT * FROM x WHERE a = 1 AND b = 2 AND c = 3 => If nothing found, try: SELECT * F
即将参加考试,我正在参加之前的考试。 问题: 当两个或多个样式表规则应用于同一元素时,以下哪种类型的规则将优先? 一个。任何来自浏览器的声明 b.有用户来源的正常声明 C。作者来源正常声明 d.文档级
我是一名优秀的程序员,十分优秀!