Hash Table with Linear Probing and Random Numbers - java

Hi I have the task to show, and count, the trace of operations needed to insert the randomly generated keys, one by one, into an initially empty 101-bucket hash table.
I have created this class to generate 100 random numbers and then insert them into the hash table class, but i dont know how to insert them to the hash table and i do it manually.
I will appreciate if you give me some advice.
The Code:
import java.util.Random;
public class RandomNumbers {
static void main(String[] args) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
public RandomNumbers() {
for (int i = 0; i < 100; i++) {
System.out.println(getRandomNumberInRange(0, 15024267));
}
}
public static int getRandomNumberInRange(int min, int max) {
if (min >= max) {
throw new IllegalArgumentException("max must be greater than min");
}
Random r = new Random();
return r.nextInt((max - min) + 1) + min;
}
String[] numbersPrinting;
}
As you can see I inserted the random numbers manually.
The Hash Table Code:
import java.util.Arrays;
/**
*
*
*/
public class HashFunction {
String[] theArray;
int arraySize;
int itemsInArray = 0;
int K = 0;
/**
*
*/
public static void main(String[] args) {
HashFunction theFunc = new HashFunction(101);
String[] elementsToAdd2 = {"3638273","3483793","1362909","14908691","14624805","3959017","14208240","8911589","3701879", };
theFunc.hashFunction2(elementsToAdd2, theFunc.theArray);
}
public void hashFunction2(String[] stringsForArray, String[] theArray) {
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) % 101;
System.out.println("P" + arrayIndex + " " + "I" + newElementVal + "#" + arrayIndex );
// Cycle through the array until we find an empty space
while (theArray[arrayIndex] != "-1") {
++arrayIndex;
System.out.println( "P" + arrayIndex);
// If we get to the end of the bucket go back to index 0
arrayIndex %= arraySize;
}
theArray[arrayIndex] = newElementVal;
}
}
HashFunction(int size) {
arraySize = size;
theArray = new String[size];
Arrays.fill(theArray, "-1");
}
}
I don't know how to insert the random numbers from the random numbers class into the Hash Table class

I think what you should do is create Random numbers in the main function of HashFunction class:
public static void main(String[] args) {
HashFunction theFunc = new HashFunction(101);
String[] elementsToAdd2 = new String[101];
for (int i = 0; i <= 100; i++) {
elementsToAdd2[i] = Integer.toString(RandomNumbers.getRandomNumberInRange(0, 15024267));
}
theFunc.hashFunction2(elementsToAdd2, theFunc.theArray);
}
With this way, you will have access to Random Numbers array in HashFunction class and you can add it in theArray array of HashFunction class.

Related

invoke a method named printArray that prints my random numbers array

