Trouble Determining End Game [closed] - java

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
I am trying to check to see if a player can no longer make moves but i cant seem to figure out how to check for it.
Say i have 5 tiles or less and each tile has a value between 1 and 3 on it. I want to run through the tiles and check if there are any possible combinations that will add up to 10. Its not as simple as just checking the total because there could be 3 tile with 3's on them and one with a 2. I have spent hours trying to figure this out....
Any ideas on how i could check for all possible combinations? I only need to see if one combination is possible. As soon as one is found i would break the loop to reduce the number of checks.
Edit: If it helps you can kinda see what im talking about if you download it. Its Numero: 21 on the android.
The object of the game is to add tiles to 21. So when the user gets down to a few tiles, sometimes a combination of 21 cant be acheived even when the total of all the tiles is above 21 because the numbers dont add up to exactly 21. This creates a problem because i am unable to check for that and tell the user that they have lost.
I really dont even know where to begin when it comes to checking for it. i can loop through all the tiles multiple times but the thhing is a combination could be as many tiles are on the board. So i have to check for combinations of 3, then 4 , then 5 and so on until the number of tiles left is reached. Its kind of hard for me to explain this exactly
Corrective Edit For Future Reference:
I apologize for my initial question for being so ambiguous. Happened to be the first question I ever asked on here... This is a much better description of the problem and the solution. I decided to keep the previous text for record.
The game has numerous numbered tile and I you have to add them up to 21 to remove. You can not go over 21. It has to be exact.
What I was wanting to check is if there was still a combination of tiles that could be used to add up to 21 exactly. A basic sum check doesn't work because you could have 5 number 5 tiles and be more than 21 but not possible to eliminate anymore.
Solution
As #mellamokb answered subset sum recursion needed to be used. Basically you loop through the tiles and on each tile you call the same function twice. One call adds the current tile and the other continues to the next iteration without adding the current tile. If any return true then the function is true. Basically a binary tree.
Code
boolean validate(tiles, index, subtotal, total){
if index >= tiles.length return false;
if subtotal == total return true;
return validate(tiles, index + 1, subtotal + tiles[index].number, total) ||
validate(tiles, index + 1, subtotal, total);
}
Call it with
validate(tiles, 0, 0, 21)
That about does it.

This sounds like a variation of the subset sum problem. The simplest algorithm is O(2^n), iterating over every possible subset combination by using bit flags, for example.
for i = 0 to 2^n - 1
set subtotal = 0
for each bit in i
if bit i is set, add ith element to subtotal
check subtotal against desired total (i.e., 10)
Or, alternatively using recursion:
validate(set, index, subtotal, total)
if index >= set.length return false;
if subtotal == total return true;
return validate(set, index + 1, subtotal + set[index], total) ||
validate(set, index + 1, subtotal, total);
Usage:
validate(set, 0, 0, 10);

Related

can't find error my sollution to makeBricks problem java

I found a simple Java exercise and I answered it, yet there seems to be an issue with my code and I can't seem find the problem. Please point me towards the issue:
The problem is:
We want to make a row of bricks that is goal inches long. We have a number of small bricks (1 inch each) and big bricks (5 inches each). Return true if it is possible to make the goal by choosing from the given bricks. This is a little harder than it looks and can be done without any loops.
And I made this function as answer:
public boolean makeBricks(int small, int big, int goal) {
if (small>=goal) return true;
if ((goal>=5) && (big>=1)){ makeBricks(small,big-1,goal-5);}
return false;
}
Yet when running it on https://codingbat.com/prob/p183562 it says that it's wrong and it all looks correct to me.
Adding a return statement fixes your technical problem of being unable to determine the truth value of calls further down the stack, but that's a linear solution to a problem that can be solved in constant time with basic math:
public boolean makeBricks(int small, int big, int goal) {
return big * 5 + small >= goal && goal % 5 <= small;
}
The idea here is to first determine if all of our bricks combined meets or exceeds the goal: big * 5 + small >= goal. If we can't satisfy this equation, we're definitely out of luck.
However, this is overly optimistic and does not account for cases when we have sufficient blocks to exceed the goal but not enough small blocks to remove some number of larger blocks and meet the goal. Testing goal % 5 <= small ensures that we have enough small blocks to bridge the gap of 5 that will be left as each large block is removed.
If that's still not clear, let's examine an edge case: makeBricks(3, 2, 9). Our goal is 9 and we have 3 small blocks and 2 large ones. Combining our entire arsenal gives a total of 13, which seems sufficient to meet the goal. However, if we omit one of our large blocks, the closest we can get is 8. If we omit all of our small blocks, the closest we can get is 10. No matter what we do, the goal is one block out of reach.
Let's check that against our formula: 9 mod 5 == 4, which is 1 more than our number of small blocks, 3, and matches our hand computation. We should return false on this input. On the other hand, if we had 1 extra small block, 9 % 5 == small would be true, and we'd have just enough blocks to bridge the gap.
Put a return in front of your recursive call:
return makeBricks(small,big-1,goal-5);

