1

我有以下代码,它将采用 30 个字符串(即数字)并在使用“%29”计算它们后将它们放入哈希表中

import java.util.Arrays;


public class HashFunction {

    String[] theArray;
    int arraySize;
    int itemsInArray = 0;

    public static void main(String[] args) {

        HashFunction theFunc = new HashFunction(30); // this is where you should be able to control the number of spaces availble in the hash table!!!

        // Simplest Hash Function

        // String[] elementsToAdd = { "1", "5", "17", "21", "26" };

        // theFunc.hashFunction1(elementsToAdd, theFunc.theArray);

        // Mod Hash Function
        // This contains exactly 30 items to show how collisions
        // will work

        String[] elementsToAdd2 = { "100", "510", "170", "214", "268", "398",
                "235", "802", "900", "723", "699", "1", "16", "999", "890",
                "725", "998", "978", "988", "990", "989", "984", "320", "321",
                "400", "415", "450", "50", "660", "624" };

        theFunc.hashFunction2(elementsToAdd2, theFunc.theArray);

        // Locate the value 660 in the Hash Table

        //theFunc.findKey("660");

        theFunc.displayTheStack();

    }

    // Simple Hash Function that puts values in the same
    // index that matches their value

    public void hashFunction1(String[] stringsForArray, String[] theArray) {

        for (int n = 0; n < stringsForArray.length; n++) {

            String newElementVal = stringsForArray[n];

            theArray[Integer.parseInt(newElementVal)] = newElementVal;

        }

    }



    public void hashFunction2(String[] stringsForArray, String[] theArray) {

                        int sumOfCollisions = 0;
                        float averageOfCollisions = 0;
                        int numberOfCollisions = 0;                        

        for (int n = 0; n < stringsForArray.length; n++) {

            String newElementVal = stringsForArray[n];

            // Create an index to store the value in by taking
            // the modulus

            int arrayIndex = Integer.parseInt(newElementVal) % 29;

            System.out.println("Modulus Index= " + arrayIndex + " for value "
                    + newElementVal);

            // Cycle through the array until we find an empty space


            while (theArray[arrayIndex] != "-1") {
                ++arrayIndex;
                                numberOfCollisions++;

                //System.out.println("Collision Try " + arrayIndex + " Instead");
                                //System.out.println("Number of Collisions = " + numberOfCollisions);
                // If we get to the end of the array go back to index 0

                arrayIndex %= arraySize;
            }


                        if (numberOfCollisions > 0)
                        {
                            System.out.println("                       Number of Collisions = " + numberOfCollisions);
                        }                       

            theArray[arrayIndex] = newElementVal;

        }

                        sumOfCollisions += numberOfCollisions;

                        averageOfCollisions = sumOfCollisions / 30;

                        System.out.println("Sum of Collisions = " + sumOfCollisions);

                        System.out.println("Average of Collisions = " + averageOfCollisions);                

    }

    // Returns the value stored in the Hash Table

    public String findKey(String key) {

        // Find the keys original hash key
        int arrayIndexHash = Integer.parseInt(key) % 29;

        while (theArray[arrayIndexHash] != "-1") {

            if (theArray[arrayIndexHash] == key) {

                // Found the key so return it
                System.out.println(key + " was found in index "
                        + arrayIndexHash);

                return theArray[arrayIndexHash];

            }

            // Look in the next index

            ++arrayIndexHash;

            // If we get to the end of the array go back to index 0

            arrayIndexHash %= arraySize;

        }

        // Couldn't locate the key

        return null;

    }

    HashFunction(int size) {

        arraySize = size;

        theArray = new String[size];

        Arrays.fill(theArray, "-1");

    }

    public void displayTheStack() {

        int increment = 0;

        for (int m = 0; m < 3; m++) {

            increment += 10;

            for (int n = 0; n < 71; n++)
                System.out.print("-");

            System.out.println();

            for (int n = increment - 10; n < increment; n++) {

                System.out.format("| %3s " + " ", n);

            }

            System.out.println("|");

            for (int n = 0; n < 71; n++)
                System.out.print("-");

            System.out.println();

            for (int n = increment - 10; n < increment; n++) {

                if (theArray[n].equals("-1"))
                    System.out.print("|      ");

                else
                    System.out
                            .print(String.format("| %3s " + " ", theArray[n]));

            }

            System.out.println("|");

            for (int n = 0; n < 71; n++)
                System.out.print("-");

            System.out.println();

        }

    }

}

为方便起见,这里是输出:

    run:
Modulus Index= 13 for value 100
Modulus Index= 17 for value 510
Modulus Index= 25 for value 170
Modulus Index= 11 for value 214
Modulus Index= 7 for value 268
Modulus Index= 21 for value 398
Modulus Index= 3 for value 235
Modulus Index= 19 for value 802
Modulus Index= 1 for value 900
Modulus Index= 27 for value 723
Modulus Index= 3 for value 699
                       Number of Collisions = 1
Modulus Index= 1 for value 1
                       Number of Collisions = 2
Modulus Index= 16 for value 16
                       Number of Collisions = 2
Modulus Index= 13 for value 999
                       Number of Collisions = 3
Modulus Index= 20 for value 890
                       Number of Collisions = 3