So far i have made a random numbers array but i am stuck on how to make a printarray method that i can call within the main. I need to invoke print array in the same class and print out all elements separated by one space
public class HunterIsaacsHw6
{
public static void main(String[] args)
{
System.out.println("Java, Online, Hunter Isaacs, hw6");
// define the range
int max = 100;
int min = 1;
int range = max - min + 1;
// combining both statements in one
double doubleArray[] = new double[10];
// generate random numbers within 1 to 10
for (int i = 0; i < 10; i++) {
doubleArray[i] = (Math.random() * range) + min;
}
}
public static double printArray(doubleArray[]){
for(double n: doubleArray){
System.out.println(n+" ");
}
}
Your method declaration is incorrect and you are not even calling it. Try:
public static void main(String [] args)
{
System.out.println("Java, Online, Hunter Isaacs, hw6");
// define the range
int max = 100;
int min = 1;
int range = max - min + 1;
// combining both statements in one
double doubleArray[] = new double[10];
// generate random numbers within 1 to 10
for (int i = 0; i < 10; i++) {
doubleArray[i] = (Math.random() * range) + min;
}
printArray(doubleArray);
}
public static void printArray(double doubleArray[]){
for(double n: doubleArray){
System.out.println(n);
}
}
Also, nothing is being returned from printArray so it should be declared as void
Also I prefer the declaration as double[] doubleArray
edit
Also System.out.println(n); is sufficient, there is no need to append a space

Trouble calling method and Populating Random Array

I am new to coding and trying to call a method (RandomArray) which I wrote and defined in a separate class, but in my driver code I am getting following error message:
Couldn't find symbol- RandomArray().
the code SHOULD create an array (size of which is chosen by the user) and then populate it with random numbers and output the Highest, Lowest, and Average of the numbers in said array.
All spellings match up, and the call itself works and displays no errors, but when using it in the for-loop I get the error message.
This is the class where I created the method:
import java.util.Random;
public class RandomArray
{
//things declared at class level
public int minimun,maximun,adverage, mn, mx, avg;
public String range;
//constucotr for inital numbers
public RandomArray()
{
minimun = 0;
maximun = 1000 + 1;
}
static int RandomArray()
{
Random ran = new Random();
return (ran.nextInt(1000) + 1);
}
//define types
public RandomArray (int mn, int mx, String r, int a)
{
minimun = mn;
maximun = mx;
range = r;
adverage = a;
}
//set minimun
public void setMinimun (int m)
{
minimun = mn;
}
//get minimun
public int getMinimun()
{
return minimun;
}
//set maximun
public void setMaximun(int x)
{
maximun = mx;
}
//get maximun
public int getMaximun()
{
return maximun;
}
//compute adverage
public int adverage(int...array)
{
int adverage = 0;
if (array.length > 0)
{
int sum = 0;
for(int num : array)
sum = sum + num; //add numbers in array
adverage = (int)sum / array.length; //divide numbers in array by the array lenth
}
return adverage;
}
//return values as a string
public String toString()
{
return String.valueOf(getMinimun() + getMaximun() + adverage());
}
}
And this is the driver program that should be populating the array (of users choice) with random numbers and printing the highest, lowest and average:
import java.util.Random;
import java.util.Scanner;
import java.util.Arrays;
public class DemoRandomArray
{
// variable go here
final int minimun = 0;
public static void main(String[] args)
{
final int max = 100;
RandomArray ra = new RandomArray();
int[] anArray = new int[1000];
for(int i=1; i < max; i++)
{
System.out.println(RandomArray());
}
}
}
The method is inside another class, so you need to use the class name.
RandomArray.RandomArray() instead of just RandomArray()

Java Methods and Arrays

I am just starting out in Java and I have searched through the internet for several hours and cannot seem to find something to help me on an assignment. I have an array and I need to write a method for it. It seems easy but I cannot seem to connect the two together. I understand the methods but we did not go over using them with arrays so I am totally confused. If there is a similar answer on here, please point me in the right direction.
Thank you for your time.
Question:
Write a method which takes in an integer from the user between 1 and 10 and determines if that number is part of the randomly generated array. It must have a method signature of (int []) and return a boolean.
public class ArrayExample {
public int [] createRandomArray() {
int size = (int) (Math.random() * 10) + 1;
int[] array = new int [size];
for (int i = 0; i < array.length; i++) {
array[i] = (int) (Math.random() * 10 ) + 1;
}
return array;
}
public static void main(String [] args) {
}
}
It will be something like below:
public class ArrayExample {
public static int [] createRandomArray() {
int size = (int) (Math.random() * 10) + 1;
int[] array = new int [size];
for (int i = 0; i < array.length; i++) {
array[i] = (int) (Math.random() * 10 ) + 1;
}
return array;
}
private static boolean checkForNumInArray(int[] randomArrayInput){
//your logic goes here
// ask user for input number - Scanner/BufferedReader
//search for that number in array - Loops
// if found return true, otherwise return false - if-else
}
public static void main(String [] args) {
int[] randomArray = createRandomArray();
boolean isPresent = checkForNumInArray(randomArray);
}
}
You can go through the code to have understanding
public class ArrayExample {
public int [] createRandomArray() {
int size = (int) (Math.random() * 10) + 1;
int[] array = new int [size];
for (int i = 0; i < array.length; i++) {
array[i] = (int) (Math.random() * 10 ) + 1;
}
return array;
}
public int getUserInput() {
//Take input from user and check it is between 1 and 10.
}
public boolean search(int[] arr, int input) {
// Use some searching algorithm. Linear search will suit as the array is randomly generated.
// if input is present in array return true else return false.
}
public static void main(String [] args) {
int input = getUserInput();
boolean result = search(createRandomArray(), input);
//Print a message based on result.
}
}
In the main method you simply have to iterate the loop of integers from one to ten and check if it is present in the array you have created.
public static void main(String[] args) {
int arr[] = createRandomArray();
for(int i=0;i<=10;i++) {
if(Arrays.binarySearch(arr, i) == 0) { System.out.println("yes"); }
}
}

How to remove duplicates from array using for loop

In this code I have found duplicates from an array and I want to remove them. The output then will be unique generated numbers. I am required to use math.random and modulo. Anyone have any clues? I tried to store them in an array but then the original array has 0's and 0 is part of my domain for the random number generation (from 0 to 52).
public class Decks {
public static void main(String[] args) {
generate();
}
public static void generate() {
int deckOfCard[] = new int[52];
for (int counts = 0; counts < 52; counts++) {
deckOfCard[counts] = (int) (Math.random() * 51);
}
for (int i = 0; i < deckOfCard.length - 1; i++) {
for (int j = i + 1; j < deckOfCard.length; j++) {
if ((deckOfCard[i] == (deckOfCard[j])) && (i != j)) {
System.out.println("DUPLICATE " + deckOfCard[i]);
}
}
}
for (int count = 0; count < deckOfCard.length; count++) {
System.out.print("\t" + deckOfCard[count]);
}
}
Why dont you try using HashSet instead of arrays ? As you know sets only store unique values so you wont have any duplicates.
You must validate the numbers generated during the random number generation like this:
import java.util.Random;
public class Decks {
public static void main(String[] args) {
Random myRandom = new Random();
int[] num = new int[53];
boolean[] check = new boolean[53];
int all = 0;
int ranNum;
while (all < 53) {
ranNum = myRandom.nextInt(53);
if (!check[ranNum]) {
check[ranNum] = true;
num[all] = ranNum;
all++;
}
}
for (int i = 0; i < 53; i++) {
System.out.println(num[i]);
}
}
}
I suggest not including number 0 because it does not exist in a real deck of cards (ACE being the lowest having the number value of 1). I just included it right here because in my understanding, 0 is included in your desired output.
Considering time complexity, you can sort them first, which at best case takes nlogn time, and then use O(1) to find duplicated elements out.

Suggest some more optimised solution for this rand generator

I have a function 'generateRan' that generates random numbers. This function can not be changed.
int generateRan() {
Random num = new Random();
return (1 + num.nextInt(100));
}
I have to write code that will:
Print numbers 1-20 randomly.
Print numbers 1-200 randomly.
Each number should be printed only once.
The function can be used any number of times. But it is a bit heavy so I want to make the code more optimized.
Here is what I've coded:
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
public class Test {
public static void main(String[] args) {
List<String> list = new ArrayList();
Test t = new Test();
iniList(list, 20);
for (Integer i = ((t.generateRan()) % 20); list.size() > 0; i = 1+((t
.generateRan()) % 20)) {
if (list.contains(i.toString())) {
list.remove(i.toString());
System.out.println(i);
}
}
System.out.println("********");
iniList(list, 200);
for (Integer i = ((t.generateRan()%2)*100 + t.generateRan()) ; list.size() > 0; i = ((t.generateRan()%2)*100 + t.generateRan())) {
if (list.contains(i.toString())) {
list.remove(i.toString());
System.out.println(i);
}
}
}
private static void iniList(List list, int i) {
for (Integer k = 1; k <= i; k++) {
list.add(k.toString());
}
}
int generateRan() {
Random num = new Random();
return (1 + num.nextInt(100));
}
}
Currently the code for 1-200 is incorrect.
Each numbers should print only once
Then all you need to to is create a List<Integer> of the entire range, then call Collections.shuffle.
private static void displayNumbers(int minInclusive, int maxInclusive) {
List<Integer> list = new ArrayList<Integer>();
for (int i = minInclusive; i <= maxInclusive; i++) {
list.add(i);
}
Collections.shuffle(list);
for (int value : list) {
System.out.println(value);
}
}
Personally I'd normally use parameters of minInclusive, maxExclusive or minInclusive, count, but it looks like it may be more readable this way for your situation.
Assuming you have to use your generateRan() function, otherwise use Collections.shuffle as indicated.
public static void main(String[] args) {
List<Integer> list = new ArrayList();
initList(list, 200);
while (list.size() > 0) {
int index = generateRan() % list.size();
System.out.println(list.remove(index));
}
}
public static void initList(List<Integer> s, int size) {
for (int i = 1; i <= size; i ++)
s.add(i);
}
public static int generateRan() {
Random num = new Random();
return (1 + num.nextInt(100));
}
You add all the ints you want to print to your list, then only use random to choose which one of these to print. Your function is called n times.
I would recomment using a Set rather than a List, for it's faster in searching for duplicates
Set<Integer> set = new HashSet<Integer>();
for(int i = 0; i < 20;) {
Integer r = generateRan();
if(set.add(r)) {
System.out.println(r);
++i;
}
}

Categories