Trying all possibilities in java - 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.

Related

Java HashMap array size

I am reading the implementation details of Java 8 HashMap, can anyone let me know why Java HashMap initial array size is 16 specifically? What is so special about 16? And why is it the power of two always? Thanks
The reason why powers of 2 appear everywhere is because when expressing numbers in binary (as they are in circuits), certain math operations on powers of 2 are simpler and faster to perform (just think about how easy math with powers of 10 are with the decimal system we use). For example, multication is not a very efficient process in computers - circuits use a method similar to the one you use when multiplying two numbers each with multiple digits. Multiplying or dividing by a power of 2 requires the computer to just move bits to the left for multiplying or the right for dividing.
And as for why 16 for HashMap? 10 is a commonly used default for dynamically growing structures (arbitrarily chosen), and 16 is not far off - but is a power of 2.
You can do modulus very efficiently for a power of 2. n % d = n & (d-1) when d is a power of 2, and modulus is used to determine which index an item maps to in the internal array - which means it occurs very often in a Java HashMap. Modulus requires division, which is also much less efficient than using the bitwise and operator. You can convince yourself of this by reading a book on Digital Logic.
The reason why bitwise and works this way for powers of two is because every power of 2 is expressed as a single bit set to 1. Let's say that bit is t. When you subtract 1 from a power of 2, you set every bit below t to 1, and every bit above t (as well as t) to 0. Bitwise and therefore saves the values of all bits below position t from the number n (as expressed above), and sets the rest to 0.
But how does that help us? Remember that when dividing by a power of 10, you can count the number of zeroes following the 1, and take that number of digits starting from the least significant of the dividend in order to find the remainder. Example: 637989 % 1000 = 989. A similar property applies to binary numbers with only one bit set to 1, and the rest set to 0. Example: 100101 % 001000 = 000101
There's one more thing about choosing the hash & (n - 1) versus modulo and that is negative hashes. hashcode is of type int, which of course can be negative. modulo on a negative number (in Java) is negative also, while & is not.
Another reason is that you want all of the slots in the array to be equally likely to be used. Since hash() is evenly distributed over 32 bits, if the array size didn't divide into the hash space, then there would be a remainder causing lower indexes to have a slightly higher chance of being used. Ideally, not just the hash, but (hash() % array_size) is random and evenly distributed.
But this only really matters for data with a small hash range (like a byte or character).

Arrangements of sets of k positions in a n-competitors race

this is a copy of my post on mathexchange.com.
Let E(n) be the set of all possible ending arrangements of a race of n competitors.
Obviously, because it's a race, each one of the n competitors wants to win.
Hence, the order of the arrangements does matter.
Let us also say that if two competitors end with the same result of time, they win the same spot.
For example, E(3) contains the following sets of arrangements:
{(1,1,1), (1,1,2), (1,2,1), (1,2,2), (1,2,3), (1,3,2), (2,1,1), (2,1,2),(2,1,3), (2,2,1), (2,3,1), (3,1,2), (3,2,1)}.
Needless to say, for example, that the arrangement (1,3,3) is invalid, because the two competitors that supposedly ended in the third place, actually ended in the second place. So the above arrangement "transfers" to (1,2,2).
Define k to be the number of distinct positions of the competitors in a subset of E(n).
We have for example:
(1,1,1) -------> k = 1
(1,2,1) -------> k = 2
(1,2,3,2) -------> k = 3
(1,2,1,5,4,4,3) -------> k = 5
Finally, let M(n,k) be the number of subsets of E(n) in which the competitors ended in exactly k distinct positions.
We get, for example,M(3,3) = M(3,2) = 6 and M(3,1) = 1.
-------------------------------------------------------------------------------------------
Thus far is the question
It's a problem I came up with solely by myself. After some time of thought I came up with the following recursive formula for |E(n)|:
(Don't continue reading if you want to derive a formula yourself!)
|E(n)| = sum from l=1 to n of C(n,l)*|E(n-l)| where |E(0)| = 1
And the code in Java for this function, using the BigInteger class:
public static BigInteger E (int n)
{
if (!Ens[n].equals(BigInteger.ZERO))
return Ens[n];
else
{
BigInteger ends=BigInteger.ZERO;
for (int l=1;l<=n;l++)
ends=ends.add(factorials[n].divide(factorials[l].multiply(factorials[n-l])).multiply(E(n-l)));
Ens[n]=ends;
return ends;
}
}
The factorials array is an array of precalculated factorials for faster binomial coefficients calculations.
The Ens array is an array of the memoized/cached E(n) values which really quickens the calculating, due to the need of repeatedly calculating certain E(n) values.
The logic behind this recurrence relation is that l symbolizes how many "first" spots we have. For each l, the binomial coefficient C(n,l) symbolizes in how many ways we can pick l first-placers out of the n competitors. Once we have chosen them, we to need to figure out in how many ways we can arrange the n-l competitors we have left, which is just |E(n-l)|.
I get the following:
|E(3)| = 13
|E(5)| = 541
|E(10)| = 102247563
|E(100)| mod 1 000 000 007 = 619182829 -------> 20 ms.
And |E(1000)| mod 1 000 000 007 = 581423957 -------> 39 sec.
I figured out that |E(n)| can also be visualized as the number of sets to which the following applies:
For every i = 1, 2, 3 ... n, every i-tuple subset of the original set has GCD (greatest common divisor) of all of its elements equal to 1.
But I'm not 100% sure about this because I was not able to compute this approach for large n.
However, even with precalculating factorials and memoizing the E(n)'s, the calculating times for higher n's grow very fast.
Is anyone capable of verifying the above formula and values?
Can anyone derive a better, faster formula? Perhaps with generating functions?
As for M(n,k).. I'm totally clueless. I absolutely have no idea how to calculate it, and therefore I couldn't post any meaningful data points.
Perhaps it's P(n,k) = n!/(n-k)!.
Can anyone figure out a formula for M(n,k)?
I have no idea which function is harder to compute, either E(n) or M(n,k), but helping me with either of them will be very much appreciable.
I want the solutions to be generic as well as work efficiently even for large n's. Exhaustive search is not what I'm looking for, unfortunately.
What I am looking for is solutions based purely on combinatorial approach and efficient formulas.
I hope I was clear enough with the wording and what I ask for throughout my post. By the way, I can program using Java. I also know Mathematica pretty decently :) .
Thanks a lot in advance,
Matan.
E(n) are the Fubini numbers. M(n, k) = S(n, k) * k!, where S(n, k) is a Stirling number of the second kind, because S(n, k) is the number of different placing partitions, and k! is the number of ways to rank them.