Modulus Index= 0 for value 725
                       Number of Collisions = 3
Modulus Index= 12 for value 998
                       Number of Collisions = 3
Modulus Index= 21 for value 978
                       Number of Collisions = 4
Modulus Index= 2 for value 988
                       Number of Collisions = 7
Modulus Index= 4 for value 990
                       Number of Collisions = 9
Modulus Index= 3 for value 989
                       Number of Collisions = 14
Modulus Index= 27 for value 984
                       Number of Collisions = 15
Modulus Index= 1 for value 320
                       Number of Collisions = 23
Modulus Index= 2 for value 321
                       Number of Collisions = 31
Modulus Index= 23 for value 400
                       Number of Collisions = 31
Modulus Index= 9 for value 415
                       Number of Collisions = 37
Modulus Index= 15 for value 450
                       Number of Collisions = 40
Modulus Index= 21 for value 50
                       Number of Collisions = 43
Modulus Index= 22 for value 660
                       Number of Collisions = 47
Modulus Index= 15 for value 624
                       Number of Collisions = 61
Sum of Collisions = 61
Average of Collisions = 2.0
-----------------------------------------------------------------------
|   0  |   1  |   2  |   3  |   4  |   5  |   6  |   7  |   8  |   9  |
-----------------------------------------------------------------------
| 725  | 900  |   1  | 235  | 699  | 988  | 990  | 268  | 989  | 320  |
-----------------------------------------------------------------------
-----------------------------------------------------------------------
|  10  |  11  |  12  |  13  |  14  |  15  |  16  |  17  |  18  |  19  |
-----------------------------------------------------------------------
| 321  | 214  | 998  | 100  | 999  | 415  |  16  | 510  | 450  | 802  |
-----------------------------------------------------------------------
-----------------------------------------------------------------------
|  20  |  21  |  22  |  23  |  24  |  25  |  26  |  27  |  28  |  29  |
-----------------------------------------------------------------------
| 890  | 398  | 978  | 400  |  50  | 170  | 660  | 723  | 984  | 624  |
-----------------------------------------------------------------------
BUILD SUCCESSFUL (total time: 0 seconds)

如您所见,我已对其进行了设置,以便它告诉我在构建此特定哈希表时发生的平均冲突次数。有 30 个号码和 30 个空格供他们占用。我尝试将可用空间量的参数从 30 更改为 60,但这并没有改变任何东西,我想弄清楚如何解决这个问题。

这对我很重要,因为我想把这段代码提升一个档次。我想尝试这个程序以获得更大的数字集,可能是一千个或更多,但我不想只是手动输入一千多个字符串数字。我将如何编写一个可以为我执行此操作的循环?例如,如果我在它的参数中输入 1000,它将产生一千个字符串表示法(如代码中所示)的数字,这些数字将被使用。

我还想这样做,以便我可以在单个程序执行中运行多个这些字符串数字。例如,哈希表可以保存 1000 个数字,所以它会运行 1 个数字的程序,然后是 2,3,等等......直到它一直这样做到 1000。并且每次它这样做,我希望它输出该特定运行中发生的平均碰撞次数。只有 1 个数字不会发生冲突,最终会随着数字数量的增加而发生冲突。

通过这样做,我可以制作一个图表,显示碰撞数量如何随着数字与可用点的比率的变化而变化。例如,x 轴是平均碰撞次数,y 轴是输入数字数量与总可用空间的比率(意味着它的值范围为 0 到 1.00)

提前感谢所有花时间教我的人。对此,我真的非常感激。

4

2 回答 2

0

要让您的程序为您随机生成数字,您应该创建一个方法,该方法接受一个整数参数,该参数循环遍历该大小的数组并插入一个随机数。

int size_of_hash = Integer.parseInt( args[1] );

上面的代码将从命令行获取一个参数并使用它来创建一个变量来确定哈希表的大小。您可以使用此变量来创建哈希函数,也可以使用它来创建数组

你可以调用一个方法

public int[] createRandomArray( int size ) {
    Random r = new Random(); //java.util.Random - this class will randomly generate integers for you
     int random_array = //instantiate the array

     for( int i = 0; i <= size; i++ ) {
         //insert logic
      }

      return random_array;
 }

方法不完整。最好的学习方法是做。这里要注意的重要一点是,这种方法本质上是一个简单的重复任务,并让程序为您完成。Javadocs 是学习 Java 生态系统中新资源的绝佳资源。只需谷歌“javadoc random”,课程就会出现。

我建议将 main 方法更改为类的构造函数,并重写 main 方法以调用您可以在程序的参数中指定的许多试验。这将帮助您通过运行大量试验而不是一次试验来获得更准确的数据。

于 2014-03-03T05:39:46.917 回答
0

使用以下内容:

import java.util.Random; //that's where it is.
...
...//directly to the class
private Random r = new Random();
public String randomString(int limit)
{
    int n = r.nextInt(limit);
    return n+"";
}
...

这将返回(0 到限制 -1)String内的a 形式的随机数。limit如果您想要一串n数字,请执行此操作

StringBuilder s = new StringBuilder();
for(int i = 0; i < n; i++)
    s.append(r.nextInt(10));
return s.toString();
于 2014-03-03T05:40:59.867 回答