将随机数插入Java数组中

时间:2018-10-19 00:27:31

标签: java arrays hash hashtable

我必须使用开放寻址将900个随机整数散列到一个空表中,该表的大小设置为1009。为了确定该数字在表中的位置,我采用了随机数mod 1009,然后将其放在打开的位置。如果不是,我应该在那之后检查下一个键,并继续一个接一个地检查,直到找到一个可以放置随机数的键。到目前为止,我的代码是:

import java.util.*;

public class openAdd{
public static void main(String[] args) {
    //set table length
    int[] table = new int[1009];

    //insert 900 random integers into the table using open addressing
    //random number % table size = the key the number should be placed
    //if the key is already taken go to the next key until you find an open one
    Random randomGenerator = new Random();

    for (int i = 0; i < 900; i++) {
        int num = randomGenerator.nextInt(99999);
        int key = num % 1009;
        if (table[key] == 0) {
            table[key] = num;
        }
    }
}

}

我认为到目前为止我所拥有的都很好,我只是对如何将密钥设置为key + 1(如果原始密钥中已经有东西)感到困惑。谢谢您的帮助,如果需要添加任何内容,请告诉我。

1 个答案:

答案 0 :(得分:1)

您似乎有正确的想法,只是没有正确的实现。如果table[key]非零,则需要递增key,直到在table为零的table[key]中找到索引为止。您可以利用Java的余数运算符(就像您已经使用的那样)来防止key超出数组的边界:

int key = num % 1009;

if (table[key] == 0) {
    table[key] = num;
} else {
    while (table[key = (key + 1) % table.length] != 0);
    table[key] = num;
}

由于table.length大于要设置的元素数量,因此无需检查数组是否为 full 。另外,请记住,num可以是0