Java loop to evaluate all operators - java

I need to modify this code in order to use order of operations and to be able to multiply and divide but I have no idea where to start. I know if works for addition and subtraction but I just need to figure out how to make it multiply and divide.
import java.util.Scanner;
class Expressions {
String e;
void setExpressions(String exp){
e =exp;
}
int evaluate1(){
//e has +. -. only, single digit numbers
int r = e.charAt(0)-'0';
int l = e.length();
for(int i=1; i<=l-1; i++ )
if (e.charAt(i) == '+')
r += (e.charAt(i+1)-48);
else
r -= (e.charAt(i+1)-'0');
return r;
}
int evaluateAS(){
//e has +, -, only, multiple digit numbers
int r = 0;
int n = 0;
int op = '+'; //+, -
for(int i=0; i<e.length(); i++ ){
if (e.charAt(i) == '-' || e.charAt(i) == '+'){
if (op == '+')
r += n;
else
r -= n;
n = 0;
op = e.charAt(i);
}
else //digits
n = n*10+(e.charAt(i) - '0');
}
if (op == '+')
r += n;
else
r -= n;
return r;
}
}
public class Runner {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
Expressions myE = new Expressions();
System.out.println("Enter E: ");
String e = in.next();
myE.setExpressions(e);
//int r = myE.evaluate1();
int r = myE.evaluateAS();
System.out.println(e+" = "+ r);
}
}

Multiplication (or division) together with addition requires priority, which means that you cannot continue to evaluate your expression from left to right.
Usually, computation parsers use the reversed polish notation (http://en.wikipedia.org/wiki/Reversed_Polish_notation) which gives you a tree representation of the mathematical expression. The wikipedia article contains many information as too how to use this.
Typically, you'll use the Shunting-yard algorithm to convert your infix (usual) notation to RPN, then you'll see how easy it is to evaluate an expression represented in the RPN.

Related

How to add power function to sigma

I've written this code that computes the sum of the positive divisors, and all the values have to be to the power of a.
For instance:
sigma(0,14) = 1^0 + 2^0 + 7^0 + 14^0 = 4;
sigma(2,12) = 1^2 + 2^2 + 3^2 + 4^2 + 6^2 + 12^2 = 210.
sigma(a, b).
I have tried different versions but I don't know how to add the power function.
try {
int a = Integer.parseInt(input1.getText());
int b = Integer.parseInt(input2.getText());
int result1 = 0;
for (int i = 2; i <= Math.sqrt(b); i++)
{
if (b % i == 0)
{
if (i == (b / i))
result1 += i;
else
result1 += (i + b / i);
}
}
result.setText(String.valueOf(result1 + b + 1));
}
}
In Java the ^ character means XOR.
The power function is provided by the Math.pow() method.
So 3^2 would be Math.pow(3, 2).
If you wanted to implement it yourself for integers, you could do it simply like this:
double power(int a, int b) {
int pow = (b < 0) ? -b : b;
double result = 1;
for (int i = 0; i < pow; i++) {
result *= a;
}
return (b < 0) ? 1 / result : result;
}
But I wouldn't do it myself. It gets a bit more complicated for floating points, and Java has a native underlying implementation which is much faster.
IntStream delivers beautiful concise calculation.
static int sigma(int exp, int num) {
IntStream.rangeClosed(1, num) // 1, ..., num
.filter(k -> num % k == 0) // Only divisors
.map(k -> pow(k, exp))
.sum();
}
static int pow(int k, int exp) {
if (exp == 0) {
return 1;
}
int squareRoot = pow(k, exp/2);
int n = squareRoot * squareRoot;
return (exp % 2) == 0 ? n : n*k;
}
The power calculation can be optimized by not using exp# multiplications of k but square roots.
For those interested in program transformation:
pow(k, exp) needs only to rely on exp with recursion to exp/2 (integer division). So you could turn the code inside out, have a vector of divisors,
and operate on that.
If you want to implement it without using Math.pow() you can simply follow the mathematical definition of the exponentiation for a positive exponent:
public static long exp(int a, int b){ //computes a^b
long result = 1;
for (int i = 0; i < b; i++) {
result *= a;
}
return result;
}
I would recommend that you use Java lambdas to accomplish what you're looking for.
Taking an input and returning a List of positive divisors seems useful on its own.
Raising every entry to a power could be done easily with a lambda.
Keep the two functions separate. Take a more functional approach.
Here is a simple code for you:
public static void main(String args[]) {
Scanner scanner = new Scanner(System.in);
List<Integer> listOfBs = new ArrayList<>();
System.out.println("Input your a");
int a = scanner.nextInt();
System.out.println("Input your b");
int b = scanner.nextInt();
int sqrt = (int) Math.sqrt(b);
for (int i = 1; i <= sqrt; i++) {
if (b % i == 0) {
listOfBs.add(i);
int d = b / i;
if (d != i) {
listOfBs.add(d);
}
}
}
int sigma = 0;
for(int e : listOfBs)
{
sigma += Math.pow(e,a);
}
System.out.println("Your sigma function is: "+sigma);
}
}

