Thanks a bunch for the tip on the static to all of you folks who answered! Feeling a little less frustrated now.
I am not going to ask questions step by step through my whole assignment, but I want to make sure that this is the way to go about one of the next tasks. I have written the following, which compiles fine (the purpose is to check the string to make sure that it is numeric, and the user may have also entered the ISBN as a number with or without dashes):
private String validateISBN(String bookNum)
{
String[] book;
int j=0;
for ( int i=0;i<bookNum.length();i++)
if (character.isDigit(bookNum.charAt[i]))
bookNum.charAt[i]=book[j];j++;
I haven't written the next part, which has to allow for an X as the last digit in the string (which is apparently how ISBN numbers work). I would assume that if the above is correct (or close), that all i need to do is check that the ninth character is a digit or an X, by writing something like:
if book[9] isDigit() || if book[9] == "x" || if book[9] == "X";
Is that about right (ISBN numbers are always 10 numbers or 9 numbers and an X at the end)?
The last digit of ISBN-10 is the check digit. Since your method is supposed to check if the entered ISBN is correct, you have to calculate the check digit on your own and compare it to the given one (plus making sure all characters are digits).
If you're not knowing what this means, read the validating ISBN-10 section at http://en.wikipedia.org/wiki/International_Standard_Book_Number#Check_digits
The 2001 edition of the official manual of the International ISBN Agency says that the ISBN-10 check digit[18] — which is the last digit of the ten-digit ISBN — must range from 0 to 10 (the symbol X is used instead of 10) and must be such that the sum of all the ten digits, each multiplied by the integer weight, descending from 10 to 1, is a multiple of the number 11. Modular arithmetic is convenient for calculating the check digit using modulus 11. Each of the first nine digits of the ten-digit ISBN — excluding the check digit, itself — is multiplied by a number in a sequence from 10 to 2, and the remainder of the sum, with respect to 11, is computed. The resulting remainder, plus the check digit, must equal 11; therefore, the check digit is 11 minus the remainder of the sum of the products.
On a related note: there is also the 13-digit ISBN-13...
Maybe your solution might look like this:
Remove the dashes, break down the string to an int array, compute the tenth-digit (see wiki-link), if all is fine return the input string.
Related
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.
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.
So, I am making a program for doing arithmetic with multiple bases (meaning binary up to haxidecimal and all of the in-between), and since I am still relatively new to Java, I am having a bit of a hard time trying to figure out exactly how to make the comparison I want. What I would like to do is take the last character in the string and compare it to a specific integer. For example, say I have 9.54126 for a number. Well, at this point in the program this number is actually a string of characters, so I am looking at the '6' at the end as a character. I want to see if that six is high enough to round up or not. So, essentially I am looking to see if it's ASCII value is higher than half of the current base (if the answer is to be shown in base 15 or 16, I round up at 8 and so on). Earlier in the program I found the value it should be rounded at based on what the current chosen base is and saved it in the integer variable roundable. Now, I need to know how to compare the ASCII values of the integer as a character, and the character in the last spot. Here is example code:
//roundable is an integer here but I want it to be the character representation
//of the number so I can compare their ASCII values
if(convertedString.charAt(lastSpot)) >= roundable){
//round here
} else {
//don't round
}
Can someone please tell me how to accomplish this? Thank you!
Try this:
int base;
String number;
boolean roundUp = number.charAt(number.length() - 1) - '0' > base / 2;
Assuming that, your convertedString contains only character from '0'-'9': you just could easily do,
lastSpot = convertedString.length() - 1;
roundable = base/2;
if((convertedString.charAt(lastSpot) - '0') >= roundable){
//round here
} else {
//don't round
}
hex(decimal) value of '0' is 30(48) in and for '9' is 39(57).
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 .
Excluding the check digit, what is the minimum length number the luhn algorithm will work on?
My thoughts are that it would work on any number greater than 2 digits (again, excluding the check digit).
The reason I ask is this:
if i iterates over all digits in the number from right to left.
This causes i%2 == 0 (used to find alternate positions in the number) in my luhn validation to fail if the number is 3 digits or smaller (e.g. 125 -- which on paper seems to be a valid number)
Obviously I could change my condition from i%2== 0 to something else but if it's not the correct behavior for the algorithm it'd be nice to know.
Luhn's algorithm would work on two digits. It will warn if a single digit is wrong and some (but not all) of the cases where digits are transposed. Heck, it would theoretically work with one digit, but that's not very useful. You can see for yourself by fixing one digit, then changing the other and verifying that each value of the other digit will give a unique "checksum". With just two digits, however, just adding digits mod 10 would give you the same property, but it wouldn't catch any transposition errors.