Find all combinations of Chess game [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I am making a program that is calculating the number of possible solutions of a chess game with only bishops and queens. The user can put in the maximal number of queens and bishops, as well as the size of the chess board.
I will call any set of positions for the bishops and the queens on the board a combination. A combination counts as a solution if all squares are attacked.
So for example, if the user wants to calculate the possible number of solutions with 2 queens and 1 bishop on a 3x3 chess board, two of the solutions could be:
B-- ---
-Q- -Q-
--- ---
And if the user chooses 9 queens instead of 2:
QQQ BQQ
QQQ QQQ
QQQ QQQ
I have managed to create an algorithm to check if a combination is a valid solution. The problem I got is the algorithm to find all the possible combinations there is. So what I need is an algorithm that loops through all possible combinations, and for each one check if the combination is a valid solution. I think a recursive solution would be the best for this.
There might be some smart way to solve this much faster, but I will sketch how to do a brute force using recursion. If you have a board with n squares in total, and your solution checking algorithm runs in F(n), this solution will be O(F(n)*3^n) - not very fast for larger boards in other words.
For a normal 8 by 8 chess board with many pieces this might be completely useless, since you run into the wheat and chessboard problem, only worse since your solution checker is expensive and it grows by the power of 3, not the power of 2. If you have fewer pieces, the problem is somewhat mitigated by the fact that you can stop branching once all the pieces are placed.
I will assume your solution checking function is named cheack_solution that takes a two dimensional array with the board, and returns a boolean (true if the board is a solution, otherwise false).
//Just to start it off.
int count_solutions(max_queens, max_bishops, a, b) {
int[][] board= new int[a][b];
return recurse(board, 0, a*b, max_queens, max_bishops, 0, 0);
}
//This is where the actual work is done.
//board is the board so far, represented by a two dimensional array where
// -1 = Queen
// 0 = Empty
// 1 = Bishop
//i is the square we are currently on, and n is the total number of board.
//max_queens and max_bishops are the maximum allowed to place.
//queens and bishops are the number placed so far.
int recurse(board, i, n, max_queens, max_bishops, queens, bishops) {
if(i == n || (max_queens == queens && max_bishops == bishops)) {
//If we have placed all the pieces, it is time to check if it is a solution.
//Return one if it is, otherwise zero.
return (int) sheck_solution(board);
}
//We havent placed all the pieces yet. Time to do some recursion.
//Get the two dimensional x and y coordinates for the one dimensional coordinate i.
x = i / board.length;
y = i % board.length);
//Number of solutions = the sum of number of solutions for the alternatives.
int solutions = 0;
//Place a queen in the current spot.
if(queens < max_queens) {
board[x][y] = -1;
solutions += recurse(board, i+1, n, max_queens, max_bishops, queens + 1, bishops);
}
//Place a bishop in the current spot.
if(bishops < max_bishops) {
board[x][y] = 1;
solutions += recurse(board, i+1, n, max_queens, max_bishops, queens, bishops + 1);
}
//Place nothing in the current spot.
board[x][y] = 0;
solutions += recurse(board, i+1, n, max_queens, max_bishops, queens, bishops);
return solutions;
}
I have not tried this, and my Java is a bit rusty, so don't expect this to run at the first try. You will need some debugging. I think the logic behind it should be allright, though.
EDIT: As requested in comments, I will try to explain why this works. You can imagine all possible board states as a tree. First there are three branches, one for each alternative (queen, bishop, empty) for the first square. Each of those three branches has three branches for the second square, and each of those three branches has three branches for the third square and so on.
The recursion traverse all these branches, since every time the function is called it calls itself three times. However the two if statements limits the traversion so that when the maximum number for a type of piece is reached, it does not try to place more of that piece.
So why do we need to put the "leave empty" option last of the three options? That is because all the function calls uses the same board array. It is not copied. Therefore when the function exit it must leave the board in the same state as it recieved it. Since there was nothing in square i when the function was called, there should be nothing in square i when the function returns.

Quiz algorithm - harder to get q answered correct / easier to get q answered wrong

