Math twenty four game Java [duplicate] - java

This question already has answers here:
Building a math game in Java
(3 answers)
Closed 8 years ago.
The 24 Game is an arithmetical game in which the objective is to find a way to manipulate four integers so that the end result is 24. Addition, subtraction, multiplication, or division in any order of the numbers may be used to make the four digits operations from one to nine equal 24.
The rules are simple: you have to use each number only once and only the 4 numbers that were read from the user to find one equation to obtain 24.
For example, for the numbers 4,7,8,8, a possible solution is: (7-(8/8))*4=24.
Most sets of 4 digits can be used in multiple equations that result in 24: for example the input: 2, 2, 4 and 7 can be used in multiple ways to obtain 24:
2+2*(4+7) = 24
2+2*(7+4) = 24
(2+2)*7-4 = 24
(2*2)*7-4 = 24
2*(2*7)-4 = 24
There are also combinations of 4 numbers that cannot result into any equation equal with 24. For example 1,1,1,1. In this case, your program should return that there is no possible equation equal with 24.
Note: Although we will enter 4 integers between 1 and 9, we will use doubles to compute all the operations. For example, the numbers 3,3,8,8 can be combined into the formula: 8/(3-8/3) = 24.
Workflow: Your program should read the 4 numbers from the user and output a formula that results in 24. The algorithm should enumerate all the possible orders of 4 numbers, all the possible combinations and all the possible formulas. There is no required GUI for this project I need help with a method that will shuffle the operators for all 64 possible combos so 4 operators and 3 being used in each equation and also account for parenthesis during the equations . I have no idea where to begin.

If you can generate permutations of a string. You need to do that for all the numbers to get all the permutations possible for those numbers.
Now you just need to plugin permutations of operators (3 at a time).
For that you can generate all the permutations of the operators and store them in an array, as that would remain constant for each case. And out of each permutation generated, just pick the first 3 characters as we are looking at groups of 3 out of the 4 possible.
Once you have that, it's simply a matter of reading a permutation of the numbers and then reading a permutation of operators and evaluating the expression.
For reference, I have made a simple demo of a function that finds permutations of a string in Java. The recursive function looks something like (from a relevant SO Post):
public void permut(String str1,String str2){
if(str2.length() != 0){
char ch = str2.charAt(0);
for(int i = 0; i <= str1.length();i++)
permut(str1.substring(0,i) + ch + str1.substring(i,str1.length()),
str2.substring(1,str2.length()));
}else{
System.out.println(str1);
}
}
If you can successfully generate all permutations of a string, the above exercise should be doable. I hope it gets you started in the right direction.

Related

