Betting and Search for uniqueness - java

I've been working ahead in my intro class and I've almost finished my last project, Keno. its a betting game that rewards money according to how many numbers you matched with the dealer. I'm having issues on where to put the betting aspect, they start with 100$ and are asked to wage a certain amount of money. I don't know which method that would go under for it to still work because my methods aren't voids, so i wont be able to return more than one data value.
My second issue, maybe the more important one, is that they need to be unique numbers. To do that i would need to search the array of numbers every time to see if they match, or use an array of booleans to keep track of the numbers. I don't know how i would do the second but i have a good idea of what i would do with the first. The issue is that im using a do while already, im not sure how i could add the for loop with a nested for loop in. Here is my code, sorry if its messy, i know my teacher hates my curly braces:
package Keno;
import cs1.Keyboard;
public class Keno {
public static void main(String[]args){
int userArr[]=user();
int compArr[]=computer();
int howMany=matchNums(compArr,userArr);
int moneyGained=betting(howMany);
System.out.println("You matched "+howMany+" numbers");
System.out.println("You have gained "+moneyGained+" dollars!");
}
public static int[] computer(){
int []compChoice=new int[20];
for(int x=0;x<compChoice.length;x++){
compChoice[x]=(int)(Math.random()*81);
}
return compChoice;
}
public static int[] user(){
int choice[]=new int[7];
System.out.println("Welcome to Keno!");
System.out.println("Choose 7 unique numbers ranging from 1-80");
System.out.println("*************************************************");
//assigns numbers to choice array
for(int x=0;x<choice.length;x++){
do{
int temp=x+1;
System.out.println("number "+temp+": ");
choice[x]=Keyboard.readInt();
}while(choice[x]<0||choice[x]>80);
}
System.out.println("Thanks!");
System.out.println("*************************************************");
return choice;
}
public static int matchNums(int arr1[], int arr2[]){
int count=0;
//checks each array slot individually to see if they match
for(int x=0;x<arr1.length;x++){
for(int y=0;y<arr2.length;y++){
if(arr1[x]==arr2[y]){
count++;
}
}
}
return count;
}
public static int betting(int matches){
int moneyGained=0;
if(matches==7){
moneyGained=12000;
}else if(matches==6){
moneyGained=200;
}else if(matches==5){
moneyGained=20;
}else if(moneyGained==4){
moneyGained=1;
}
return moneyGained;
}
}

