In regards to continues subtraction - java

I made a swing calculator as part of homework that I did and would like some advice on continues subtraction in particular.
With continues adding up it is straight forward enough(i.o.w. adding the operands and then to continue adding from there onwards). This is what I did.
if(totalCount > 1)
{
if(sbOne.length() > 0)
{
operandOne = Double.parseDouble(sbOne.toString());
}
else
{
operandOne = 0;
}
if(sbTwo.length() > 0)
{
operandTwo = Double.parseDouble(sbTwo.toString());
}
else
{
operandTwo = 0;
}
result = operandOne + operandTwo;
totalResult += result;
screenResult = Double.toString(totalResult);
txtDisplay.setText(screenResult);
notCalculate = true;
sbOne.setLength(0);
sbTwo.setLength(0);
How can I achieve the same result by subtracting one operand from another and then to continue subtracting from there onwards.

Your code seems confusing, particularly as it is incomplete and not compilable. My interpretation of your code is as follows: you have two presumably positive values which you add together, whereupon you add that sum to a total which you already have. My interpretation of your question is as follows: you want to subtract that sum from the total. A solution to that is as Hot Licks said, which is just to use the following operation: totalResult -= result;. If you want to make it possible to decide whether or not you want to add or subtract, add a Boolean flag, namely:
/*somewhere in your code to determine whether you add or subtract,
have a button or something which changes this value.
*/
boolean isAdding = true;
//...
//button pressed
isAdding = false;
//...
//your calculating code goes here
if(isAdding)
totalResult += result;
else
totalResult -= result;
//all of the other stuff

Related

Why do I get no output out of println in this case?

I tried this a lot, and debugged it a few times, everything seems to be working and largest prime does indeed become the largest prime even if it takes rather long.
I can't get the printed value from System.out.println. I could find it through the debugger but the value is too high to find fast just holding down step over.
It compiles as well so I am stumped about what's the issue here. I would be very happy to know what I did wrong.
Edit: The reason why I wrote this code in the first place is because in the site project euler it asked for the largest prime value that when divided with the value of primer gave a whole number.
Is there a way at least that would allow me to make it faster with the same value? this seems rather impractical.
package unit5;
public class Primefinder { public static void main(String[] args)
{
double primer = 600851475143d;
double largestprime = 0;
Boolean ifprime = false;
for(double x = 2d; x < primer; x++)
{
for(double z = 2d; z<x; z++)
{
if( (x%z == 0) && (z != x) )
{
ifprime = false;
break;
}
else {
ifprime = true;
}
}
if((ifprime != false) && (x > largestprime))
{
largestprime = x;
}
ifprime = false;
}
System.out.print(largestprime);
}
}
for other questions you might ask everywhere, please tell us that what is the purpose of your code. this way it is easier to get the fault.
the code you have written above runs completely but the numbers you have used are too big so you need to wait a lot, so that compiler be able to reach to this line:
System.out.print(largestprime);
use lower numbers (at least for test) or wait properly.
Your 'primer' Value is very big.
So, loop is taking very much time to reach at '600851475143' value.
Wait Sometime and it with show largest prime number

Better approach for multiple if else statements?

I have a program that takes in 3 numbers (feet, inches, sixteenths) then multiplies them by x. Upon starting to write the output part, I ran into needing:
if (sixteenths4<16) {
sixteenths5=sixteenths4;
inches6=0;
}else if (16<=sixteenths4) {
sixteenths5=sixteenths4-16;
inches6=1;
}else if (32<=sixteenths4) {
sixteenths5=sixteenths4-32;
inches6=2;
}else if (48<=sixteenths4) {
sixteenths5=sixteenths4-48;
inches6=3;
} else {
sixteenths5=sixteenths4-64;
inches6=4;
}
I realize the last else is redundant as it will never happen. My issue is that since the total sixteenths could exceed 4-5 hundred, that would be a lot of if else blocks. Is there a better way to do this?
Remive all the if/else statements and use integer arithmetic instead.
This is equivalent code for all your code:
sixteenths5 = sixteenths4 % 16;
inches6 = sixteenths4 / 16;

Efficiently parse single digit arithmetic expression

How would you efficiently (optimizing for runtime but also keeping space at a minimum) parse and evaluate a single digit arithmetic expression in Java.
The following arithmetic expressions are all valid:
eval("-5")=-5
eval("+4")=4
eval("4")=4
eval("-7+2-3")=-8
eval("5+7")=12
My approach is to iterate over all elements, keeping track of the current arithmetic operation using a flag, and evaluate digit by digit.
public int eval(String s){
int result = 0;
boolean add = true;
for(int i = 0; i < s.length(); i++){
char current = s.charAt(i);
if(current == '+'){
add = true;
} else if(current == '-'){
add = false;
} else {
if(add){
result += Character.getNumericValue(current);
} else {
result -= Character.getNumericValue(current);
}
}
}
return result;
}
Is this the only optimal solution? I have tried to use stacks to keep track of the arithmetic operator, but I am not sure this is any more efficient. I also have not tried regular expressions. I only ask because I gave the above solution in an interview and was told it is sub-optimal.
This seems a bit more compact. It certainly requires fewer lines and conditionals. The key is addition is the "default" behavior and each minus sign you encounter changes the sign of what you want to add; provided you remember to reset the sign after each addition.
public static int eval(String s){
int result = 0;
int sign = 1;
for(int i = 0; i < s.length(); i++){
char current = s.charAt(i);
switch (current)
{
case '+': break;
case '-': sign *= -1; break;
default:
result += sign * Character.getNumericValue(current);
sign = 1;
break;
}
}
return result;
}
As a note, I don't think yours produces correct results for adding a negative, e.g., "4- -3". Your code produces 1, rather than the correct value of 7. On the other hand, mine allows expressions such as "5+-+-3", which would produce the result 8 (I suppose that's correct? :). However, you didn't list validation as a requirement and neither of us are checking for sequential digits, alpha characters, white space, etc. If we assume the data is properly formatted, the above implementation should work. I don't see how adding data structures (such as queues) could possibly be helpful here. I'm also assuming just addition and subtraction.
These test cases produce the following results:
System.out.println(eval("1+2+3+4"));
System.out.println(eval("1--3"));
System.out.println(eval("1+-3-2+4+-3"));
10
4
-3
You need to lookup up 'recursive descent expression parser' or the Dijkstra shunting-yard algorithm. Your present approach is doomed to failure the moment you have to cope with operator precedence or parentheses. You also need to forget about regular expressions and resign yourself to writing a proper scanner.

