Infix to postfix read negative integers as negative - java.util.scanner

Im doing a calculator for schoolwork and everything works except my scanner, cause when it takes a negative integer it doesnt see it as a negative number it just sees the subtraction sign as a operator and I want it to see it like a part of the operand:
String exp = "8+4*-12-4";
String[] temp = new String[exp.length()];
temp =exp.split("(?<=[-+*/])|(?=[-+*/])");
this makes it correct if its only positive integers.
for example
input: 8+4*12-4
and the
output:[8, 4, 12, *, +, 4, -]
but with a negative number it doesnt get it right!
so thats what I want help with, thanks in advance

LinkedList <String>list= new LinkedList<String>();
just takes each of the characters in the string and adds each to the resulting list. Instead of doing this, you need to write syntax-aware code. If you can insist on white space between all tokens, then you can split on spaces with, for example, String.split. If not, the simplest alternative is to iterate over the characters in the string "by hand" and create the output that way.
While I suppose it is also possible to use String.split with a non-capturing positive lookahead to also split on operators, figuring out regular expressions to that level of mastery is more difficult than solving the problem in code. I can't give an example for the positive lookahead assertion implementation, as I don't want to take the time to run up a development envirionment, write the code, create test cases and debug it - since I don't think this is the approach you should take in any case.

Related

Palindrome Validity Proof of Correctness

Leetcode Description
Given a string of length n, you have to decide whether the string is a palindrome or not, but you may delete at most one character.
For example: "aba" is a palindrome.
"abca" is also valid, since we may remove either "b" or "c" to get a palindrome.
I have seen many solutions that take the following approach.
With two pointers left and right initialized to the start and the end characters of the string, respectively, keep incrementing left and decrementing right synchronously as long as the two characters pointed by left and right are equal.
The first time we run into a mismatch between the characters pointed by left and right, and say these are specifically indices i and j, we simply check whether string[i..j-1] or string[i+1..j] is a palindrome.
I clearly see why this works, but one thing that's bothering me is the direction of the approach that we take when we first see the mismatch.
Assuming we do not care about time efficiency and only focus on correctness, I cannot see what prevents us from trying to delete a character in string[0..i-1] or string[j+1..n-1] and try to look whether the entire resulting string can become a palindrome or not?
More specifically, if we take the first approach and see that both string[i..j-1] and string[i+1..j] are not palindromes, what prevents us from backtracking to the second approach I described and see if deleting a character from string[0..i-1] or string[j+1..n-1] will yield a palindrome instead?
Can we mathematically prove why this approach is useless or simply incorrect?

Splitting a string into words with dynamic programming

In this problem we've to split a string into meaningful words. We're given a dictionary to see If the word exists or not.
I"ve seen some other approaches here at How to split a string into words. Ex: "stringintowords" -> "String Into Words"?.
I thought of a different approach and was wondering If it would work or not.
Example- itlookslikeasentence
Algorithm
Each letter of the string corresponds to a node in a DAG.
Initialize a bool array to False.
At each node we have a choice- If the addition of the present letter to the previous subarray still produces a valid word then add it, if it does not then we will begin a new word from that letter and set bool[previous_node]=True indicating that a word ended there. In the above example bool[1] would be set to true.
This is something similar to the maximum subarray sum problem.
Would this algorithm work?
No, it wouldn't. You solution takes the longest possible word at every step, which doesn't always work.
Here is counterexample:
Let's assume that the given string is aturtle. Your algorithm will take a. Then it will take t as at is valid word. atu is not a word, so it'll split the input: at + urtle. However, there is no way to split urtle into a sequence of valid English words. The right answer would be a + turtle.
One of the possible correct solutions uses dynamic programming. We can define a function f such that f(i) = true iff it's possible to split the first i characters of the input into a valid sequence of words. Initially, f(0) = true and the rest of the values are false. There is a transition from f(l) to f(r) if s[l + 1, r] is a valid word for all valid l and r.
P.S. Other types of greedy algorithms would not work here either. For instance, if you take the shortest word instead of the longest one, it fails to work on, for instance, the input atnight: there is no way to split tnight after the a is stripped off, but at + night is clearly a valid answer.