The simplest way to add the betting/money concept would be to add an integer which represents how much money the player has (starting at 100). You will have to ask the player how much they want to wager, and then adjust their money accordingly.
public static void main(String[] args) {
int playerMoney = 100;
int wagered = getWager(); // dont forget it has to be 0 < wagered <= 100
// adjust players money according to the wager, and how much they won
For ensuring uniqueness, either one of your ideas would work. I like just checking for the numbers existence already in the array, but the boolean array of size 80 would work too. It just seems like a lot for only 7 numbers though.

Related

Shortest path in Rat in a Maze with option to remove one wall

This is the problem:
You have maps of parts of the space station, each starting at a prison exit and ending at the door to an escape pod. The map is represented as a matrix of 0s and 1s, where 0s are passable space and 1s are impassable walls. The door out of the prison is at the top left (0,0) and the door into an escape pod is at the bottom right (w-1,h-1).
Write a function answer(map) that generates the length of the shortest path from the prison door to the escape pod, where you are allowed to remove one wall as part of your remodeling plans. The path length is the total number of nodes you pass through, counting both the entrance and exit nodes. The starting and ending positions are always passable (0). The map will always be solvable, though you may or may not need to remove a wall. The height and width of the map can be from 2 to 20. Moves can only be made in cardinal directions; no diagonal moves are allowed.
To Summarize the problem: It is a simple rat in a maze problem with rat starting at (0,0) in matrix and should reach (w-1,h-1). Maze is a matrix of 0s and 1s. 0 means path and 1 means wall.You have the ability to remove one wall(change it from 0 to 1). Find the shortest path.
I've solved the problem but 3 of 5 testcases fail and I don't know what those test cases are. and I'm unable to figure out why. Any help would be greatly appreciated.Thanks in Advance. Here is my code:
import java.util.*;
class Maze{//Each cell in matrix will be this object
Maze(int i,int j){
this.flag=false;
this.distance=0;
this.x=i;
this.y=j;
}
boolean flag;
int distance;
int x;
int y;
}
class Google4_v2{
public static boolean isPresent(int x,int y,int r,int c)
{
if((x>=0&&x<r)&&(y>=0&&y<c))
return true;
else
return false;
}
public static int solveMaze(int[][] m,int x,int y,int loop)
{
int r=m.length;
int c=m[0].length;
int result=r*c;
int min=r*c;
Maze[][] maze=new Maze[r][c];//Array of objects
for(int i=0;i<r;i++)
{
for(int j=0;j<c;j++)
{
maze[i][j]=new Maze(i,j);
}
}
Queue<Maze> q=new LinkedList<Maze>();
Maze start=maze[x][y];
Maze[][] spare=new Maze[r][c];
q.add(start);//Adding source to queue
int i=start.x,j=start.y;
while(!q.isEmpty())
{
Maze temp=q.remove();
i=temp.x;j=temp.y;
int d=temp.distance;//distance of a cell from source
if(i==r-1 &&j==c-1)
{
result=maze[i][j].distance+1;
break;
}
maze[i][j].flag=true;
if(isPresent(i+1,j,r,c)&&maze[i+1][j].flag!=true)//check down of current cell
{
if(m[i+1][j]==0)//if there is path, add it to queue
{
maze[i+1][j].distance+=1+d;
q.add(maze[i+1][j]);
}
if(m[i+1][j]==1 && maze[i+1][j].flag==false && loop==0)//if there is no path, see if breaking the wall gives a path.
{
int test=solveMaze(m,i+1,j,1);
if(test>0)
{
test+=d+1;
min=(test<min)?test:min;
}
maze[i+1][j].flag=true;
}
}
if(isPresent(i,j+1,r,c)&&maze[i][j+1].flag!=true)//check right of current cell
{
if(m[i][j+1]==0)
{
maze[i][j+1].distance+=1+d;
q.add(maze[i][j+1]);
}
if(m[i][j+1]==1 && maze[i][j+1].flag==false && loop==0)
{
int test=solveMaze(m,i,j+1,1);
if(test>0)
{
test+=d+1;
min=(test<min)?test:min;
}
maze[i][j+1].flag=true;
}
}
if(isPresent(i-1,j,r,c)&&maze[i-1][j].flag!=true)//check up of current cell
{
if(m[i-1][j]==0)
{
maze[i-1][j].distance+=1+d;
q.add(maze[i-1][j]);
}
if(m[i-1][j]==1 && maze[i-1][j].flag==false && loop==0)
{
int test=solveMaze(m,i-1,j,1);
if(test>0)
{
test+=d+1;
min=(test<min)?test:min;
}
maze[i-1][j].flag=true;
}
}
if(isPresent(i,j-1,r,c)&&maze[i][j-1].flag!=true)//check left of current cell
{
if(m[i][j-1]==0)
{
maze[i][j-1].distance+=1+d;
q.add(maze[i][j-1]);
}
if(m[i][j-1]==1 && maze[i][j-1].flag==false && loop==0)
{
int test=solveMaze(m,i,j-1,1);
if(test>0)
{
test+=d+1;
min=(test<min)?test:min;
}
maze[i][j-1].flag=true;
}
}
}
return ((result<min)?result:min);
}
public static int answer(int[][] m)
{
int count;
int r=m.length;
int c=m[0].length;
count=solveMaze(m,0,0,0);
return count;
}
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
System.out.println("enter row size ");
int m=sc.nextInt();
System.out.println("enter column size ");
int n=sc.nextInt();
int[][] maze=new int[m][n];
System.out.println("Please enter values for maze");
for(int i=0;i<m;i++)
{
for(int j=0;j<n;j++)
{
maze[i][j]=sc.nextInt();
}
}
int d=answer(maze);
System.out.println("The maze can be solved in "+d+" steps");
}
}
Found the problem. maze[i][j].flag=true; needs to be put as soon as the cell is visited, inside the if(m[i+1][j]==0) condition. Otherwise, the distance for same cell can be added by more than one cells
Unfortunately it's quite hard to help you because your code is very difficult to read. The variables are generally single characters which makes it impossible to know what they are supposed to represent. Debugging it would be more help than most of us are willing to give :-)
I suggest you go about debugging your code as follows:
Split your solveMaze method into a number of smaller methods that each perform much simpler functions. For example, you have very similar code repeated 4 times for each direction. Work to get that code in a single method which can be called 4 times. Move your code to create the array into a new method. Basically each method should do one simple thing. This approach makes it much easier to find problems when they arise.
Write unit tests to ensure each of those methods do exactly what you expect before attempting to calculate the answer for entire mazes.
Once all the methods are working correctly, generate some mazes starting from very simple cases to very complex cases.
When a case fails, use an interactive debugger to walk through your code and see where it is going wrong.
Good luck.