Finding Repeating part of fraction (a/b) and print only repeating integers as String in java? [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 1 year ago.
Improve this question
I'm solving a problem of fraction,
if the fraction part is repeating, print the only repeating integers as String.
if the fraction part is not repeating, print upto 4 digits after decimal.
if the fraction output is simple print it directly as string.
E.g.
a) 1/3 = 0.3333... , here 3 is recurring, so need to print only 0.3.
b) 5/2 = 2.5 -- Simple Math.
c) 22/7 = 3.14287, here 14287 is repeating, so need to print 3.14287
Can you please help, the solution should have O(k) time complexity and space complexity
public String fractionToDecimal(int numerator, int denominator) {
StringBuilder tem = new StringBuilder();
long q = numerator / denominator;
return tem.append(q);
}
This question is quite complicated. You need to know quite a few advanced concepts to fully understand why it is so.
Binary vs. Decimal
The notion '1 divided by 3 repeats the 3 endlessly' only works if you presuppose a decimal rendering system. Think about it: Why does '10' come after '9'? As in, why did 'we' decide not to have a specific symbol for the notion 'ten', and instead this is the exact point on the number line 'we' decided to go for two digits, the first digit and the zero digit written next to each other? That's an arbitrary choice, and if you delve into history, humans made this choice because we have 10 fingers. Not all humans made this choice, to be clear: Sumerians had unique digits all the way up to 60, and this explains why there are 60 seconds in a minute, for example. There are remote tribes using 6, 3, and even weirder number systems.
If you want to spend some fun math time, go down the rabbithole on wikipedia reading about exotic number systems. It's mesmering stuff, a fine way to spend an hour (or two, or ten!)
Imagine a number system for aliens that had only 3 fingers total. They'd count:
Human Alien
0 0
1 1
2 2
3 10
4 11
5 12
6 20
8 21
9 22
10 30
Their number system isn't "weird" or "bad". Just different.
However, that number concept goes both ways: When you write, say, "1 divided by 4 = 0.25", that 25 is also in 'decimal' (the name for a number system that has 10 digits, like what most humans on the planet earth like to use).
In human, 1 divided by 10 is 0.1. Easy, right?
Well, in '3-finger alien', one divided by three is... 0.1.
Not 0.1 repeating. Nono. Just 0.1. It fits perfectly. In their number system, one divided by ten is actually quite complicated, where it is ridiculously simple in ours.
Computers are aliens too. They have 2 fingers. Just 0 and 1, that's all. A computer counts: 0 1 10 11 100 101 110 111 and so on.
An a / b operation that repeats in decimal may not repeat in binary. Or it may. Or a number that doesn't repeat in decimal may repeat in binary (1/5 repeats endlessly in binary, in decimal, it's just 0.2, easy).
Given that computers don't like counting in decimal, any basic operation is an instant 'loser' - you can no longer answer the question if you even write double or float anywhere in your code here.
But it requires knowledge of binary and some fairly fundamental math to even know that.
Solution strategy 1: BigDecimal
NOTE: I don't think this is the best way to go about it, I'd go with strategy 2, but for completeness...
Java has a class baked into the core library called java.math.BigDecimal that is intended to be used when you don't want any losses. double and float are [A] binary based, so trying to use them to figure out repeating strides is completely impossible, and [B] silently round numbers all the time to the nearest representable number. You get rounding errors. Even 0.1 + 0.2 isn't quite 0.3 in double math.
For these reasons, BigDecimal exists, which is decimal, and 'perfect'.
The problem is, well, it's perfect. In basis, dividing 1 by 3 in BigDecimal math is impossible - an exception occurs. You need to understand the quite complicated API of BigDecimal to know about how to navigate this issue. You can tell BigDecimal about exactly how much precision you're okay with.
So, what you can do:
Convert your divider and dividend into BigDecimal numbers.
Configure these for 100 digits after the comma precision.
Divide one by the other.
Convert the result to a string.
Analyse the string to find the repeating stride.
That algorithm is technically still incorrect - you can have inputs that have a repetition stride that is longer than 100 characters, or a division operation that appears to have a repeating stride when it actually doesn't.
Still, for probably every combination of numbers up to 100 or so you care to throw at it, the above would work. You can also choose to go further (more than 100 digits), or to write an algorithm that tries to find a repeat stride with 100 digits, and if it fails, that it just uses a while loop to start over, ever incrementing the # of digits used until you do find that repeating stride in the input.
You'll be using many methods of BigDecimal and doing some fairly tricky operation on the resulting string to attempt to find the repetition stride properly.
It's one way to solve this problem. If you would like to try, then read this and have fun!
Solution Strategy 2: Use math
You can use a mathematical algorithm to derive the next decimal digit given a divisor and dividend. This isn't so much computer science, it's purely a mathematical exercise, and hence, don't search for 'java' or 'programming' or whatnot online when looking for this.
The basic gist is this:
1/4 becomes the number 0.25, how would one derive that? Well, had you multiplied the input by 10 first, i.e. calculate 10/4, then all you really need to do is calculate in integral math. 4 fits into 10 twice, with some left over. That's where the 2 comes from.
Then to derive the 5: Take the left-over (4 fits into 10 twice, and that leaves 2), and multiply it again by 10. Now calculate 20/4. That is 5, with nothing left over. Great, that's where the 5 comes from, and we get to conclude that there is no need to continue. It's zeroes from here on out.
You can write this algorithm in java code. Never should it ever mention double or float (you immediately fail the exercise if you do this). a / b, if both a and b are integral, does exactly what you want: Calculates how often b fits into a, tossing any remainder. You can then obtain the remainder with some more simple math:
int dividend = 1;
int divisor = 4;
List<Integer> digits = new ArrayList<>();
// you're going to have to think about when to end this loop
System.out.print("The digits are: 0.");
while (dividend != 0 && digits.size() < 100) {
dividend *= 10;
int digit = dividend / divisor;
dividend -= (digit * divisor);
digits.add(digit);
System.out.print(digit);
}
I'll leave the code you'd need to write to find repetitions to you. You can be certain it repeats 'cleanly' when your divisor number ends up being a divisor value you've seen before. For example, when doing 1/3, going through this algorithm:
First loop through:
dividend (1) is multiplied by 10, becomes 10.
dividend is now integer-divided by the divisor (3), producing the digit 3.
We determine what's left: the digit times the divisor is 9, so 9 of those 10 have been used up, leaving the 1. We set dividend to 1.
As you can see, nothing actually changed: The dividend is still 1 just like it was at the start, therefore all loops through go like this, producing an endless stream of 3 values, which is indeed the correct answer.
You can maintain a list of dividends you've already seen. e.g. by storing them in a Set<Integer>. Once you hit a number you've already seen, you can just stop printing: You've started the repetition.
This algorithm has the considerable benefit of always being correct.
So what do I do?
I think your teacher wants you to figure out the second one, and not to delve into the BigDecimal API.
This is an awesome exercise, but more about math than programming.