Is it bad to convert int to String only to access its digits?

I'm getting into a habit of converting int numbers to String to access its digits.
For example:
int number = 2899;
String number_str = String.valueOf(number);
StringBuffer reversedNumber = new StringBuffer();
for(int i = number_str.length()-1; i >= 0; i--)
{
reversedNumber.append(Character.getNumericValue(number_str.charAt(i)));
}
I believe there's another more common way to access the digits, namely, using a series of mod 10 and div 10. I understand mod 10 will give the n-th digit while div 10 will give 1 to (n-1)th digit of any given number with length n. But, I feel converting to String and accessing its characters is more convenient.
One of the examples when I converted int to String was on this question I asked on Code Review: https://codereview.stackexchange.com/questions/74441/stepping-number-solution-optimization
I basically wanted to check if a number was a stepping number. For example:
input: 8343545
output: 8343545 is a stepping number
Explanation: 8343545 can be written as 8,343,545. Def: A number is called a stepping number if every adjacent digits, except those separated by commas, differ by 1.
There are many other int problems I have done previously and used String conversion to access digits of a number. I just want to know is it bad to do this? Could you explain why is it bad and mod 10 or div 10 is preferred?
Is it bad?
No it is not, generally speaking. I actually prefer it:
Very easily understandable by people. Compare it with division/mod10 - not too many beginners will understand that. You code for people.
It's very easy to implement. Far less chance to write buggy code.
That said, ALL the good libraries use div10/mod10 method. First of all, library consumers don't really know the details, nor do they particularly care. Secondly, it performs much better, in performance wise.
There is very good chance that your use case does not require hyper-super performance. If it does - you know exactly what has to be done.

caesar cipher check in ocaml

I want to implement a check function that given two strings s1 and s2 will check if s2 is the caesar cipher of s1 or not. the inter face needs to be looked like string->string->bool.
the problem is that I am not allowed to use any string functions other than String.length, so how can I solve it? i am not permitted any list array, iterations. Only recursions and pattern matching.
Please help me. And also can you tell me how I can write a substring function in ocaml other than the module function with the above restrictions?
My guess is that you are probably allowed to use s.[i] to get the ith character of string s. This is the same as String.get, but the instructor may not think of it in those terms. Without some form of getting the individual characters for the string, I believe that this is impossible. You should probably double check with your instructor to be sure, but I would be surprised if he had meant for you to be unable to separate a string into characters (which is something that you cannot do with pattern-matching alone in Ocaml).
Once you can get individual characters, the way to do it should be pretty clear (you do not need substring to traverse each string recursively).
If you still want to write substring, creating it would be complex since you don't have access to String.create or other similar functions. But you can write your own version of String.create using recursion, one character string literals (like "x"), the ability to set a character in a string to another (like s.[0] <- c), and string concatenation (s1 ^ s2). Again, of course, all of this is assuming that those operators are allowed to be used.

How does one update and print a 'Rational' token in javacc?

I have added the new token RATIONAL that recognises rational numbers on my JavaCC parser. How can I update the output part of the program to print the numeric value of the rational number?
For example ('2/5') value = 0.4, ('8/2') value = 4.0, ('4/0') value = infinity.
I will be grateful if anyone could help me. Thanks.
You need to further split the image of your RATIONAL token in order to have both numbers available for computation.
It's not clear from your question whether the parentheses and quotes are part of the defined syntax. If they are, you can easily define them as delimiters for a rational expression and define tokens for the numbers and the slash. In case of ambiguity with other places where numbers can appear, remember that lexical states are your friends.
If a rational expression is simply made of two numbers separated by a slash, then I'd recommend building an AST and evaluate it after the parsing is complete. You can alternatively evaluate it during the parsing, but the difficulty of this depends on the rest of your grammar.

Resources