Need help Spotting A logic error in my program (prime numbers) / understanding output

New to programming.
Before you comment: I understand that their are more efficient ways to do this, and already have. I just feel that understanding the process here will make me a better programmer.
Following pseudo code I saw in class. I wrote a program that takes a integer and prints every prime number up to and including the integer(userinput).
This is what I came up with:
//Import Scanner.
import java.util.Scanner;
//Create class.
public class QuestionTwoA2
{
public static void main(String[] args)
{
System.out.println("Enter an integer:"); //Ask for user input.
int userInteger; //Create scanner object and collect user input.
Scanner keyboard = new Scanner(System.in);
userInteger = keyboard.nextInt();
boolean primeFlag = true; //Condition required for prime number loop.
int outer; //I localised these variables outside the loop so that I
int inner; //could test output by printing it.
//Checks natural numbers in between 2 and userInteger.
for (outer = 2; outer < userInteger; outer++)
{
for (inner = 2; inner < outer; inner++)
{
if (outer % inner == 0)
{
primeFlag = false;
//System.out.println(outer + " " + inner);
break;
}
}
if (primeFlag) //I think this statement causes a logic problem.
System.out.println(outer);
}
}
}
I have/had print statements in various parts of my code just to visualise what values I am comparing to get a remainder. My current output is (for any integer input):
Enter an integer:
9
2
3
Logically my code looks fine but obviously doesn't work, help explaining what is actually going on would be much appreciated.
You should put "boolean primeFlag = true;" inside the first for and before the second for.
Since second for is for detecting whether the "outer" variable is a prime number or not, so before going into that you should set your flag true which is your assumption at first, and in second loop when you are checking all smaller values to see whether it is actually prime or not and change the flag if not.

Breaking out" of a while loop still executing whats inside?

