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 5 years ago.
Improve this question
the string is 1a2a(3a4) then I am able to extract (3a4) & calculate it, let 'x' be the answer then substitute to main 1a2ax & calculate as normal (which is easy, I have done. ( a - add, s - sub, m - mul, d - div)
for above equation, I have done like this (works only if I have one set of brackets)
public class task2 {
private static double parseString(String str) {
// declaring the operators' counters
int a = 1;
int s = 1;
int m = 1;
int d = 1;
// splitting the string up into operands and operators
double[] operands = Arrays.stream(str.split("[asmd]")).mapToDouble(Double::parseDouble).toArray();
String[] operators = str.split("\\d+");
// the rest is pretty much self-explanatory
double total = operands[0];
for (int i = 1 ; i < operators.length ; i++) { // note that i starts at 1 because the first item in operators
switch (operators[i]) { // array is an empty string
case "a":
total = total * a + operands[i];
a++;
break;
case "s":
total = total * s - operands[i];
s++;
break;
case "d":
total = total * d / operands[i];
d++;
break;
case "m":
total = total * m * operands[i];
m++;
break;
}
}
return total;
}
public static void main(String[] args){
String x= "1a(2a6a16)a9s88s77m9d5";
System.out.print("Expression \""+x+"\" on solving gives answer as ");
//To extract String with Bracket
Matcher m = Pattern.compile("\\((.*?)\\)").matcher(x);
String y = null;
while(m.find()) {
y = m.group(1);
}
String z = Double.toString(task2.parseString(y));
int p = (int)Double.parseDouble(z);
String q = Integer.toString(p);
x = x.replaceAll("\\p{P}","");
x = x.replace(y,q);
// To call method to find value
System.out.println(task2.parseString(x));
}
}
But prob comes when an equation is
((1a3a(9s9s(10d200))s(10m100a(192s187))a10)d2d8)
, when I have to apply the recursive extract of innermost parenthesis until no more parenthesis, which I am struggling with.
firstly (10d200) extracted and calculated, let the answer be "P", the equation becomes ((1a3a(9s9sP)s(10m100a(192s187))a10)d2d8)
secondly (9s9sp) extracted and calculated, let answer be "Q", equation becomes ((1a3aQs(10m100a(192s187))a10)d2d8)
thirdly (192s187) extracted and calculated, let answer be "R", equation becomes ((1a3aQs(10m100aR)a10)d2d8)
forthly (10m100aR) extracted and calculated, let answer be "S", equation becomes ((1a3aQsSa10)d2d8)
fifthly (Td2d8) expression calculated.
Plz, Help me out here. Thanks in advance.
Pseudocode:
while (there are parentheses left) {
find first closing parenthesis;
walk left and find nearest opening parenthesis;
evaluate expression inbetween;
replace expression with result and remove parentheses;
}
evaluate expression;
Edit: Just for completeness, this can be written in a compact way using peg.js: https://jsfiddle.net/mxLq9drm/2
The simplest way would be to always parse the content of the first pair of brackets:
stack s
for i = 0; i < len(text); i++ do
if text[i] is openingbracket
s.push(i)
if next character is closing bracket
pos = s.pop()
res = parse(text, pos + 1, i - 1)
text.replace(pos, i, res) //update the string to parse
i = pos + len(res) //set i to the end of the newly inserted string
The basic idea is to store the indices of all opening-brackets in a stack. If a closing-bracket is encountered, take the string between the last opening-bracket (head of the stack) and the current position, evaluate the expression and replace it in the string. Afterwards update the current position in the string and proceed to parse.
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
Java Code Example: i am facing issue when i insert 010 it shows only 1 instead of whole number and when i insert 200 it gave me reverse number only 2 while it should show me exact 002 how can i get exact number in reverse:
class Reverse{
public static void main(String args[]){
int remander,sum=0;
int number=454;
while(n>0) // loop here
{
remander=n%10; // Getting remainder
sum=(sum*10)+remander;
number=number/10;
}
System.out.println("Reverse"+sum);
}
}
It is clear that you are new to Java, and new to programming. Welcome to StackOverflow. I'm going to add some extra advice that I don't normally offer, to help you get better faster.
Don't reuse a variable for more than one thing. Use it for only one thing. That means that if a variable holds you input, don't overwrite it with intermediate values. Variables are (relatively) cheap, create another. You can practice this by marking your variables final which will prevent you from changing their values after assigned.
Use meaningful variable names. "r" is not a meaningful name. "remainder" is a meaningful name. This helps others immediately, and will help you later, when the program isn't fresh on your mind and you don't remember what "r" means.
Once you master not reusing variables, you will have a lot of variables. Look for variables that are "set once and read once" and try to rearrange your code to remove them completely. It will take some time to understand what I mean, but if you have heard of "refactoring" the idea is to remove the variable name because it isn't used twice (so it probably isn't a key part of your problem.
Now, applying these rules
final int number = 454;
// get the number digits, smallest to largest
int remainder = number;
int accumulator = 0;
while (remainder > 0) {
final int digit = remainder % 10;
accumulator = accumulator * 10 + digit;
remainder = remainder / 10;
}
final int reversed = accumulator;
note that digit is never used twice
final int number = 454;
// get the number digits, smallest to largest
int remainder = number;
int accumulator = 0;
while (remainder > 0) {
accumulator = accumulator * 10 + remainder % 10;
remainder = remainder / 10;
}
final int reversed = accumulator;
Note that all that "logic" could have a really good name put to it, so we'll create a "method"
public int reverse(int value) {
int remainder = value;
int accumulator = 0;
while (remainder > 0) {
accumulator = accumulator * 10 + remainder % 10;
remainder = remainder / 10;
}
return accumulator;
}
which cleans up the other code to
final int number = 454;
final int reversed = reverse(number);
or maybe even
final int reversed = reverse(454);
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
In Java, the following code:
long x = 123;
String s = "abc" + x;
takes a significantly more runtime than:
long x = 123;
String s = "abc" + String.valueOf(x);
I got to know this through leetcode. I was trying to solve the following problem: https://leetcode.com/problems/fraction-to-recurring-decimal/
Here is the exact code for my solution:
public String fractionToDecimal(int numerator, int denominator) {
long n = numerator, d = denominator;
boolean isNegative = (n * d < 0);
if(n < 0) n = -n;
if(d < 0) d = -d;
long q = n / d;
long r = n % d;
if(r == 0) return (isNegative ? "-" : "") + q;
StringBuilder sb = new StringBuilder();
if(isNegative) sb.append('-');
sb.append(q).append('.');
Map<Long, Integer> found = new HashMap<>();
int index = sb.length();
while(r > 0 && !found.containsKey(r)){
found.put(r, index++);
n = r * 10;
q = n / d;
r = n % d;
sb.append(q);
}
if(r > 0) {
sb.insert(found.get(r), "(");
sb.append(')');
}
return sb.toString();
}
When I click on Submit it takes as long as 7 milliseconds to complete.
But if I literally just change line no. 8 from + q to + String.valueOf(q) the runtime plummets down to just 1 millisecond. Please feel free to copy paste the code on leetcode to try it out there and see this change in runtime for yourself, if necessary.
This is highly confusing to me. Why is this happening? As per my understanding, in both the cases, compiler first converts the long to a String, and then concatenates those two Strings together, right? So, under the hood, isn't concatenating a String and a long exactly the same as concatenating two Strings together? Then why does one take more time to run than the other? Any insight would be highly appreciated. TIA.
Note: this answer was written before the question was changed. It used to include the expressions shown below.
"abc" + 123 is a constant expression - the concatenation is done at compile-time so "abc123" ends up in the constant pool.
"abc" + String.valueOf(123) is not a constant expression. The concatenation happens at execution time, which is obviously rather more expensive than just using the compile-time concatenation result.
So I'd expect the result to be the opposite of what you've actually reported in the question.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
My code works perfectly for some floating value such as 125.5:
public class NewClass {
public static void main(String[] args){
Scanner Input = new Scanner(System.in);
NewClass ob = new NewClass();
double n = Input.nextDouble();
double cbrt = ob.Cbrt(n);
System.out.println(cbrt);
}
public double GetSquareRoot(double n, double low, double high) {
double cbrt = (low + high) / 2;
if (cbrt*cbrt*cbrt > n)
return GetSquareRoot(n, low, cbrt);
if (cbrt*cbrt*cbrt < n)
return GetSquareRoot(n, cbrt, high);
return cbrt;
}
public double Cbrt(double n) {
NewClass ob = new NewClass();
return ob.GetSquareRoot(n, 0, n);
}
}
It does not give correct answer when input is:
0.008
or 0.125
or 50
or 100
Then I am getting java.lang.StackOverflowError.
When input is 125.5 or 125 or 8 it gives the correct solution.
Can someone help me?
The error is that this line:
return ob.GetSquareRoot(n, 0, n);
(which is, of course, misnamed) tries to find a solution between 0 and n. However, if 0 < n < 1, then n1/3 > n, so you will never find a solution in the interval (0, n). You'll need to make a special case of this; for example, if 0 < n < 1, you can search the interval (n, 1) instead.
Also, using 0 and n as the bounds won't work for negative numbers, so if you want to make your method more complete and handle those cases, you'll need special cases for those too (probably different for -1 < n < 0 and n < -1).
MORE: After seeing your comment about StackOverflowError, it's occurred to me that you have an additional problem: that you're expecting an exact result. When you put in 0.008, the cube root is 0.2. However, neither 0.008 nor 0.2 can be represented exactly as a floating-point number. The consequence is that if you let cbrt = whatever value is closest to 0.2 that can be represented, then cbrt*cbrt*cbrt won't be exactly 0.008. It can't be exactly 0.008 anyway, since 0.008 can't be represented as a double; however, if n is whatever value is closest to 0.008, then it's likely that cbrt*cbrt*cbrt will not be exactly equal to n, due to roundoff errors. For a calculation like this, it's important that you not compare doubles for equality; instead, compare them using an "epsilon" value, or a margin of error. Thus, after
double cbrt = (low + high) / 2;
you should have something like
if (Math.abs(cbrt*cbrt*cbrt - n) < EPSILON)
return cbrt;
where EPSILON is some small value such as 1E-10. (I've sometimes seen code where EPSILON is computed to be a relative value, i.e. abs(n * RELATIVE_EPSILON), instead of an absolute value.)
Another way to avoid StackOverflowError is to quit when low and high become really close, because by that point you're not going to gain much more accuracy, and you need to make sure you exit the algorithm even if the value of cbrt*cbrt*cbrt is a little bit off. Something like
if (high - low < EPSILON)
return cbrt;
See also What's wrong with using == to compare floats in Java?.
//How about My Solution - Without Recursive
import java.util.Scanner;
public class CubeRoot {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String str = input.next();
Boolean negative = false;
if (str.startsWith("-")) {
str = str.substring(1);
negative = true;
}
if (str.indexOf(".") > 0) {
// find the poisition of '.'
int pPos = str.length() - 1 - str.indexOf(".");
String plainStr = (str.substring(0, str.indexOf('.')).concat(str.substring(str.indexOf('.') + 1)));
StringBuffer cStr = new StringBuffer(cubeRoot(plainStr));
if (cStr.toString().equalsIgnoreCase(plainStr))
System.out.println("couldn't compute Cube Root for this :(");
else {
if (cStr.length() > pPos / 3) // devide 3 times to put the '.'
cStr.insert(cStr.length() - pPos / 3, ".");
else {
int cStrLength = cStr.length();
for (int i = 0; i <= pPos / 3 - cStrLength; i++)
cStr = new StringBuffer("0").append(cStr.toString());
cStr.insert(cStr.length() - pPos / 3, ".");
}
String append = (negative) ? new String("-") : new String("");
System.out.println(append + cStr.toString());
}
} else {
System.out.println("Not a floating num");
}
}
private static String cubeRoot(String d) {
Long l = new Long(d);
for (int i = 0; i < l; i++) {
if (i * i * i == l) {
return String.valueOf(i);
}
}
return d;
}
}
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 6 years ago.
Improve this question
So I'm new to programming. I'm using java. Right now I have an assignment I can't solve on a website that teaches java.
This is the assignment
Write a program that returns number of occurrences of a string in another string.
E.g
Input:
First String: the
Second String: The students are working hard in the faculty of Engineering because they love it
Output:
3
Note: You should only use nested loops. Don’t use methods like indexOf or substring.
Ienter image description here reached to the code the calculate the number of occurrences but it failed in case of repeated letters
E.g
input:
First String : ooo
Second String : wooooooooooooooooooooow
Output : 21
It's supposed to be 7 since the ooo have only repeated 7 times
This question can be simply solved by using z-function in linear time.
int NumberOfcopies(String t, String h){
// t = the first string i.e "ooo"
// h = the second string i.e "wooooooooooooooooooooow"
String s = t + "$" + h; // adding a sentinel character in between
int n = s.length(); // length of new string
int[] z = new int[n]; // z array
// Code ref : http://e-maxx-eng.github.io/string/z-function.html
int l = 0, r = 0;
for (int i = 1; i < n; i++){
if (i <= r)
z[i] = Math.min(r - i + 1, z[i - 1]);
while (i + z[i] < n && s.charAt(z[i]) == s.charAt(i + z[i]))
++z[i];
if (i + z[i] - 1 > r){
l = i;
r = i + z[i] - 1;
}
}
//checking for all the occurance of string t in string h
int res = 0;
for (int i = t.length() + 1; i < n; ){
if (z[i] == t.length()){
//A copy is found so skip next t.length chars
i += t.length();
++res;
}
else ++i;
}
System.out.println("Number of Occurance : " + res);
return res;
}
The Z-function for this string is an array of length n where
the i-th element is equal to the greatest number of characters
starting from the position i that coincide with the first
characters of s.
This can be exploited to find the number of occurrences of a string t in another string h. Suppose we join the string t and h with a sentinel character in between (Sentinel character is a character that does not occur in either of the strings) to form a new string s.
Lets us calculate the z function in array z[].
Now lets start searching from the character after the sentinel character i.e. the characters of string h. For i-th character in string h ( such that i-th character belongs to string s) if z[i] equals to length of string t (the pattern) then it implies that starting from i-th char, the t.length() chars are same as the first t.length() chars of string s which is what the string t equals.
example :
t = ab
h = aaabaab
s = a b $ a a a b a a b
z = 0 0 0 1 1 2 0 1 2 0
i = 0 1 2 3 4 5 6 7 8 9
for i = 5 we can see that z[i] == t.length(), that means we found a copy. Now to prevent Overlapping solutions, we skip the t.length() chars hence now i = 7
continuing this will get you the result.
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 6 years ago.
Improve this question
I found it in the net and I want to know the explanation of it's algorithm.
I'm having a hard time to understand this. thank you so much :)
import java.util.Scanner;
class BinarySearch
{
public static void main(String args[])
{
int c, first, last, middle, n, search, array[];
Scanner in = new Scanner(System.in);
System.out.println("Enter number of elements");
n = in.nextInt();
array = new int[n];
System.out.println("Enter " + n + " integers");
for (c = 0; c < n; c++)
array[c] = in.nextInt();
System.out.println("Enter value to find");
search = in.nextInt();
first = 0;
last = n - 1;
middle = (first + last)/2;
while( first <= last )
{
if ( array[middle] < search )
first = middle + 1;
else if ( array[middle] == search )
{
System.out.println(search + " found at location " + (middle + 1) + ".");
break;
}
else
last = middle - 1;
middle = (first + last)/2;
}
if ( first > last )
System.out.println(search + " is not present in the list.\n");
}
}
I'll appreciate your response. thanks again.
The binary search algorithm begins by comparing the target value to the value of the middle element of the sorted array. If the target value is equal to the middle element's value, then the position is returned and the search is finished. If the target value is less than the middle element's value, then the search continues on the lower half of the array; or if the target value is greater than the middle element's value, then the search continues on the upper half of the array. This process continues, eliminating half of the elements, and comparing the target value to the value of the middle element of the remaining elements - until the target value is either found (and its associated element position is returned), or until the entire array has been searched (and "not found" is returned).
Here is your answer beautifully explained :
check this out
http://www.csit.parkland.edu/~mbrandyberry/CS1Java/Lessons/Lesson27/BinarySearch.htm