Check if string contains a character with for loop?

I am currently working on a simple code that will check if an user inputted String contains character(s) that are specified in the for loop.
My current code
import java.util.Scanner;
public class AutumnLeaves {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int G = 0;
int R = 0;
int Y = 0;
int B = 0;
String S = sc.nextLine();
for (int i = 0; i < S.length(); i++) {
if (S.contains("G")) {
G++;
} else {
if (S.contains("R")) {
R++;
} else {
if (S.contains("Y")) {
Y++;
} else {
if (S.contains("B")) {
B++;
}
}
}
}
}
int total = G + R + Y + B;
System.out.println(G/total);
System.out.println(R/total);
System.out.println(Y/total);
System.out.println(B/total);
}
}
As you can see, it checks if the string contains such characters and it will increase the counter of the character by one. However when I run it, I don't receive the results I predicted.
If I input GGRY, it outputs 1 0 0 0. When the desired out put is
0.5
0.25
0.25
0.0
Any help would be appreciated!
The problem is that S.contains returns true if the whole string contains the given character. S.charAt should solve your problem:
for (int i = 0; i < S.length(); i++) {
if (S.charAt(i) == 'G') G++;
else if (S.charAt(i) == 'R') R++;
else if (S.charAt(i) == 'Y') Y++;
else if (S.charAt(i) == 'B') B++;
}
Also, dividing integers will return an integer (rounded down). As such your output would always be 0 unless all the characters are the same. Just cast them to double before printing:
System.out.println((double) G/total);
System.out.println((double) R/total);
System.out.println((double) Y/total);
System.out.println((double) B/total);
Edit: As pointed out by Sumit Gulati in a comment, a switch statement will have better performance in Java 7. Also, as David Conrad pointed out using only ifs in the for loop would work too as the conditions are mutually exclusive.
Your earlier code S.contains("some character") was finding the index of the character in the entire string. Use S.charAt(i) to specifically find the index at ith location in the string.
Finally, you need to convert the integer to floating point in order to print output as floating values.
public class AutumnLeaves {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int G = 0;
int R = 0;
int Y = 0;
int B = 0;
String S = sc.nextLine();
for (int i = 0; i < S.length(); i++) {
if (S.charAt(i) == 'G') {
G++;
} else {
if (S.charAt(i) == 'R') {
R++;
} else {
if (S.charAt(i) == 'Y') {
Y++;
} else {
if (S.charAt(i) == 'B') {
B++;
}
}
}
}
}
int total = G + R + Y + B;
System.out.println(G * 1.0 / total);
System.out.println(R * 1.0 / total);
System.out.println(Y * 1.0 / total);
System.out.println(B * 1.0 / total);
}
}

how to get exponents without using the math.pow for java