Finding a missing integer, given 4 billion unsorted integers [duplicate]

This question already has answers here:
Generate an integer that is not among four billion given ones
(38 answers)
Closed 8 years ago.
I came across this interview questions and I was trying to understand how to approach this problem. I read this question on SO. I understood the approach of the author of the post, however I do not understand the approach suggested in the accepted answer. So I moved to this blog. According to this blog we can calculate the number of zeroes and ones at each of the bit positions and from that we can find out the missing number. But then for that the file should have 2^32-1 numbers which is greater than 4 billion. So that method should not work right? I am sure there is something wrong in my understanding, but I just can't figure out the missing link.
If you had a "complete" sequence of numbers from 0 to 2^N-1 then the number of bits set in each bit position would be equal (and equal to (2^N)/2).
If only one number is missing, then it's 1 bits correspond to the bit positions that are short one bit count.
Note that this only works for powers of 2, but possibly one can work out more complex formulae for "odd" counts.
add the intergers up using long
subtract the result from (N+1)*(N+2)/2 where N is the number of integers in your file. The result is your missing number
Example:
file contains 1,3
sum = 4
N=2, so (N+1)(N+2)/2 = (2+1)(2+2)/2 = 6
6-sum=6-4=2
2 is your missing number

Generate N random numbers in given ranges that sum up to a given sum

first time here at Stackoverflow. I hope someone can help me with my search of an algorithm.
I need to generate N random numbers in given Ranges that sum up to a given sum!
For example: Generatare 3 Numbers that sum up to 11.
Ranges:
Value between 1 and 3.
Value between 5 and 8.
value between 3 and 7.
The Generated numbers for this examle could be: 2, 5, 4.
I already searched alot and couldnt find the solution i need.
It is possible to generate like N Numbers of a constant sum unsing modulo like this:
generate random numbers of which the sum is constant
But i couldnt get that done with ranges.
Or by generating N random values, sum them up and then divide the constant sum by the random sum and afterwards multiplying each random number with that quotient as proposed here.
Main Problem, why i cant adopt those solution is that every of my random values has different ranges and i need the values to be uniformly distributed withing the ranges (no frequency occurances at min/max for example, which happens if i cut off the values which are less/greater than min/max).
I also thought of an soultion, taking a random number (in that Example, Value 1,2 or 3), generate the value within the range (either between min/max or min and the rest of the sum, depending on which is smaller), substracting that number of my given sum, and keep that going until everything is distributed. But that would be horrible inefficiant. I could really use a way where the runtime of the algorithm is fixed.
I'm trying to get that running in Java. But that Info is not that importend, except if someone already has a solution ready. All i need is a description or and idea of an algorithm.
First, note that the problem is equivalent to:
Generate k numbers that sums to a number y, such that x_1, ..., x_k -
each has a limit.
The second can be achieved by simply reducing the lower bound from the number - so in your example, it is equivalent to:
Generate 3 numbers such that x1 <= 2; x2 <= 3; x3 <= 4; x1+x2+x3 = 2
Note that the 2nd problem can be solved in various ways, one of them is:
Generate a list with h_i repeats per element - where h_i is the limit for element i - shuffle the list, and pick the first elements.
In your example, the list is:[x1,x1,x2,x2,x2,x3,x3,x3,x3] - shuffle it and choose first two elements.
(*) Note that shuffling the list can be done using fisher-yates algorithm. (you can abort the algorithm in the middle after you passed the desired limit).
Add up the minimum values. In this case 1 + 5 + 3 = 9
11 - 9 = 2, so you have to distribute 2 between the three numbers (eg: +2,+0,+0 or +0,+1,+1).
I leave the rest for you, it's relatively easy to create a uniform distribution after this transformation.
This problem is equivalent to randomly distributing an excess of 2 over the minimum of 9 on 3 positions.
So you start with the minima (1/5/3) and then cycle 2 times, generating a (pseudo-)random value of [0-2] (3 positions) and increment the indexed value.
e.g.
Start 1/5/3
1st random=1 ... increment index 1 ... 1/6/3
2nd random=0 ... increment index 0 ... 2/6/3
2+6+3=11
Edit
Reading this a second time, I understand, this is exactly what #KarolyHorvath mentioned.