How can I shorten an algorithm that employs different scenarios with similar code?

I have developed a program that solves kinematic equations in elementary physics. To solve, one needs 3 out of a possible 5 variables. There are 10 different combinations of what 3 variables are known. I coded 10 scenarios similar to the two blocks of code below
// If we have acceleration, final velocity, and initial velocity
if (varEntered[0] == true && varEntered[1] == true && varEntered[2] == true)
{
double acceleration = knownVariables[0]; //Setting acceleration
double finalVelocity = knownVariables[1]; //Setting finalVelocity
double initVelocity = knownVariables[2]; //Setting initVelocity
double time = ((finalVelocity - initVelocity)/acceleration); //Finding time using an equation
double distance = ((finalVelocity + initVelocity)*((0.5)*time)); //Finding distance using an equation
System.out.println("The time is " + time + " seconds"); //Printing time
System.out.println("The distance is " + distance + " meters"); //Printing distance
}
//If we have distance, final velocity, initial velocity
if (varEntered[3] == true && varEntered[1] == true && varEntered[2] == true)
{
//Known variables
double distance = knownVariables[3]; //Acceleration
double finalVelocity = knownVariables[1]; //Final Velocity
double initVelocity = knownVariables[2]; //Initial Velocity
// Unknown variables
double time = (distance/((0.5)*(finalVelocity + initVelocity))); //Time
double acceleration = ((finalVelocity - initVelocity)/time); //Acceleration
System.out.println("The time is " + time + " meters/second"); //Printing time
System.out.println("The acceleration is " + acceleration + " meters/second^2"); //Printing distance
}
These seem very similar, but are different scenarios. As a programming beginner, I am wondering if the algorithm I use can be modified to shorten the code. If any more info is needed I will be more than happy to provide.
You should define a function that accepts three numbers and performs the general calculation.
For a starter, try this tutorial. Then you can call your function twice, each time with different sets of variables.
I would use a Map and do something like this (warning: pseudocode):
import java.util.HashMap;
import java.util.Map;
Map<String,double> map=new HashMap<String, double>();
Initialize the map with all the values that are known, e.g.:
map.put("initVelocity", 0.35);
Then you can define the following function:
void calculateValues(Map<double,String> map){
if( map.containsKey("initVelocity") && map.containsKey("finalVelocity") && map.containsKey("acceleration")){
map.put("time",((map.get("finalVelocity") - map.get("initVelocity")/map.get("acceleration"));
}
add all the other algorithms here in the same way!!!
}
This function takes the values that are already defined in the HashMap and tries to calculate the missing parameters. It will often be necessary to call it multiple times on a map until all parameters are set. You could do something like:
while( the map has not all values set){
calculateValues(map);
}
Also, you could make sure (by adding this condition to the if-statements) that any of the algorithms is called only if the resulting values are not set yet. But don't worry too much about that.
From what I noticed, it seems each variable is associated with a number. You can eliminate all the possible scenarios completely and have if conditions on each of the five variables; through this identify the 3 variables first and initialize the local variables. They are independent of each other when assigned, so there's no reason to make that many combinations. This will shorten the code by a lot.
The next step is to shorten the number of combinations you have. The best thing I can think of is finding out the two values you need to compute and using the formulas, in other words another block of if else statements. Here's what the code would look like:
//initialize all to 0
double acceleration = 0;
double distance = 0;
double finalVelocity = 0;
double initVelocity = 0;
double time = 0;
//place the proper values for each
if (varEntered[0] == true){
acceleration = knownVariables[0];
}
if (varEntered[1] == true){
finalVelocity = knownVariables[1];
}
if (varEntered[2] == true){
initVelocity = knownVariables[2];
}
if (varEntered[3] == true){
distance = knownVariables[3];
}
if (varEntered[4] == true){
time = knownVariables[4];
}
// now you have 10 cases
if(varEntered[0] == false && varEntered[1] == false){
//use the formulas here
} else if (varEntered[0] == false && varEntered[2] == false){
//use other formula here
}// repeat for the next 8, with each time you change the condition and formulas
//like you have it. Also, I noticed that you missed the else in your conditionals;
//it is more efficient if you use if-else clauses when only one should execute every time you run the code.
Hope this helps.
Feel free to copy this out, fill the rest and try it out.
If you're careful with your dependencies, you can get away with 5 cases with 1 calculation each instead of 10 cases with 2 calculations each. To do this, you have to make sure that no two variables directly depend on each other. If that were to happen, then you would be out of luck when both of the variables are unknown.
One way to do this is to take your list of variables and calculate each variable in terms of the following three (wrapping around when you reach the end of the list), as in the following example. In this example, solveAll takes an array of doubles with the unknowns set to Double.MAX_VALUE, and it sets the unknowns to the correct values. (If there are more than two unknowns, you'll get an infinite recursion.)
// Really should use enum instead of constant ints, and an EnumMap instead of an array.
public final static int ACCELERATION = 0;
public final static int FINALVELOCITY = 1;
public final static int INITVELOCITY = 2;
public final static int DISTANCE = 3;
public final static int TIME = 4;
private double[] vars;
public void solveAll(double[] vars) {
this.vars = vars;
for (int i=ACCELERATION; i<=TIME; i++) {
get(i);
}
}
private double get(int v) {
if (vars[v] != Double.MAX_VALUE) {
return vars[v];
}
switch (v) {
case ACCELERATION:
return (vars[ACCELERATION] = (get(FINALVELOCITY)*get(FINALVELOCITY) - get(INITVELOCITY)*get(INITVELOCITY)) / (2*get(DISTANCE)));
case FINALVELOCITY:
return (vars[FINALVELOCITY] = 2*get(DISTANCE)/get(TIME) - get(INITVELOCITY));
case INITVELOCITY:
return (vars[INITVELOCITY] = get(DISTANCE)/get(TIME) - get(ACCELERATION)*get(TIME)/2);
case DISTANCE:
return (vars[DISTANCE] = (get(FINALVELOCITY) - get(ACCELERATION)*get(TIME)/2) * get(TIME));
case TIME:
return (vars[TIME] = (get(FINALVELOCITY) - get(INITVELOCITY)) / get(ACCELERATION));
}
return Double.MAX_VALUE; // Bad variable index
}

"If" statement alternatives

I'm doing my homework, and am stuck on some logic (I think I used that term correctly?). I'm writing an application that shows 12 buttons numbered 1-12, 2 pictures of dice, and a Roll button.
The player rolls the dice (2, 6 sided die) and whatever number(s) he gets, he can use to "cover" some of the twelve numbers. For example, let's say he rolls the dice and gets a 3 and a 5. He gets to choose whether to cover the 3 and the 5, or the total of the two numbers - 8 (Did I mention I'm a math wiz?).
The goal of the game is to cover all the numbers using the least amount of rolls.
The problem I'm having is with, what I believe to be, the if statements:
if (die1 == 3 && die2 == 5) {
player can cover 3 and 5, or 8, but not both
}
Now, I think this works, but if I wrote all this out it would be 36 if statements (give or take zero). Is there an easier way?
By your description I think the player can select die1, die2 or die1 + die2, so to see if the user selected a valid value you need just one if.
if (cover == die1 or cover == die2 or cover == ( die1 + die2)) {
//valid..
}
no if statement needed. player can cover die1 and die2 or die1+die2
This is a good example to use a switch case, IMO.
That'd be 2 switchs which have 6 cases each.
Don't check until the player tries to cover something. By only validating the input you simplify everything down to one if statement.
If you do need to know all possibilities (maybe to show the player possible moves), then ... you still don't need all those if statements. Simply highlight the buttons that match the dice roll and only accept those as input; you'll want to index them in an array or map by their value (e.g. "1") as a way to retrieve them.
You know with two dice you always have three covering options. Presumably elsewhere in code you're going to compare your covered options with numbers. Something like
int[] covered = { die1, die2, die1+die2 };
// ... other stuff
if (comparisonValue > 6) {
// maybe do special stuff since this uses both dice
if (comparisonValue == covered[2]) {
// covered/coverable behavior
} else {
// not
}
} else {
// maybe do special stuff since this only uses one die
if (comparisonValue == covered[0] || comparisonValue == covered[1]) {
// covered/coverable behavior
} else {
// not
}
}
gives you first what's covered, then simple use of it. You could also foreach over the array to do stuff for the covered numbers, ala
for (int c : covered) {
// do stuff with c because it's covered
}
That's fairly fragile, but the flexible answer (e.g., dumping the outcomes into Collection) is way overkill for 6-sided, integer face dice, and the really flexible answer (e.g., accommodating a variable number of dice, specialized combination of faces into outcomes) is like nuclear armageddon for this particular problem.
EDIT for your particular problem, I'd do something like
// start new turn, disable all buttons
// get rolls
int[] coverable = { die1, die2, die1+die2 };
for (int covered : coverable ) {
// enabled covered button
}
If the player can change which of the 1-12 are covered by previous rolls based on a new outcome, well, then you could be in for some fun depending on how much help you want to give them.
I would probably create 2 new objects and use them with a lookup table, like so:
class TossResult{
int firstDie;
int secondDie;
}
Class Coverage{
TossResult tossResult;
int getThirdNumber(){
return tossResult.firstDie + tossResult.secondDie;
}
}
Then on application start-up, populate your map:
HashMap<TossResult, Coverage> lookup = new HashMap<>();
for (int i = 0, i < SIDES_ON_DIE; i++){
for (int j = 0, j < SIDES_ON_DIE; j++){
TossResult tempResult = new TossResult(i,j);
Coverage tempCoverage = new Coverage(tempResult);
lookup.put(tempResult, tempCoverage);
}
}
After a user rolls the dice, create a new TossResult and do a lookup.get(tossResult)
You could also create an array of 12 ints or bools. Initialize all 12 elements (say to 0 or false). Then for each role you can do something lik:
if (false == myArray[die1Value] && false == myArray[die2Value]) {
myArray[die1Value] = true;
myArray[die2Value] = true;
} else if (false == myArray[die1Value + die2Value]) {
myArray[die1Value + die2Value]
} else if (false == myArray[die1Value] || false == myArray[die2Value]) {
if (false == myArray[die1Value]) {
myArray[die1Value] = true;
}
if (false == myArray[die2Value]) {
myArray[die2Value] = true;
}
} else {
// all 12 covered
}
And certainly you can refactor this code some more.
The stated goal "The goal of the game is to cover all the numbers using the least amount of rolls." is not doable, really. The best you can do is to use probabilities to know if, for instance, you should cover on a roll of 1 and 2, a 1 and 2, or 3 first:-)

Categories

Resources