CSC1109_Tutorials/Week6_Lab/lab6_Hash.java

94 lines
2.7 KiB
Java

package Week6_Lab;
import java.util.*;
public class lab6_Hash {
public static void main(String[] args){
HashMap<Integer, Integer> ht = new HashMap<>();
ht.put(0,1);
ht.put(1,3);
ht.put(2,5);
ht.put(3,7);
ht.put(4,9);
ht.put(5,11);
// Question 1
System.out.print("Before adding: ");
printHashMap(ht);
System.out.print("After adding and sorting: ");
printHashMap(addAndSort(ht, 10));
// Question 2
System.out.println("After swapping");
swap(ht, 1, 6);
printHashMap(ht);
//Question 3
HashMap<Integer, Integer> ranIntHash = new HashMap<>();
Random rand = new Random();
for (int i = 0; i < 500; i++) {
ranIntHash.put(i, rand.nextInt(1000, 9999));
}
System.out.println("The 500 random numbers generated are: ");
printHashMap(ranIntHash);
int randomIntegerToSearch = rand.nextInt(1000, 9999);
System.out.println("\nAnother random number generated is " + randomIntegerToSearch);
int index = search(ranIntHash, randomIntegerToSearch);
System.out.println(index);
}
public static void printHashMap(HashMap<Integer, Integer> ht){
System.out.print("[");
for (int i = 0; i < ht.size(); i++) {
if (Objects.equals(ht.get(i), ht.get(ht.size() - 1))) {
System.out.println(ht.get(i) + "]");
break;
}
System.out.print(ht.get(i) + ", ");
}
}
public static HashMap<Integer, Integer> addAndSort(HashMap<Integer, Integer> ht, int value){
//Collections.sort(ht); Does Not Work
// For each value in ht, if value is less than value, insert value at that index
for (int i = 0; i < ht.size(); i++) {
if (value < ht.get(i)) {
ht.put(ht.size(), ht.get(ht.size() - 1));
// Shift all values to the right of i to the right
for (int j = ht.size() - 2; j > i; j--) {
ht.put(j, ht.get(j - 1));
}
ht.put(i, value);
break;
}
}
return ht;
}
public static void swap(HashMap <Integer, Integer> ht, int indexOne, int indexTwo){
// Swap the values at indexOne and indexTwo
int temp = ht.get(indexOne);
ht.put(indexOne, ht.get(indexTwo));
ht.put(indexTwo, temp);
}
public static int search(HashMap <Integer, Integer> ht, int searchVal){
// Return index of searchVal if found, else return -1
for (int i = 0; i < ht.size(); i++) {
if (ht.get(i) == searchVal) {
return i;
}
}
return -1;
}
}