The purpose of this program is to take in positive integers and once the sentinel value (-1) is hit the program will return the 2 lowest numbers. My program works, but in some scenarios it doesn't. for example if I enter 10,15,20,-1 the program will result in 10 rather than 10 and 15. Here is my program:
public class Small{
public static void main(String [ ] args){
int number;
number=IO.readInt();
int lowest=number;
int lowest2=number;
while (number!=-1){
number=IO.readInt();
if(number>0){
if(number<lowest && number!=-1){
lowest=number;}
else{if((number<lowest2||!(number>=lowest2))&& number!=-1){
lowest2=number;}
}
}
}
IO.outputIntAnswer(lowest);
IO.outputIntAnswer(lowest2);
}
}
The main problem with your code is that you set lowest and lowest2 to the first value you enter. If all the other numbers you enter are higher than the first number, it will never be able to find anything lower.
With your example, the first number is 10 which you assign to lowest and lowest2. When you enter 15, it's not lower than 10, so neither variable can be reset. Same with 20.
You've also got a lot of redundant checks in your if-statements.
public class Small {
public static void main(String [ ] args) {
int number;
int lowest = Integer.MAX_VALUE;
int lowest2 = Integer.MAX_VALUE;
while (number!=-1) {
number=IO.readInt();
if (number > 0) {
if(number < lowest) {
lowest=number;
}
else if (number < lowest2) {
lowest2=number;
}
}
}
}
IO.outputIntAnswer(lowest);
IO.outputIntAnswer(lowest2);
}
The problem is with your logic flow of the program. Here's what the code is doing:
Read in one number, store in both lowest and lowest2.
Go through loop to read in more numbers
2a. If the number is positive, check against lowest.
2a1. If the read in value is lower than lowest, change lowest's value to the read in value.
2a2. Otherwise, if the read in value is lower than lowest2, change lowest2's value to the read in value. Only do this if lowest was not changed.
2b. If the read in value is -1, end the loop.
2c. If the read in value is negative but not -1, continue but don't add the number to lowest or lowest2.
Print out the values for lowest and lowest2.
If you see the error, it's in 2a2. This is linked to the fact that your setup before the while loop is formatted as you did: you made both lowest and lowest2 that first value.
This code would normally run correctly, except for one instance: what if that first value were to be the smallest positive value you entered, with all other values greater than it? lowest2 would be set to that value, and you're checking to see if any other values are smaller than it (which they're not, because they're all going to be greater than it).
Tips for when you're coding:
1) Attempt to develop a logical thinking mentality. Think through how you want to create algorithms for your program. Make sure you don't run into any situations where your program does not run the way you want it to, like in this case (this is called a logic error).
2) Run through your programs by hand when you're finished coding, or after you've run it and got an error. Step through every line of your code, and try to see where and why your code isn't working the way you want it to. Or have someone else see, like a fellow programmer. Sometimes, even the best eyes do not catch their own mistakes.
EDIT:
There are various ways to solve this particular problem. One way is to do what Seeker and Rick did:
1) Set both values to the largest possible Integer value, and thus all values entered will be lower than the first values.
2) Ask for the first two inputs at the beginning before the loop, and check them against each other to set the first two lowest values.
However, I believe there are certain things to watch out for when you're doing something like this. These should all be outlined before you code, of course.
1) What if the user is entering only one or zero valid values? Seeker's method wouldn't work, unless he checks that the first/second value is negative/-1. Rick's method wouldn't work either because at least one of the lowest/lowest2 values would still be that max Integer value.
2) What if there were no positive values entered before the -1? This is similar to number 1, and your ints would be null.
You can certainly use Seeker's and Rick's algorithms, but you should check for these conditions if you use them.
import java.util.Scanner;
public class Small {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter Number");
int lowest = scanner.nextInt();
System.out.println("Enter Number");
int lowest2 = scanner.nextInt();
if (lowest > lowest2) {
int t = lowest;
lowest = lowest2;
lowest2 = t;
}
while (true) {
System.out.println("Enter Number");
int number = scanner.nextInt();
if (number == -1)
break;
if (number < lowest2 && number < lowest) {
lowest = number;
} else if (number < lowest2) {
lowest2 = number;
}
}
System.out.println("lowest:" + lowest);
System.out.println("lowest2:" + lowest2);
scanner.close();
}
}

Game of dice in java

The requirements of the program are:
Antonia and David are playing a game.
Each player starts with 100 points.
The game uses standard six-sided dice and is played in rounds. During one round, each player rolls one die. The player with the lower roll loses the number of points shown on the higher die. If both players roll the same number, no points are lost by either player.
Write a program to determine the final scores.
I came up with the following code:
import java.util.*;
public class prob3
{
public static void main(String[]args)
{
Random g=new Random();
int a,b,c;
int rounds;
int antonio=100;
int david=100;
Scanner s=new Scanner(System.in);
System.out.println("Please enter the no. of rounds you want to play(1-15): ");
rounds=s.nextInt();
for(int d=1;d<=rounds;d++)
{
a=g.nextInt(6)+1;
b=g.nextInt(6)+1;
System.out.println("Round "+d+":"+a+" "+b);
if(a<b)
antonio=100-b;
else if(a>b)
david=100-a;
}
System.out.println("Total for Antonio: "+antonio);
System.out.println("Total for David: "+david);
}
}
The program fails to calculate the right sum at the end.
What am I doing wrong?
Any help would be appreciated.
Thanks.
You are doing this.
antonio=100-b;
When you probably want
antonio = antonio - b;
The first code simply subtracts the dice roll from 100 every time, which is pointless. You want to subtract the dice roll from the players totals. Do this for both players.
As stated above the "100 - b" was your main problem. But there is no reason in your problem statement to set a number of rounds.
I whould rather use a loop like this:
while(antonio >= 0 && david >= 0){
//do the same stuff here
}
System.out.println...
Since it looks as some exercise for some java course.. This may sound useless but:
Format always your code.. Spaces, brakets and tabs
Use descriptive variable mames. a b c d are not quite intuitive in a larger program.
Remover unused variables
Y mucha suerte tío!

Quick Sort Java

