【发布时间】:2015-03-16 08:49:57
【问题描述】:
我正在编写一个程序,该程序应该用 1000 个随机值填充十个随机树,范围从 0 到 300。这是我的测试器类的代码。然而,当我运行这个程序时,它会为每棵树打印出完全相同的内容,而在代码方面,它看起来就像我正在添加不同的随机数。
我感觉它一直在添加相同的数字,但我不知道如何更改它。我对 Random 类或 Math.random() 不是很熟悉。
package ch08.trees;
import java.util.ArrayList;
public class BSTTest {
ArrayList<BinarySearchTree<Integer>> trees = new ArrayList<BinarySearchTree<Integer>>();
public BSTTest() {
for(int h = 0; h < 10; h++) { //Populate the arraylist with 10 trees
trees.add(new BinarySearchTree<Integer>());
}
for(int i = 0; i < 10; i++) //Run through 10 trees in array
for(int j = 0; j < 1000; j++) { //1000 integers for each tree
trees.get(i).add((int) Math.random()*300);
}
}
public String toString() {
String s = "";
for(int i = 0; i < 10; i++) {
int height = trees.get(i).height();
int optimal = trees.get(i).optimal();
double ratio = (double) height/(double) optimal; //Ratio only useful when decimal
s += "Tree " + i + "--" + "Height: " + height + ", Optimal Height: " + optimal +
", Bushyness Ratio: " + ratio + "\n";
}
return s;
}
public static void main(String[] args) {
BSTTest a = new BSTTest();
System.out.println(a);
}
}
【问题讨论】:
标签: java tree binary-tree binary-search-tree populate