Hellow, For some off reason I cannot get my hash table to fill with the items and keys when I insert. It seems like it is being added when run through the driver, but nothing is stored, and there are absolutely no error messages.
I am suppose to create a hash table that utilizes quadratic probing. I am suppose to count the number of transversals which cannot be > 20.
Here is the code:
public class HashTable {
String[] table;
String[] keys;
int currentSize, maxSize, numOfEntries;
int traverse = 0;
double capacity;
public HashTable(int size, double load){
if(size <= 0){
System.out.println("Size must be greater then 0");
}
else if(load < 0 || load > 1){
System.out.println("Load must be between 0 and 1. EX: 0.75");
}else{
this.currentSize = 0;
table = new String[size];
keys = new String[size];
this.capacity = load * size;
this.maxSize = size;
}
}
public int hash(String num){
return (2 * Integer.parseInt(num) + 5) % table.length;
}
public int getLength(){
return table.length;
}
public int getMaxSize(){
return maxSize;
}
public int probe(String num){
int temp = hash(num);
int calc = 0;
numOfEntries = 0;
while(table[temp] != null){
traverse++;
temp = (int)((temp + (float)calc/2 + (float) (calc * calc)) % maxSize);
calc++;
numOfEntries++;
}
if(traverse >= 20){
System.out.println("Insert Failed : Reached 20 Traversal Limit!");
return 20;
}
return temp;
}
public void resize(){
String [] tempTable = table;
if(table.length >= capacity){
table = new String[tempTable.length * 2];
for(int i = 0; i < tempTable.length; i++){
if(tempTable[i] != null){
insert(tempTable[i]);
}
}
}
}
public void insert(String num){
int temp = probe(num);
table[temp] = num;
currentSize++;
if(currentSize >= capacity){
resize();
}
}
public String searchKey(String key){
String temp = "";
numOfEntries = 0;
for(int i = 0; i < keys.length; i++){
if(key == keys[i]){
temp = table[i];
numOfEntries++;
break;
}
numOfEntries++;
}
if(temp == ""){
System.out.println("No items that match that key!");
}
return temp;
}
public int numOfEntries(){
return numOfEntries;
}
public void print(){
System.out.println("Key\t:\tValue");
for(int i = 0; i < table.length; i++){
if(keys[i] != null){
System.out.println(keys[i] + "\t:\t" + table[i]);
}
}
System.out.println();
}
}
Here is the Driver:
import java.util.*;
public class HashTableDriver {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter Table Size:\t");
int size = scan.nextInt();
System.out.println("Enter Load Factor (Between 0 and 1");
double load = scan.nextDouble();
int temp = 0;
HashTable table = new HashTable(size,load);
System.out.println(table.getLength());
System.out.println(table.getMaxSize());
while(temp != 4){
System.out.println();
System.out.println("i)(1) Insert an item to the Hash Table" +
"\nii)(2) Search A Specific Key" +
"\niii)(3) Display the Table" +
"\nvii)(4) Quit");
String input = scan.next();
switch(input){
case "1":
System.out.println();
System.out.println("Enter value to add to table");
String desKey1 = scan.next();
table.insert(desKey1);
continue;
case "2":
System.out.println("Please enter specific key desired:\t");
String desKey2 = scan.next();
if(table.searchKey(desKey2).equals(desKey2)){
System.out.println("Key Found");
System.out.println("Number of cells accessed:\t" + table.numOfEntries());
}
else{
System.out.println("Key Not Found");
}
continue;
case "3":
table.print();
continue;
case "4":
temp = 4;
break;
}
}
}
}
Related
Prompt: Write a program that reads five cards from the user, then analyzes the cards and prints out the category of hand that they represent.
Poker hands are categorized according to the following labels: Straight flush, four of a kind, full house, flush, straight, three of a kind, two pairs, pair, high card.
I currently have my program set as follows, first prompting the user for 5 cards, 2-9, then sorting the cards in ascending order. I set up my program to prompt the user and then go through several if else statements calling methods. I am having issues though where its not identifying three or four of a kind.
Example, if I enter 1, 3, 2, 1, 1, it identifies it as TWO PAIRS instead of Three of a Kind.
Same for entering 1, 1,1, 1, 4, it identifies as three of kind instead of 4.
Any suggestions to my code?
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
final int HAND_SIZE = 5;
int[] hand = new int[HAND_SIZE];
getHand(hand); //Prompt user for hand
sortHand(hand);//Sort hand in ascending order
if(containsFullHouse(hand))
{
System.out.print("FULL HOUSE!");
}
else if(containsStraight(hand))
{
System.out.print("STRAIGHT!");
}
else if(containsFourOfAKind(hand))
{
System.out.print("FOUR OF A KIND!");
}
else if(containsThreeOfAKind(hand))
{
System.out.println("THREE OF A KIND!");
}
else if(containsTwoPair(hand))
{
System.out.println("TWO PAIRS!");
}
else if(containsPair(hand))
{
System.out.println("PAIR!");
}
else
System.out.println("High Card!");
}
public static void getHand(int[] hand)
{
Scanner input = new Scanner(System.in);
System.out.println("Enter five numeric cards, 2-9, no face cards please");
for(int index = 0; index < hand.length; index++)
{
System.out.print("Card " + (index + 1) + ": ");
hand[index] = input.nextInt();
}
}
public static void sortHand(int[] hand)
{
int startScan, index, minIndex, minValue;
for(startScan = 0; startScan < (hand.length-1); startScan++)
{
minIndex = startScan;
minValue = hand[startScan];
for(index = startScan + 1; index <hand.length; index++)
{
if(hand[index] < minValue)
{
minValue = hand[index];
minIndex = index;
}
}
hand[minIndex] = hand[startScan];
hand[startScan] = minValue;
}
}
public static boolean containsPair(int hand[])
{
boolean pairFound = false;
int pairCount = 0;
int startCheck = hand[0];
for(int index = 1; index < hand.length; index++)
{
if((hand[index] - startCheck) == 0)
{
pairCount++;
}
startCheck = hand[index];
}
if (pairCount == 1)
{
pairFound = true;
}
else if(pairCount !=1)
{
pairFound = false;
}
return pairFound;
}
public static boolean containsTwoPair(int hand[])
{
boolean twoPairFound = false;
int twoPairCount = 0;
int startCheck = hand[0];
for(int index = 1; index < hand.length; index++)
{
if((hand[index] - startCheck) == 0)
{
twoPairCount++;
}
startCheck = hand[index];
}
if (twoPairCount == 2)
{
twoPairFound = true;
}
else if(twoPairCount != 2)
{
twoPairFound = false;
}
return twoPairFound;
}
public static boolean containsThreeOfAKind(int hand[])
{
boolean threeFound = false;
int threeKind = 0;
int startCheck = hand[0];
for(int index = 1; index < hand.length; index++)
{
if((hand[index] - startCheck) == 0)
{
threeKind++;
}
startCheck = hand[index];
}
if(threeKind == 3)
{
threeFound = true;
}
else if(threeKind !=3)
{
threeFound = false;
}
return threeFound;
}
public static boolean containsStraight(int hand[])
{
boolean straightFound = false;
int straight = 0;
int startCheck = hand[0];
for(int index = 1; index < hand.length; index++)
{
if((hand[index] - startCheck) == 1)
{
straight++;
}
startCheck = hand[index];
}
if(straight == 4)
{
straightFound = true;
}
return straightFound;
}
public static boolean containsFullHouse(int hand[])
{
boolean fullHouseFound = false;
int pairCheck = 0;
int startPairCheck = hand[0];
for(int index = 1; index < hand.length; index++)
{
if((hand[index] - startPairCheck) == 0)
{
pairCheck++;
}
startPairCheck = hand[index];
}
int threeOfKindCheck = 0;
int startThreeKindCheck = hand[0];
for(int index = 1; index < hand.length; index++)
{
if((hand[index] - startThreeKindCheck) == 0)
{
threeOfKindCheck++;
}
startThreeKindCheck = hand[index];
}
if(pairCheck == 1 && startThreeKindCheck == 3)
{
fullHouseFound = true;
}
return fullHouseFound;
}
public static boolean containsFourOfAKind(int hand[])
{
boolean fourFound = false;
int fourKind = 0;
int startCheck = hand[0];
for(int index = 1; index < hand.length; index++)
{
if((hand[index] - startCheck) == 0)
{
fourKind++;
}
startCheck = hand[index];
}
if(fourKind == 1)
{
fourFound = true;
}
else if(fourKind !=4)
{
fourFound = false;
}
return fourFound;
}
}
Some hints.
Start with the highest hand. This eliminates lots of logic.
I.e if you check for pairs first, than you also have to check to make sure that your pair is the only pair, and not three of a kind.
But if you already ruled all of those out your code would be check card 1and2 23 34 and 45.
I have a question. As an assignment we have to make the Nim game resolver using backtracking to predict which player is going to win based on the input on which player is going to start first (assuming that both players have a perfect decision rate).
Here is the code for the NimGame:
package Nim;
import java.util.ArrayList;
public class NimGame {
private int[] elements;
public NimGame(int[] elements) {
this.elements = new int[elements.length];
this.elements = elements;
}
public int NimSolver(boolean player) {
if (player == true && NimHelp(elements) == true) {
return 1;
} else if (player == false && NimHelp(elements) == true) {
return -1;
} else {
int score = 0;
int tmp = 0;
if (player == true) {
score = -1;
} else {
score = 1;
}
for (int i = 0; i < elements.length; i++) {
for (int j = 1; j <= elements[i]; j++) {
// Decrement element (Do thing)
elements[i] -= j;
// Backtrack
tmp = NimSolver(!player);
// SetScore
if (player == true && tmp > score) {
score = tmp;
} else if (player == false && tmp < score) {
score = tmp;
}
// Increment element (Undo thing)
elements[i] += j;
}
}
return score;
}
}
private boolean NimHelp(int[] elements) {
boolean[] isEmpty = new boolean[elements.length];
for (int i = 0; i < elements.length; i++) {
if (elements[i] == 0) {
isEmpty[i] = true;
} else {
isEmpty[i] = false;
}
}
for (boolean value : isEmpty) {
// If not all value is empty return false
if (!value)
return false;
}
return true;
}
public void NimResult(int player,int result)
{
if (player == 1) {
result = NimSolver(true);
} else if (player == 2) {
result = NimSolver(false);
}
if (result == 1) {
System.out.println("");
System.out.println("PLAYER 1 WON");
} else {
System.out.println("");
System.out.println("PLAYER 2 WON");
}
}
public void NimPrint(ArrayList<Integer> element)
{
System.out.println("");
System.out.print("MATCHES--------------------------------------");
for(int i = 0; i < element.size() ;i++)
{
System.out.println("");
for (int j = 0; j < element.get(i) ; j++) {
System.out.print("|");
}
}
}
}
Here is the code for Test Main class:
package Main;
import java.util.ArrayList;
import java.util.Scanner;
import Nim.NimGame;
public class Main {
public static void main(String[] args) {
int rows;
int elementTmp;
ArrayList<Integer> rowTmp = new ArrayList<Integer>();
int playerNo;
int result = 0;
int[] elements;
#SuppressWarnings("resource")
Scanner sc = new Scanner(System.in);
System.out.print("Input number of rows: ");
rows = sc.nextInt();
elements = new int[rows];
System.out.println("");
System.out.println("Input number of elements in each row");
for (int i = 0; i < rows; i++) {
System.out.print("Row number " + (i + 1) + " : ");
elementTmp = sc.nextInt();
elements[i] = elementTmp;
rowTmp.add(elementTmp);
}
NimGame nim = new NimGame(elements);
nim.NimPrint(rowTmp);
System.out.println("");
System.out.println("---------------------------------------------");
System.out.println("");
System.out.println("First player to move");
System.out.println("1) Player 1");
System.out.println("2) Player 2");
System.out.print("Input: ");
playerNo = sc.nextInt();
nim.NimResult(playerNo, result);
}
}
It works for the sequence: 3 rows , Row1 = 1, Row2 = 2, Row3 = 3 for example:
Input number of rows: 3
Input number of elements in each row
Row number 1 : 1
Row number 2 : 2
Row number 3 : 3
MATCHES--------------------------------------
|
||
|||
---------------------------------------------
First player to move
1) Player 1
2) Player 2
Input: 1
PLAYER 2 WON
But it doesn't work for all the sequences. I don't understand why.
I am having trouble for the past week trying to solve how to check if an Id has already been added to the array, and if it has, stop the user from entering the rest of the data, I would greatly appreciate some help with this.
My code:
class CustomerUse {
public static int checkId(Customer theArray[], int noOfValues,
String searchId) {
int idCheck = 0;
int step = 0;
while (step < noOfValues) {
step++;
if ((step < noOfValues) && (theArray[step].getId().equals(searchId))) {
idCheck = -1;
}
}
return idCheck;
}
public static void listAllNames(Customer[] names, int NoOfElements) {
int index;
String result;
for (index = 0; index < NoOfElements; index++) {
System.out.println(names[index]);
}
}
public static int findPlace(Customer theArray[], int balance, int noOfValues) {
int step;
int place;
step = 0;
while ((step < noOfValues) && (balance < theArray[step].getBalance())) {
step++;
}
place = step;
return place;
}
public static int addOne(Customer theArray[], int place, String Id,
Customer theObject, int noOfValues) {
int step;
if (noOfValues == 0) {
theArray[0] = theObject;
noOfValues++;
} else {
for (step = noOfValues - 1; step >= place; step--) {
theArray[step + 1] = theArray[step];
}
theArray[place] = theObject;
noOfValues++;
}
return noOfValues;
}
public static int deleteName(Customer theArray[], int noOfElements) {
String searchId;
int step;
int whichOne = 0;
System.out.println("Enter Id of customer to be deleted ");
searchId = EasyIn.getString();
step = 0;
while ((step < noOfElements)
&& !(theArray[step].getId().equals(searchId))) {
step++;
}
if (step < noOfElements) {
whichOne = step;
for (step = whichOne; step < noOfElements - 1; step++) {
theArray[step] = theArray[step + 1];
}
noOfElements--;
} else {
System.out.println(" Sorry this customer doesn't exist");
}
return noOfElements;
}
public static void main(String[] args) {
Customer empArray[];
int index;
int noOfElements;
String searchName;
Customer tempObject;
int step;
int option = 0;
int place;
String newName = "";
String newId;
int newBalance;
int checkID = 0;
empArray = new Customer[100000];
noOfElements = 0;
System.out
.println("\n 1. Add Customer \n 2. Delete Customer \n 3. List all Customers \n 4. Exit");
System.out.print("Enter Option ");
option = EasyIn.getInt();
while (option != 4) {
if (option == 1) {
System.out.print("Enter ID ");
newId = EasyIn.getString();
System.out.print("Enter name ");
newName = EasyIn.getString();
System.out.print("Enter Balance ");
newBalance = EasyIn.getInt();
System.out.println();
tempObject = new Customer(newName, newId, newBalance);
place = findPlace(empArray, newBalance, noOfElements);
noOfElements = addOne(empArray, place, newId, tempObject,
noOfElements);
checkID = checkId(empArray, noOfElements, newId);
if (checkID == -1) {
System.out.println("Sorry this ID already exists");
checkID = 0;
}
} else if (option == 2) {
noOfElements = deleteName(empArray, noOfElements);
} else if (option == 3) {
listAllNames(empArray, noOfElements);
}
System.out.print("Enter Option ");
option = EasyIn.getInt();
}
}
}
This effectively skips array entry at index 0:
while (step < noOfValues)
{
step++;
Better:
public static int checkId(Customer theArray[], int noOfValues, String searchId){
for (int step = 0; step < noOfValues; ++step ){
if( theArray[step].getId().equals(searchId) )
{
return step;
}
}
return -1;
}
Return -1 on not found, otherwise the index.
I haven't checked the remainder of your code, just saw that the use of an array should be discarded in favour of a List.
Hy there. Below you can see sagment of my code. So lets go to the problem.
int i is not returning correct values and i cannot figure it out why.
LIST: [AGRFT, AGRFT, ARNES, ASCII, ASEAN, Aaron, Abdul, Abdul]
So for example. User inputs AS***, the program should return i is at 2. However i am getting i is at 0.
If i remember right it should go like this:
User_input= AS***
User_input.lenght() should be 5
first it should be user_input.charAt(0)=='*' NO
second it should be user_input.charAt(1)=='*' NO
third it should be user_input.charAt(2)=='*' YES
BREAK
i is at 2.
SO what am i missing?
I am getting 0.
Oh and also at
for(i=0; i < user_input.length();i++){
i am getting warning that i++ is Dead code?
if (dolzina == 5) {
for(i=0; i < user_input.length();i++){
if (user_input.charAt(i)=='*');
break;
}
System.out.println("i is at "+ i);
this is my full code for refrence. What it does it reads from txt file add wor
public class proba {
public static void main(String[] args) {
String izbira;
int dolzina=0;
int i=0;
Scanner in = new Scanner(System.in);
String user_input;
Scanner input = new Scanner(System.in);
String regex;
List<String> list5 = new ArrayList<String>();
int beseda;
String prefix = null;
try {
File file = new File("sort.txt");
FileReader fileReader = new FileReader(file);
BufferedReader bufferedReader = new BufferedReader(fileReader);
String vrstica;
while ((vrstica = bufferedReader.readLine()) != null) {
if (vrstica.length() == 5) {
list5.add(vrstica);
}
}
System.out.println(list5);
do{
do {
System.out.println("Enter lenght of word:");
if (in.hasNextInt()) {
dolzina = in.nextInt();
} else if (in.hasNextLine()) {
System.out.printf("Wrong entry!%n ",
in.nextLine());
}
} while (dolzina <= 0);
Collections.sort(list5);
System.out.println("Enter a word for unknown character enter * :");
user_input = input.nextLine();
System.out.println("Sorted list: [length: " + list5.size() + "]");
if (dolzina == 5) {
for(i=0; i < user_input.length();i++){
if (user_input.charAt(i)=='*');
break;
}
System.out.println("i je"+ i);
prefix=user_input.substring(0,i);
System.out.println(prefix);
int start=binarySearchfirst(list5,prefix);
int end=binarySearchlast(list5,prefix);
System.out.println(start);
System.out.println(end);
for (int b=start;b<=end;b++)
{
user_input = user_input.replace("*", ".");
String s = (String) list5.get(b);
if (s.matches(user_input))
System.out.println(s);
}
}
dolzina=-1;
System.out.println("Ponovni vnos (da/ne):");
Scanner inn= new Scanner (System.in);
izbira = inn.next();
}while (izbira.equalsIgnoreCase("da"));
bufferedReader.close();
} catch (IOException e) {
e.printStackTrace();
}}
public static int binarySearchfirst(List<String> integerList, String prefix) {
int low = 0;
int high = integerList.size() - 1;
while (low <= high) {
int mid = (low + high) / 2;
if (integerList.get(mid).startsWith(prefix)) {
if (mid == 0 || !integerList.get(mid - 1).startsWith(prefix)) {
return mid;
} else {
high = mid - 1;
}
} else if (prefix.compareTo(integerList.get(mid)) > 0) {
low = mid + 1;
} else {
high = mid - 1;
}
}
return low;
}
public static int binarySearchlast(List<String> integerList, String prefix) {
int low = 0;
int high = integerList.size()-1;
while (low <= high) {
int mid = (low+high)/2;
if (integerList.get(mid).startsWith(prefix)) {
if (mid == integerList.size()-1 || !integerList.get(mid+1).startsWith(prefix)) {
return mid;
}
else {
low = mid+1;
}
}
else if (prefix.compareTo(integerList.get(mid)) > 0) {
low = mid+1;
}
else {
high = mid-1;
}
}
return high;
}
}
You have an extra semi-colon after your if statement:
for(i=0; i < user_input.length();i++)
{ if (user_input.charAt(i)=='*');
break;
}
So the break is executed the first time through the loop no matter what. This is also why i++ is being reported as dead code...it's never being executed.
import java.util.InputMismatchException;
import java.util.Scanner;
import java.util.Stack;
public class TSPNearestNeighbour {
{
private final Stack<Integer> stack;
private int numberOfNodes;
public TSPNearestNeighbour()
{
stack = new Stack<Integer>();
}
public void tsp(int adjacencyMatrix[][])
{
numberOfNodes = adjacencyMatrix[1].length - 1;
int[] visited = new int[numberOfNodes + 1];
visited[1] = 1;
stack.push(1);
int element, dst = 0, i,cost=0;
int min = Integer.MAX_VALUE;
boolean minFlag = false;
System.out.print(1 + "\t");
while (!stack.isEmpty())
{
element = stack.peek();
i = 1;
min = Integer.MAX_VALUE;
while (i <= numberOfNodes)
{
if (adjacencyMatrix[element][i] > 1 && visited[i] == 0)
{
if (min > adjacencyMatrix[element][i])
{
min = adjacencyMatrix[element][i];
cost=cost+adjacencyMatrix[element][i];
dst = i;
minFlag = true;
}
}
i++;
}
if (minFlag)
{
visited[dst] = 1;
stack.push(dst);
System.out.print( dst + "\t");
minFlag = false;
continue;
}
stack.pop();
}
System.out.println("total cost" +cost);
}
public static void main(String args[])
{
int number_of_nodes;
Scanner scanner = null;
try
{
System.out.println("Enter the number of nodes in the graph");
scanner = new Scanner(System.in);
number_of_nodes = scanner.nextInt();
int adjacency_matrix[][] = new int[number_of_nodes + 1][number_of_nodes + 1];
System.out.println("Enter the adjacency matrix");
for (int i = 1; i <= number_of_nodes; i++)
{
for (int j = 1; j <= number_of_nodes; j++)
{
adjacency_matrix[i][j] = scanner.nextInt();
}
}
for (int i = 1; i <= number_of_nodes; i++)
{
for (int j = 1; j <= number_of_nodes; j++)
{
if (adjacency_matrix[i][j] == 1 && adjacency_matrix[j][i] == 0)
{
adjacency_matrix[j][i] = 1;
}
}
}
System.out.println("the citys are visited as follows");
TSPNearestNeighbour tspNearestNeighbour = new TSPNearestNeighbour();
tspNearestNeighbour.tsp(adjacency_matrix);
} catch (InputMismatchException inputMismatch)
{
System.out.println("Wrong Input format");
}
scanner.close();
}
}
> illegal start of expression in the line:
> **private final Stack<Integer> stack;**
You have 2 open braces
public class TSPNearestNeighbour { {
remove one and may be you get your code compiled