【问题标题】:How do I populate trees with many random integers?如何用许多随机整数填充树?
【发布时间】: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


    【解决方案1】:

    Math.random 返回一个介于 0.0 和 1.0 之间的双精度值,因此转换为 int 是错误的。

    这就像0 * 3001 * 300 == 不是很随机。

    如果你乘以 300.00,结果会完全不同。

    也可以考虑http://docs.oracle.com/javase/7/docs/api/java/util/Random.html

    在内存中保留一个Random 实例并调用nextInt #nextInt()

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-09-16
      • 1970-01-01
      • 1970-01-01
      • 2014-05-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多