I am programming a quiz, that serves the user a question, he then has to answer.
If the user answers correct, there should be less chance for getting the same question,
If the answer is wrong, there should be a bigger chance for getting the same question again, then there is for getting a normal question.
My solution has been to create 5 arrays containing the questions, and then move the questions around and serve them like this:
int rand = random.nextInt(100);
if (rand < 5) {
// Question answered correct 2 times - 5 % chance
} else if (rand > 4 && rand < 15) {
// Question answered correct 1 time - 10 % chance
} else if (rand > 14 && rand < 35) {
// Normal question - 20 % chance
} else if (rand > 34 && rand < 65) {
// Answered wrong 1 time - 30 % chance
} else if (rand > 64 && rand < 100) {
// Answered wrong 2 times - 35 % chance
}
But lets say I answer a question correct 1 or 2 times, there is too big a chance of getting that exact same question again, until there there are more questions that has been answered correct.
The way I have tried to fix this problem is to only generate random numbers from 15 to 100, until there has been answered correct to 100 questions.
It seems to me, that this could be implemented way better, but can't come up with a solution.
Any idea to how I could improve this?
I would implement it more like this:
You make a float array with one entry per question, that indicates the factor of how often the question is asked. Initially, all questions have a factor of 1. The trick is to lower the factor when an answer has been answered correctly. For instance, you could halve it.
To pick a question to ask, you sum up all factors in the array (if you have 250 questions, it'll initially sum to 250 but the sum will become different when the factors change) and take a random number between 0 and the sum. Let's say that this random number becomes 110.5. Then you compute the cumulative sum of the factors until they sum up to 110.5. This means, go over the array and sum up all factors, but when the sum becomes more than the random number you stop and take the question where the iteration was at at that point. For questions with a lower factor, you'll have a lower chance of hitting them. If all questions have a lower factor, the chance evens out again.
This way, you can arbitrarily increase or decrease the chance to get a question (for instance, halve the factor when the user gets a question right, and double it when he gets it wrong). Or you could, as in the current system, just set the factor to 0.5 when he gets it right once, 0.25 when he gets it right twice, 1.5 when he gets it wrong once, and 1.75 when he gets it wrong twice.
I guess you are holding all the correct answers in a list or something - why don't you just put an extra condition in the first two ifs regarding the size of this list.

Java: Finding consecutive numbers within a generated file [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 9 years ago.
So, I have created a program that runs in two parts. Firstly, I generate a list of 500 random numbers and store them in a text file. Secondly, I am required to find the max, min, average, etc. However, I am also supposed to find how many consecutive numbers come up. This is where my problem lies. I am not sure how to approach it.
Looking for a place to start.
Thank you
As you go along the array you will keep the list of the following things: current largest seen element, current smallest seen, total of all elements seen so far, ..., the last element seen & total count of consecutive numbers. If current number == last element seen + 1, you increase the consecutive count. There should also be a flag for the first element in the consecutive sequence, so that, say, {1, 2} counted 2 occurrences instead of one
last_seen = -1
previous_consecutive = false
for(x in numbers_list):
if x == last_seen + 1:
if not previous_consecutive:
number_of_consecutive_elements += 1
number_of_consecutive_elements += 1
previous_consecutive = true
else:
previous_consecutive = false
last_seen = x

How do I write a Java program that calculates the factors of a number? [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
I need help thinking up a formula for finding the factors of a number:
Write a method named printFactors that accepts an integer as its
parameter and uses a fencepost loop to print the factors of that
number, separated by the word " and ". For example, the number 24's
factors should print as:
1 and 2 and 3 and 4 and 6 and 8 and 12 and 24
You may assume that the number parameter's value is greater than 0.
Please don't give me a COMPLETE program as I would like to try it out myself.
The current code I have has a for loop to control the number of "and's" appearing, however, I printed out the last number by itself since I don't want a "24 and" attached to it...
So the output looks something like this at the moment:
"1 and 2 and 3" (I haven't yet thought up the equation hence the 1,2,3...)
I'm currently thinking that the factors requires a % kind of formula right? Will I need division? I was also thinking of printing out 1 and whatever the number (in this case, 24) you are finding factors for, since 1 and the number itself are always factors of itself.
What else am I missing??
Thanks in advance!! :)
I'm currently thinking that the factors requires a % kind of formula right?
Yes.
I was also thinking of printing out 1 and whatever the number (in this case, 24) you are finding factors for, since 1 and the number itself are always factors of itself.
If you test every number from 1 to n (e.g. from 1 to 24) then 1 and the number itself don't need to be special cases (because they'll simply satisfy your ordinary "% kind of formula").
Maybe 1 is a special case because it doesn't have the word "and" in front of it.
What else am I missing??
This may be more complicated than you want, but to find all the factors of n you only need to loop up to the square root of n.

Categories