Subtracting values from an integer until a target reached - java

I am working on a problem in Java that features an adaptation of the partition problem. Effectively, a sequence of numbers of length 5 or more is entered into the command line, and if the sequence can be split into two equal parts, true is output, and if it cannot, false is given. It is important to note that the numbers in the sequence can't be rearranged.
I have found that a solution can be found by taking the sum of all the numbers in the sequence, then dividing it by 2 to find another integer value (I'll call it T2 for this purpose). If we subtract the numbers in the sequence in order from T2 and if it becomes equal to zero at any point, ie. T2 - "term 1" - "term 2" - ... - "term n" = 0, then we need to output true. I am unsure however how this can be implemented in Java. I have experimented a little with using different "for"and "while" loops but can't get it to meet the conditions I need to give the correct output.
If anyone could point me in the right direction of how to implement this process into Java I would be extremely grateful. Apologies for the terrible formatting of the question, I'm very new to the site. Thanks in advance for your help!

Related

How `Projections.max("registrationNo")` will work when registrationNo is String

I have an entity called StudentDetails.In that there is a field RegistrationNo of type String.My client follows a pattern like xxxxx-xxxx (Number in sequence 00000 To 10000)-(current Year Number).To Store RegistrationNo in this pattern we declared it as String.Every time new student is joined we have to increment the sequence number we have to store it.
I tried Without knowing that it stored as String i tried to fetch last number using Projections.max("registrationNo") Luckily it returned max number i don't know how.But still again problem raised when sequence number reached 6 digits like xxxxxx-xxxx then Projections.max("registrationNo") is not returning 6 digit number.It is returning only max of 5 digit number .
How projection is returning max of 5 digit number but not 6 digit number.
by the way i solved that problem using id of the record to know last RegistrationNo.But Projections.max("registrationNo") is puzzling me on how it worked for sometime.
As already stated in the comments the problem is most likely a string comparison, i.e. calling max() on a property of type string will result in the "maximum" string value being returned, even if those strings represent numbers.
A string comparison is normally done by comparing characters from start to end until there is a difference or the end of one input string is reached (in which case the longer string would be the greater one).
Thus as long as your sequence numbers are of equal length it should work since comparing 10000 and 00001 will result in the "correct" characters being compared.
However, once the string lengths are different, a normal string compare won't work anymore, since the characters do represent different digits. Hence comparing 98765 to 123456 will result in 98765 being greater since the first characters to be compared will be 1 and 9 and 1 < 9 almost all of the time (unless you changed that somehow).
To solve this you can take a couple of routes which depend on your environment and goals:
store the sequence number in a separate numeric property
make the sequence strings longer right from the start, i.e. allow for a bigger range
add a specialized comparator in the code or the database (just as a hint, I'd have to look up how to do it)
From a performance point of view I'd probably take the first route.

Find if a permutation (using + and -) on a string of integers matches a number

Basically what I am doing it taking a string of integers (e.g. "1234"), and I am able to insert a + or - anywhere in this string, as much or little as I want. For example, I can do "1 + 2 + 3 + 4", "12 + 34", "123 - 4", etc. It is required to use all integers of the string, I cannot exclude any.
What I am trying to do is take another array of integers, and find if it was possible to get that number using the permutations mentioned in the first paragraph. I am somewhat lost on where to start looking for this. I could possibly create a recursive loop function to create every possible combination of the string and see if each result matches but this seems like it will be terribly slow. Another thought was to index them into an array - that way I could simply look up the answers after calculating them once.
Anyone have any suggestions?
I could possibly create a recursive loop function to create every possible combination of the string and see if each result matches but this seems like it will be terribly slow.
Doing an exhaustive search is your only option here. Fortunately, the timing isn't going to be too bad even for moderately long strings of up to 7..10 characters, because you do not need to "redo" additions and subtractions of a prior string when you process the "tail".
An outline of a possible implementation could be as follows:
Put all desired results from your array of integers in a hash set
Make a recursive method that takes the result so far, the string, and the position of the next "cut"
When the next "cut" is at the end of the string, check the result so far against the hash set from step 1
Otherwise, try these three possibilities in a loop on k
Use a k-digit number from the "cut" as a positive number, and make a recursive invocation with the "cut" moved by k digits. This is equivalent to inserting a + at the cut
Use a k-digit number from the "cut" as a negative number, and make a recursive invocation with the "cut" moved by k digits. This is equivalent to inserting a - at the cut
I'll give start help, with the approach for such a solution.
formal problem statement;
data model;
algorithm;
heuristics, cleverness.
For N digits there are some 3^N possibilities.
The solution must model the running data as:
the digits, as int[]
the sum
index from which to advance, prior digits were done.
number partalready tried, plus sign. Sign must come separate (as -1, +1) as the coming digit may be 0;
(What I leave out is the collecting of the entire result.)
The brute force solution then could be:
boolean solve(int[] digits, int sum) {
return solve(digits, sum, 1, 0, 0);
}
boolean solve(int[] digits, int sum, int signum, int part, int index) {
if (index >= digits.length) {
return signum * part == sum;
}
// Before the digit at index do either nothing, +, or -
return solve(digits, sum, signum, part * 10 + digits[index], index + 1)
|| solve(digits, sum - signum * part, 1, 0, index + 1)
|| solve(digits, sum - signum * part, -1, 0, index + 1);
}
Mind you could also split the digits in half and try to insert (nothing, +, -) there.
There are pruning opportunities, to diminish the number of tries. First the above can be done in a loop, the alternatives need not all to be tried. The order of evaluation might favor more likely candidates:
if digit 0 ...
if part > sum first - then +
...
Unfortunately +/- make a number theoretical approach AFAIK for me illusory.
#dasblinkenlight mentions even better data models, allowing to not
repeat evaluation in the alternatives. That would be even more
interesting. But might fail miserably due to time constraints. And I
wanted to come with something concrete. Without providing an entirely
ready made solution.
It is reasonable to take a brute force approach if you can rely on the input string not to be too long. If it contains n digits then you can construct 3n-1 formulae from it (between each pair of digits you can insert '+', '-', or nothing, for n-1 internal positions). For a 12-digit input string that's roughly 270000 formulae, which should be computable quite quickly. Of course, you would build and compute each one once, and compare the result to all the alternatives. Don't redo the computation for each array element.
It may be that there's a dynamic programming approach to this, but I'm not immediately seeing it, at least not one that would be substantially better than brute force.

8 puzzle: Solvability and shortest solution

I have built a 8 puzzle solver using Breadth First Search. I would now want to modify the code to use heuristics. I would be grateful if someone could answer the following two questions:
Solvability
How do we decide whether an 8 puzzle is solvable ? (given a starting state and a goal state )
This is what Wikipedia says:
The invariant is the parity of the permutation of all 16 squares plus
the parity of the taxicab distance (number of rows plus number of
columns) of the empty square from the lower right corner.
Unfortunately, I couldn't understand what that meant. It was a bit complicated to understand. Can someone explain it in a simpler language?
Shortest Solution
Given a heuristic, is it guaranteed to give the shortest solution using the A* algorithm? To be more specific, will the first node in the open list always have a depth ( or the number of movements made so fat ) which is the minimum of the depths of all the nodes present in the open list?
Should the heuristic satisfy some condition for the above statement to be true?
Edit : How is it that an admissible heuristic will always provide the optimal solution? And how do we test whether a heuristic is admissible?
I would be using the heuristics listed here
Manhattan Distance
Linear Conflict
Pattern Database
Misplaced Tiles
Nilsson's Sequence Score
N-MaxSwap X-Y
Tiles out of row and column
For clarification from Eyal Schneider :
I'll refer only to the solvability issue. Some background in permutations is needed.
A permutation is a reordering of an ordered set. For example, 2134 is a reordering of the list 1234, where 1 and 2 swap places. A permutation has a parity property; it refers to the parity of the number of inversions. For example, in the following permutation you can see that exactly 3 inversions exist (23,24,34):
1234
1432
That means that the permutation has an odd parity. The following permutation has an even parity (12, 34):
1234
2143
Naturally, the identity permutation (which keeps the items order) has an even parity.
Any state in the 15 puzzle (or 8 puzzle) can be regarded as a permutation of the final state, if we look at it as a concatenation of the rows, starting from the first row. Note that every legal move changes the parity of the permutation (because we swap two elements, and the number of inversions involving items in between them must be even). Therefore, if you know that the empty square has to travel an even number of steps to reach its final state, then the permutation must also be even. Otherwise, you'll end with an odd permutation of the final state, which is necessarily different from it. Same with odd number of steps for the empty square.
According to the Wikipedia link you provided, the criteria above is sufficient and necessary for a given puzzle to be solvable.
The A* algorithm is guaranteed to find the (one if there are more than one equal short ones) shortest solution, if your heuristic always underestimates the real costs (In your case the real number of needed moves to the solution).
But on the fly I cannot come up with a good heuristic for your problem. That needs some thinking to find such a heuristic.
The real art using A* is to find a heuristic that always underestimates the real costs but as little as possible to speed up the search.
First ideas for such a heuristic:
A quite pad but valid heuristic that popped up in my mind is the manhatten distance of the empty filed to its final destination.
The sum of the manhatten distance of each field to its final destination divided by the maximal number of fields that can change position within one move. (I think this is quite a good heuristic)
For anyone coming along, I will attempt to explain how the OP got the value pairs as well as how he determines the highlighted ones i.e. inversions as it took me several hours to figure it out. First the pairs.
First take the goal state and imagine it as a 1D array(A for example)
[1,2,3,8,0,4,7,5]. Each value in that array has it's own column in the table(going all the way down, which is the first value of the pair.)
Then move over 1 value to the right in the array(i + 1) and go all the way down again, second pair value. for example(State A): the first column, second value will start [2,3,8,0,4,7,5] going down. the second column, will start [3,8,0,4,7,5] etc..
okay now for the inversions. for each of the 2 pair values, find their INDEX location in the start state. if the left INDEX > right INDEX then it's an inversion(highlighted). first four pairs of state A are: (1,2),(1,3),(1,8),(1,0)
1 is at Index 3
2 is at Index 0
3 > 0 so inversion.
1 is 3
3 is 2
3 > 2 so inversion
1 is 3
8 is 1
3 > 2 so inversion
1 is 3
0 is 7
3 < 7 so No inversion
Do this for each pairs and tally up the total inversions.
If both even or both odd (Manhattan distance of blank spot And total inversions)
then it's solvable. Hope this helps!

Finding the expansion of PI

In an interview, I was asked to find a first 9 digit palindrome in an expansion of PI. And I had no idea as to how I should go for it. The question remained in my system throughout the interview and I couldn't properly answer the questions to follow.
Whats the optimal way?
EDIT:
Finding palindrome is not difficult but how can I get the expansion of PI as much as I need. I have tried Math.PI, i have tried 22/7 but nothing gives me what I need.
the "optimal" way here strongly depends on the choice of the algorithm for calculating Pi, assuming you don't have access to an arbitrary number of digits off the shelf.
There are lots of infinite sums that converge against pi, each of which capable of eventually producing the right digits, however you'd have to use some library that allows infinitely precise floating point numbers, or infinitely large integers.
After that, finding the palindromes is relatively easy, as you'd only have to compare the first to the ninth number, the second to the eighth and so forth.
The devil in this case is clearly which converging sum to use for the approximation of Pi.
A couple of these are listed on the wikipedia page for Pi: http://en.wikipedia.org/wiki/Pi#Polygon_approximation_era
Firstly, I would make a subset of the numbers in pi and convert to a string.
I would take a nine character subset string from it, then compare the first character with the last one. If they match, compare character 2 with 8 and so on. If any of the comparisons fails then move the 9 character string to the next set - by one character.
I would probably point the assign the first index value to first variable and ninth index value to second variable and then see if they are equal . In case they are equal I will assign second index value to first variable and eight index value to second variable till they meet at mid postion . In case they differ with one another at some place assign first variable the value of the latest left side index which differs with right side index and second variable value of the left side index + 8 and repeat process till you reach last index - 8 position .

Handling large numbers

I have this problem:
A positive integer is called a palindrome if its representation in the decimal system is the same when read from left to right and from right to left. For a given positive integer K of not more than 1000000 digits, write the value of the smallest palindrome larger than K to output. Numbers are always displayed without leading zeros.
Input
The first line contains integer t, the number of test cases. Integers K are given in the next t lines.
Output
For each K, output the smallest palindrome larger than K.
Example
Input:
2
808
2133
Output:
818
2222
My code converts the input to a string and evaluates either end of the string making adjustments accordingly and moves inwards. However, the problem requires that it can take values up to 10^6 digits long, if I try to parse large numbers I get a number format exception i.e.
Integer.parseInt(LARGENUMBER);
or
Long.parseInt(LARGENUMBER);
and LARGENUMBER is out of range. can anyone think of a work around or how to handle such large numbers?
You could probably use the BigInteger class to handle large integers like this.
However, I wouldn't count on it being efficient at such massive sizes. Because it still uses O(n^2) algorithms for multiplication and conversions.
Think of your steps that you do now. Do you see something that seems a little superfluous since you're converting the number to a string to process it?
While this problem talks about integers, its doing so only to restrict the input and output characters and format. This is really a string operations question with careful selection. Since this is the case, you really don't need to actually read the input in as integers, only strings.
This will make validating the palindrome simple. The only thing you should need to work out is choosing the next higher one.

Categories

Resources