Math twenty four game Java [duplicate]

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.

Given a number check if digits form an equation with addition?

Given a string S, I want to find out whether there are non-overlapping substrings A, B and C in S, so that the equation A + B = C holds when the substrings are interpreted as decimal numbers.
Example: For S = 17512, the answer is yes, because 12 + 5 = 17 holds.
This is not a homework question, I have tried approaching this problem building a suffix array
17512
7512
512
12
2
but then I realize that given 132, 1 + 2 = 3
Would require other forms of permutations in selection?
How do you solve this in an efficient way?
Let S be the decimal representation of the number. If n = |S| is small enough (<500 or so), you can use the following algorithm:
Let us enumerate A and C from the equation A + B = C (where we assume w.l.o.g. A > B). We know that they need to be of around the same size (plus/minus one digit), so enumerating the possibilities is a cubic operation (there are O(n3) candidates).
For every candidate pair (A, C), we need to check whether B = C - A is in the string and not overlapping with any of the A or C substrings. We can compute the difference in linear time using arithmetics in base 10.
The tricky part is to check whether B is a substring not overlapping A or C. A and C split the string into 3 parts:
S = xAyCz
If we enumerate them in a clever way, with fixed start positions and decreasing size, we can maintain suffix automata of part x and the reverses of parts y and z.
Now we can check in linear time whether B = C - A (or its reverse) exists in one of the three parts.
Time complexity of this approach: Θ(n4).
There is a variation of this which is slightly more complicated, but faster (thanks to Evgeny for pointing it out):
Create a suffix tree of the input string. Every node represents a substring. Store in every node a balanced binary search tree of the positions where the substring occurs in the string. You might need persistent trees here to save time and space.
Enumerate A and C, but this time starting from the least-significant digit (the rightmost end).
While growing A and C from right to left, keep track of the result of B = C - A. It will also grow from least-significant to most-siginificant digit. Do a search for B in the suffix tree. You can do this one digit at a time, so you can make grow A and C by 1 digit, update B and locate it in the suffix tree in O(1).
If B is positive, do three range queries in the BBST of positions to check whether B occurs in the string and does not overlap A or C
Runtime: O(n3 log n).
UPDATE: regarding the simplified version where all characters need to be used:
We first realize that we can do arithmetics on substrings of our string in linear time, if we work in base 10.
Now we want to find the splitting points a < b, so that your three substrings are A = s1...sa, B = sa+1...sb and C = sb+1...sn.
We can prove that there is only a constant number of candidates for a and b, because all three parts must have approximately the same size for the equation to hold.
Using arbitrary precision arithmetics, we can easily try out all candidate pairs (a,b) and for each of those, find M = max(A,B,C). Then just check whether M is the sum of the other two numbers.
Total time complexity: Θ(n).
If you are allowed to form substrings from arbtirary subsets of digits in their original given order as long as your digits don't overlap in the 2 summands and the sum, then I believe your problem is NP-complete. I think this is even true if the target sum is given and all you have to do is find two non-overlapping substrings of digits that add up to the target sum. However I don't have a proof of NP-completeness yet.
If your substrings of digits have to be consecutive then the situation is much better. You can search over all combinations of 2 summands and 1 sum for the starting and ending points of the numbers in O(n^6) time, and certainly there are improvements that can be made because e.g. for a given target sum, you only need to search over pairs of substrings whose max length adds up to the length of your target sum either exactly or minus 1.
UPDATE: If you need to find 3 non-overlapping contiguous substrings that give you the summation formula, then you can hash all O(n^2) substring values and then hash the sum of all pairs of summands to see if the target sum is in your hash table. If so, then you only need to check if the summand beginning and ending indices do not overlap the summand indices. Worst-case time is O(n^6), expected running time is O(n^5) for random inputs.
Assuming (As in both your examples) that your 3 substrings are contiguous, non-overlapping, non-negative, and between them cover the whole input, then there is a quadratic time solution.
First (temporarily) assume the order is aaabbbccc where aaa+bbb=ccc, and aaa>bbb.
The length of ccc must either be the same as aaa or at most one larger.
So the length of aaa (len_a) must be between n/3 and n/2.
Given the len_a, there are two choices for len_c --- len_a or len_a+1.
Given these, there is only one possible length of bbb. len_b = n-len_a = len_c
Test these 2(n/2 - n/3) = n/3 cases.
Each test is O(n) cost due to string to int conversion.
Repeat the above analysis for two permutations (aaa>bbb v bbb>=aaa), times three permutations (aaa+bbb=ccc v aaa+ccc=bbb v bbb+ccc=aaa)
You could improve the test to check only the most (or least) significant i digits of the three numbers, returning early if the sum was not possible. Assuming randomly distributed digits, you might be able to show that the expected run time of such a test was constant.
This would turn the whole algorithm into an O(n) runtime.

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.

Categories

Resources