Trying all possibilities in java

I have 4 ints (a,b,c,d) and 3 Strings that represent mathematical operators (+,-,*,/).
I want to check if it's possible to make a certain number (e) from these ints and Strings.
for example:
a + b * c - d == e;
The ints can be used only once each, and the operators can be used multiple times, but only once between every 2 ints.
Can anyone help me?
First break down your problem into smaller pieces.
I would break it down as follows:
calculate all permutations of the 4 ints. There should be 4!(24) of these. (look up generating permutations)
calculate all combinations of the 3 operations that can occur. there
should be 3*3 (9) of these. (look up generating permutations with
repeats).
now that you have the order of the intergers and the order of the operations try and compute e. (interweave the combinations: ie. 1 from ints, 1 from ops, 2nd from ints, second from ops ect...) This should be done with all int permuations and all op combinations.
after evaluating all equations (216 of these) if none of them were equal to e, there is no solution.

Roman representation of integers [duplicate]

This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
How do you find a roman numeral equivalent of an integer
I am looking for a simple algorithm (preferably in Python). How to translate a given integer number to a Roman number?
string Roman(int Num){...}
For example, Roman(1981) must produce "MCMLXXXI".
I needed the opposite one time (going from Roman numerals to int). Wikipedia has surprisingly detailed information on how Roman numerals work. Once you realize that things are this well-defined and that a specification is available this easily, translating it to code is fairly trivial.
Here is a lengthy explanation how to do it with a lot of source code attached:
http://www.faqs.org/docs/javap/c9/ex-9-3-answer.html
But I think it could be done more efficient.
Check out the code at this ActiveState link. The code looks fairly well documented.
I can't think of a third party library that has this functionality. Sometimes you have to write some stuff yourself, although there are plenty of examples of how do to this online. Here is one from RoseIndia
For hundreds, tens and units the rule is pretty much the same, i.e. you have a 1, 5 and 10 character the representation will be the same for each, just that the letters change.
You could have a table of 10 entries which represents a template
0 -
1 = U
2 = UU
3 = UUU
4 = UF
5 = F
6 = FU
7 = FUU
8 = FUUU
9 = UT
Now also have for units, tens and hundreds your table:
Units = IVX
Tens = XLC
Hundreds = CDM
Apply your template for the number to the letter representation so a U is replaced by the first character, an F by the second and a T by the 3rd.
Thousands are just an M for each thousand.
Build your string starting with the thousands, then the hundreds, then the tens and then the units.
If you were building it backwards of course you could start with the units modding by 10, then construct your units string, divide by 10 and mod again and shift to the tens string, repeat with the hundreds string and when you get to the thousands string you will know it by the fact your string has just one character i.e. an M.

Categories

Resources