Hi I'm currently working on getting my Quick Sort program working but cannot figure out where I'm going wrong, i have spent hours trying to find out why it's not working but no luck,when I run my code nothing happens. I have four other sorting algorithms working in a similar fashion which is what's confusing me the most.
Below is my code for the Quick Sort program
import java.io.IOException;
public class QuickSort {
public static int[] compute(int[] array, int lower, int higher )throws IOException{
if(lower<higher){
int pivot=split(array,lower,higher);
if(pivot>1)
compute(array, lower, pivot-1);
if(pivot+1<higher)
compute(array, pivot+1, higher);
}
return array;
}
public static int split(int[] array, int lower, int higher){
while(true){
int pivot=array[lower];
while(array[lower]<pivot)
lower++;
while(array[higher]>pivot)
higher--;
if(lower<higher){
int temp=array[higher];
array[higher]=array[lower];
array[lower]=temp;
}
else{
return higher;
}
}
}
}
Here is my Test class that's running the code:
import java.io.IOException;
import java.util.Scanner;
public class Test extends ReadIn{
static BubbleSort bubble=new BubbleSort();
public static void main(String[] args) throws IOException{
System.out.println("Enter 1 for BubbleSort\nEnter 2 for Insertion Sort\nEnter 3 for Selection Sort\nEnter 4 for Merge Sort\nEnter 5 for QuickSort\nPlease input sorting algorithm to use for sorting:");
Scanner input=new Scanner(System.in);
int number=input.nextInt();
final long startTime = System.currentTimeMillis();
int[] Array=read();
if(number==1){
Array=BubbleSort.compute(Array);
for(int i=0;i<BubbleSort.compute(Array).length;i++){
System.out.println(Array[i]);
}
}
if(number==2){
Array=InsertionSort.compute(Array);
for(int i=0;i<InsertionSort.compute(Array).length;i++){
System.out.println(Array[i]);
}
}
if(number==3){
Array=SelectionSort.compute(Array);
for(int i=0;i<SelectionSort.compute(Array).length;i++){
System.out.println(Array[i]);
}
}
if(number==4){
Array=MergeSort.compute(Array);
for(int i=0;i<MergeSort.compute(Array).length;i++){
System.out.println(Array[i]);
}
}
if(number==5){
Array=QuickSort.compute(Array,0,Array.length-1);
for(int i=0;i<QuickSort.compute(Array,0,Array.length-1).length;i++){
System.out.print(Array[i]);
}
}
final long endTime = System.currentTimeMillis();
System.out.println("Total execution time: " + (endTime - startTime) );
}
}
When I press 5 nothing happens, the rest work perfectly.
I cant figure out whatsoever what the problem is so any help or input would be appreciated.
Your Quicksort code loops forever if there's duplicate numbers in the input, since the numbers can just keep swapping with each other. As mentioned in the comment, you should manually try out your code with a sample array, or check the code running with a debugger. See the example array below.
You might want to switch the while(true) loop to a recursive call to make the code a little clearer. Also, you can practice going through the different steps of Quicksort on my Quicksort online tutorial.
Say the array = {3,1,2,3} and the pivot is 3. Nothing will change and the code will loop forever.
while(true){
int pivot=array[lower];
while(array[lower]<pivot)
lower++;
while(array[higher]>pivot)
higher--;
if(lower<higher){ //this will just swap the 3's with each other.
int temp=array[higher];
array[higher]=array[lower];
array[lower]=temp;
}
else{
return higher;
}
}
While it looks like your program is doing nothing, it probably just loops infinitely inside this loop:
while(true){
int pivot=array[lower];
while(array[lower]<pivot)
lower++;
while(array[higher]>pivot)
higher--;
if(lower<higher){
int temp=array[higher];
array[higher]=array[lower];
array[lower]=temp;
// I recommend adding this line for you to see what's going on
System.out.println("lower="+lower+", higher="+higher+", pivot="+pivot);
}
else{
return higher;
}
}
for example, if you have equal values in your Array, say value 65 is there twice, that loop will run forever...
int[] Array={1,41,2,90,32,65,12,43,78,65,46,67};
Also, in your loop above I added and extra printout of higher, lower, and pivot values - it will help you see what is happening inside that devious loop.
In general writing a while(true) loop is not a good practice, because it's so easy to hang your system on it.

Categories

Resources