This is my program
// ************************************************************
// PowersOf2.java
//
// Print out as many powers of 2 as the user requests
//
// ************************************************************
import java.util.Scanner;
public class PowersOf2 {
public static void main(String[] args)
{
int numPowersOf2; //How many powers of 2 to compute
int nextPowerOf2 = 1; //Current power of 2
int exponent= 1;
double x;
//Exponent for current power of 2 -- this
//also serves as a counter for the loop Scanner
Scanner scan = new Scanner(System.in);
System.out.println("How many powers of 2 would you like printed?");
numPowersOf2 = scan.nextInt();
System.out.println ("There will be " + numPowersOf2 + " powers of 2 printed");
//initialize exponent -- the first thing printed is 2 to the what?
while( exponent <= numPowersOf2)
{
double x1 = Math.pow(2, exponent);
System.out.println("2^" + exponent + " = " + x1);
exponent++;
}
//print out current power of 2
//find next power of 2 -- how do you get this from the last one?
//increment exponent
}
}
The thing is that I am not allowed to use the math.pow method, I need to find another way to get the correct answer in the while loop.
Powers of 2 can simply be computed by Bit Shift Operators
int exponent = ...
int powerOf2 = 1 << exponent;
Even for the more general form, you should not compute an exponent by "multiplying n times". Instead, you could do Exponentiation by squaring
Here is a post that allows both negative/positive power calculations.
https://stackoverflow.com/a/23003962/3538289
Function to handle +/- exponents with O(log(n)) complexity.
double power(double x, int n){
if(n==0)
return 1;
if(n<0){
x = 1.0/x;
n = -n;
}
double ret = power(x,n/2);
ret = ret * ret;
if(n%2!=0)
ret = ret * x;
return ret;
}
You could implement your own power function.
The complexity of the power function depends on your requirements and constraints.
For example, you may constraint exponents to be only positive integer.
Here's an example of power function:
public static double power(double base, int exponent) {
double ans = 1;
if (exponent != 0) {
int absExponent = exponent > 0 ? exponent : (-1) * exponent;
for (int i = 1; i <= absExponent; i++) {
ans *= base;
}
if (exponent < 0) {
// For negative exponent, must invert
ans = 1.0 / ans;
}
} else {
// exponent is 0
ans = 1;
}
return ans;
}
If there are no performance constraints you can do:
double x1=1;
for(int i=1;i<=numPowersOf2;i++){
x1 =* 2
}
You can try to do this based on this explanation:
public double myPow(double x, int n) {
if(n < 0) {
if(n == Integer.MIN_VALUE) {
n = (n+1)*(-1);
return 1.0/(myPow(x*x, n));
}
n = n*(-1);
return (double)1.0/myPow(x, n);
}
double y = 1;
while(n > 0) {
if(n%2 == 0) {
x = x*x;
}
else {
y = y*x;
x = x*x;
}
n = n/2;
}
return y;
}
It's unclear whether your comment about using a loop is a desire or a requirement. If it's just a desire there is a math identity you can use that doesn't rely on Math.Pow.
xy = ey∙ln(x)
In Java this would look like
public static double myPow(double x, double y){
return Math.exp(y*Math.log(x));
}
If you really need a loop, you can use something like the following
public static double myPow(double b, int e) {
if (e < 0) {
b = 1 / b;
e = -e;
}
double pow = 1.0;
double intermediate = b;
boolean fin = false;
while (e != 0) {
if (e % 2 == 0) {
intermediate *= intermediate;
fin = true;
} else {
pow *= intermediate;
intermediate = b;
fin = false;
}
e >>= 1;
}
return pow * (fin ? intermediate : 1.0);
}
// Set the variables
int numPowersOf2; //How many powers of 2 to compute
int nextPowerOf2 = 1; //Current power of 2
int exponent = 0;
/* User input here */
// Loop and print results
do
{
System.out.println ("2^" + exponent + " = " + nextPowerOf2);
nextPowerOf2 = nextPowerOf2*2;
exponent ++;
}
while (exponent < numPowersOf2);
here is how I managed without using "myPow(x,n)", but by making use of "while". (I've only been learning Java for 2 weeks so excuse, if the code is a bit lumpy :)
String base ="";
String exp ="";
BufferedReader value = new BufferedReader (new InputStreamReader(System.in));
try {System.out.print("enter the base number: ");
base = value.readLine();
System.out.print("enter the exponent: ");
exp = value.readLine(); }
catch(IOException e){System.out.print("error");}
int x = Integer.valueOf(base);
int n = Integer.valueOf(exp);
int y=x;
int m=1;
while(m<n+1) {
System.out.println(x+"^"+m+"= "+y);
y=y*x;
m++;
}
To implement pow function without using built-in Math.pow(), we can use the below recursive way to implement it. To optimize the runtime, we can store the result of power(a, b/2) and reuse it depending on the number of times is even or odd.
static float power(float a, int b)
{
float temp;
if( b == 0)
return 1;
temp = power(a, b/2);
// if even times
if (b%2 == 0)
return temp*temp;
else // if odd times
{
if(b > 0)
return a * temp * temp;
else // if negetive i.e. 3 ^ (-2)
return (temp * temp) / a;
}
}
I know this answer is very late, but there's a very simple solution you can use if you are allowed to have variables that store the base and the exponent.
public class trythis {
public static void main(String[] args) {
int b = 2;
int p = 5;
int r = 1;
for (int i = 1; i <= p; i++) {
r *= b;
}
System.out.println(r);
}
}
This will work with positive and negative bases, but not with negative powers.
To get the exponential value without using Math.pow() you can use a loop:
As long as the count is less than b (your power), your loop will have an
additional "* a" to it. Mathematically, it is the same as having a Math.pow()
while (count <=b){
a= a* a;
}
Try this simple code:
public static int exponent(int base, int power) {
int answer = 1;
for(int i = 0; i < power; i++) {
answer *= base;
}
return answer;
}

How to solve an expression from user input not using parentheses?

I'm trying to write a program that evaluates an expression the user inputs. I know I need to have separate methods so It evaluates multiplication and division first then adds the addition and subtraction afterwards. This is what I got so far. When I try anything involving multiplication or division, like 6*6, it will only print the first character, which would be just '6' in this instance. Any ideas?
import java.util.Scanner;
class Expressions {
String e;
void setExpressions(String exp) {
e = exp;
}
String evaluate() {
String n = "";
for (int i = 0; i < e.length(); i++)
if (e.charAt(i) == '*' || e.charAt(i) == '/') {
n += e.charAt(i);
}
else if (e.charAt(i) == '+' || e.charAt(i) == '/') {
evaluateMD();
n = "";
}
else
n += e.charAt(i);
return n;
}
int evaluateMD () {
int r = 1;
int n = 0;
char op = '*';
for (int i = 0; i < evaluate().length(); i++)
if (evaluate().charAt(i) == '*' || evaluate().charAt(i) == '/') {
if (op == '*')
r *= n;
else
r /= n;
n = 0;
op = evaluate().charAt(i);
}
else if (evaluate().charAt(i) == '*' || evaluate().charAt(i) == '/')
n = 0;
else //digits
n = n*10 + (evaluate().charAt(i)-'0');
if (op == '+') //last operation
r *= n;
else
r /= n;
return r;
}
int evaluateAS() {
//e has +, - only, multiple digit numbers
int r = 0;
int n = 0;
char op = '+';
for (int i = 0; i < e.length(); i++)
if (e.charAt(i) == '+' || e.charAt(i) == '-') {
if (op == '+')
r += n;
else
r -= n;
n = 0;
op = e.charAt(i);
}
else if (e.charAt(i) == '*' || e.charAt(i) == '/')
n = 0;
else //digits
n = n*10 + (e.charAt(i)-'0');
if (op == '+') //last operation
r += n;
else
r -= n;
return r;
}
}
public class hw10 {
public static void main(String[] args) {
Scanner in = new Scanner (System.in);
Expressions myE = new Expressions();
System.out.print("Enter E:");//E for expression
String e = in.next();
myE.setExpressions(e);
//int r = myE.evaluate1();
int r = myE.evaluateAS();
System.out.println(e+" = "+r);
}
}
If I needed to write arithmetic expressions parser, I would use pretty simple approach: get the input from user, translate it into reverse polish notation (take a look at section named Shunting-yard algorithm), and evaluate it.
Robert Lafore in his "Data Structures and Algorithms in Java" has pretty easy explanation of both algorithms - translation from infix to RPN and evaluation of expressions written in RPN, with the source code, so you can see how it can be implemented. After you read it, it'll be easy to mix both algorithms into one - take a look at one of my questions on this topic.
Changing the line
if (op == '+') //last operation
in the evaluateMD method to
if (op == '*') //last operation
,changing the return type of the method to double and making r and n doubles produces better results for the evaluateMD, but really you're overall procedure needs an overhaul, if not complete abandonment.
I think your it would be better if your evaluate method only returned the answer to the calculation.
It would only ever need to store 2 values at most: (in the case that you have an AS operation you would store it if the next operator was MD since MD needs to be evaluated first, but once the MD operation (which could involve more than one operator or more than one instance of the same operator i.e. 4*5*6 or 4/3*2) is computed you can then perform the 'waiting' AS immediately. For MD operations, you'd just store the latest update each time, as you almost had working in your evaluateMD method (which I think works with the modification I put at the top. If it doesn't feel free to ask me about it as I did make a few other changes).
This is an improvement on the method you were attempting, but as I said there may well be methods which are better still mentioned in other answers.

Find Perfect Number from 1-9999. Exercise from The Art and Science of Java

I am trying to find the perfect number by find out all their divisors. If their sum is equal to the number, then print out the the number. But apparently it's not working.
import acm.program.*;
public class PerfectNumber extends ConsoleProgram{
public void run() {
for (int n = 1; n < 9999; n++) {
for (int d = 2; d < n - 1; d++) {
//d is the potential divisor of n, ranging from 2 to n-1,//
//not including 1 and n because they must be the divisors.//
if (isPerfectNumber(n,d))
print(n );
}
}
}
//method that determines if n is perfect number.//
private boolean isPerfectNumber(int n, int d) {
while (n % d == 0) {
int spd = 1;
spd += d;
if (spd == n) {
return true;
} else {
return false;
}
}
}
}
Looking at the code in your case will return false most of the times. I think what you were looking for is a bit wrong.
Because d is smaller than n, and n divided by d will always be grater than 0. Also in that loop you never change the value of d.
A solution might be:
public void run() {
for (int n = 1; n < 9999; n++)
{ spd=1;
for (int d = 2; d <= n/2; d++) { //no need to go further than n/2
//d is the potential divisor of n, ranging from 2 to n-1,//
if(n%d==0) spd+=d; //if n divides by d add it to spd.
}
if(spd==n) print(n);
}
Try this and let me know if it works for you.
I find something cool here : http://en.wikipedia.org/wiki/List_of_perfect_numbers. You should the much faster using this formula: 2^(p−1) × (2^p − 1). You can see the formula better on the wikilink.
Method isPerfect should probably be something like that:
public static boolean isPerfect(int number) {
int s = 1;
int d = number / 2;
for(int i = 2; i <= d; i++) {
if (number % i == 0) s += i;
}
return s == number;
}

Categories