import java.util.Random; /** * An example of using a hashtable to check that a random string generator * actually is generating random strings * * @author gtowell * created: Sep 28, 2022 gtowell */ public class UseHT { // the hash table to hold random strings // I do not actually care about the value. private SepChainHT hashT; // an instance of the Java random number generator private Random rand; /** * Initialize the instance */ public UseHT() { hashT = new SepChainHT<>(10001); rand = new Random(); } /** * Generate a random string of the given length. * This uses only lower case letters. * @param len the length of the random string * @return the random string */ private String randomString(int len) { StringBuffer sb = new StringBuffer(); for (int i = 0; i < len; i++) { sb.append('a' + rand.nextInt(26)); } return sb.toString(); } /** * Do the testing of the random string generator. It will test * random strings of length 2 .. 4 and for each length will generate * between 10 and 100000 strings. The idea is to see how many unique strings * I get. If too few, then something is probably wrong with the generator */ public void querrier() { for (int i = 2; i < 5; i++) { // the length of the random string to make for (int j = 10; j < 100001; j = j * 10) { // the number of random strings to make hashT = new SepChainHT<>(j*2); // clear the hashtable and init with lots of room. for (int k = 0; k < j; k++) { // actually do the work of making the strings and putting them into the hashtable. String s = randomString(i); hashT.put(s, 1); } System.out.println( "Random String length: " + i + " number generated " + j + " number unique " + hashT.size()); } } } public static void main(String[] args) { (new UseHT()).querrier(); } }