How to prevent value from changing automatically in java - java

I'm very new to Java and stackoverflow so I'm sorry if I seem ignorant but I wrote this program to multiply two numbers together using the Russian Peasant multiplication algorithm. The complete program includes far more operations and is hundreds of lines of code but I only included what I thought was necessary for this particular method. I have a test harness so I know that all the submethods work correctly. The problem that I'm struggling with though is the 3rd line where I'm adding factor1 to the product. The values add correctly but then when factor1 is multiplied by 2 in the 5th line then the value that was added to product in the 3rd line also gets doubled resulting in an incorrect product value. How can I make sure that when factor 1 is doubled that it doesn't carry backwards to the product term?
while (Long.parseLong(factor2.toString()) >= 1) {
if (factor2.bigIntArray[0] % 2 == 1) {
product = product.add(factor1);
}
factor1 = factor1.multiplyByTwo();
factor2 = factor2.divideByTwo();
}

I think in your method multiplyByTwo you use code
`datamember=datamember*2;`
rather than that try doing this
return new FactorClass(datamember*2);
so it doesnt change the added value.
it would be better if u could show the mulTiplyByTwo method code since that is where your actually are getting the changed value.

Related

Is there a better method for randomizing functions besides Random?

I have 2 strings in an array. I want there to be a 10% chance of one and 90% chance to select the other. Right now I am using:
Random random = new Random();
int x = random.nextInt(100 - 1) + 1;
if (x < 10) {
string = stringArray(0);
} else {
string = stringArray(1);
}
Is this the best way of accomplishing this or is there a better method?
I know it's typically a bad idea to submit a stack overflow response without submitting code, but I really challenge this question of " the best way." People ask this all the time and, while there are established design patterns in software worth knowing, this question almost always can be answered by "it depends."
For example, your pattern looks fine (I might add some comments). You might get a minuscule performance increase by using 1 - 10 instead of 1 - 100, but the things you need to ask yourself are as follows :
If I get hit by a bus, is the person who is going to be working on the application going to know what I was trying to do?
If it isn't intuitive, I should write a comment. Then I should ask myself, "Can I change this code so that a comment isn't necessary?"
Is there an existing library that solves this problem? If so, is it FOSS approved (if applicable) / can I use it?
What is the size of this codebase eventually going to be? Am I making a full program with microservices, a DAO, DTO, Controller, View, and different layers for validation?
Is there an existing convention to solve my problem (either at my company or in general), or is it unique enough that I can take my own spin on it?
Does this follow the DRY principle?
I'm in (apparently) a very small camp on stack overflow that doesn't always believe in universal "bests" for solving code problems. Just remember, programming is only as hard as the problem you're trying to solve.
EDIT
Since people asked, I'd do it like this:
/*
* #author DaveCat
* #version 1.0
* #since 2019-03-9
* Convenience method that calculates 90% odds of A and 10% odds of B.
*
*/
public static String[] calculatesNinetyPercent()
{
Random random = new Random();
int x = random.nextInt(10 - 1 ) + 1
//Option A
if(x <= 9) {
return stringArray(0);
}
else
{
//Option B
return stringArray(1);
}
}
As an aside, one of the common mistakes junior devs make in enterprise level development is excessive comments.This has a javadoc, which is probably overkill, but I'm assuming this is a convenience method you're using in a greater program.
Edit (again)
You guys keep confusing me. This is how you randomly generate between 2 given numbers in Java
One alternative is to use a random float value between 0..1 and comparing it to the probability of the event. If the random value is less than the probability, then the event occurs.
In this specific example, set x to a random float and compare it to 0.1
I like this method because it can be used for probabilities other than percent integers.

Parsing of math expression gives wrong tree

So the code is rather complicated so ill try to do some neat pseudo code that covers the most important issues. I'm trying to parse a math expression. For example: 1-5*(-2)+3 = 14
The syntax that im using is:
expression = term OR term+expression OR term-expression
term = factor OR factor*term OR factor/term
factor = number OR -factor OR (expression)
I have written a piece of code which checks if an expression follows this syntax and it works well for checking the expressions but not for calculating it.
The pseudo code goes something like:
double readExpression()
number = readTerm()
if token == +
number2 = readExpression()
return number + number2
else if token == -
number2 = readExpression()
return number - number2
else
return number
...
(The code for readTerm() is identical to readExpression() in structure)
...
double readFactor()
if token == number
return number
else if token == -
number = readFactor()
return (-1)*number
else if token == (
number = readExpression()
return number
else raise exception
If I do the above calculation with this code it will give me a tree that looks like this:
So anyway, as you matematicians have figured out byt now, the expression should give 14 and not 8 as the tree suggests. I have noticed the that the problem arises when there are minus-signs in front of expressions since affect the whole right term i this problem whilst they should only affect the middle-term.
Ive been thinking like crazy for weeks and thought about solutions for this and looked at other codes and so on. Please dont toss a bunch of links on me if they are not really really simple and good since ive been browsing alot myself on tree traversals and other relevant topics.
What could i do at this stage? As I said, my program can tell if its right or wrong. So now I only need to parse a correct expression. Should I write another class for the parsing of the correct expression? Is it easier? Anyway I dont see how that code would look different than this.
Yes I would parse the equation, it just looks like you miss a key part of the order of operations/parsing. You need to include an additional check for double negatives.
The key factor here is that: In a situation with two identical operators then the left most operation is always carried out first.
First lets narrow down the issue.
This 1-5*(-2)+3 is equal to 1--10+3.
Now for our purposes lets assign a positive to the first operator because it helps illustrate a point:
1--10+3 is the same as +1--10+3
Now if we where to run +1--10+3 through a correct parser we would know that this -- is equal to + but only when used in the following situation:
+X--Y = X+Y
So now our parser has turned the original expression of 1--10+3 into 1+10+3 and we know that is equal to 14.
So all up: Yes you need a parser, but pay special attention to how +X--Y and X+Y work.
Also take a look at this answer: https://stackoverflow.com/a/26227947/1270000

Clarification on Mystery

I have just started taking a Computer Science class online and I am quite new to Programming(a couple of week's worth of experience). I am working on an assignment, but I do not understand what a mystery method is. I have yet to find an answer that I can wrap my head around online, in my textbook, or from my professor. Any explanation using this code as an example would also be greatly appreciated!
This is the equation where I saw it in:
public static void mystery1(int n) {
System.out.print(n + " ");
if (n > 0) {
n = n - 5;
}
if (n < 0) {
n = n + 7;
} else {
n = n * 2;
}
System.out.println(n);
}
If anybody can help, that would be amazing! Thank you!
First of all, I voted your question up because I think it's a valid question for someone who is just beginning in computer programming, and I think that some people fail to understand the significance and purpose of Stack Overflow, which is to help programmers in times of need.
Secondly, I think that the couple of users that have commented on your post are on the right track. I have personally never heard of a mystery method, so I think the goal here is for you to simply figure out what the method does. In this case, the method takes a parameter for int 'n'. This means that if, at any point in the application, the 'mystery1()' method is called, an integer will have to be passed as the variable.
Let's say that a user enters the number '9'. The method would be called by the code mystery1(9). This would then run the first part of the 'if' statement, because n is greater than 0. So, n would be equal to n - 5, or 9 - 5, which is 4. (So, n=4.)
I hope my answer was somewhat helpful to you. Take care.
Your assignment is probably to figure out what this method does. More specifically, what does it print to the screen. I'll walk you through how to figure this out.
You have a function, also called a methood, called mystery1. A function is just a named block of code that you can use throughout other pieces of code. This function takes an integer argument called n. Let's assume n=12 for this example.
The first thing that happens in your function when it is called is that n is printed out via the System.out.print method. Notice that it prints a blank space after it. Notice also at the end it prints another value of n that gets assigned within the method. So the method is going to print "12 ?" without the double quotes. The question mark is what we have to figure out. The code says if n > 0 then n = n-5. Since 12 is greater than 0, n gets the new value of 7. The next if statement says if n is less than 0, n gets assigned n+7. But it is not less than zero, it is 7 at this point, so we move to the else statement. In this statement n gets multiplied by 2 which is 14. So the last statement prints 14.
So for an input value of 12 this method prints:
12 14
I hope this helps. If not, please give more detail about your assignment and what you don't understand about my explanation.
The point of this kind of exercise is that you are given a method, but they don't tell you what it does (hence the "mystery"). You are supposed to figure out what it does on your own (like "solving the mystery"). It doesn't mean that the method is special in any way.
Say I give you a "mystery" method like this:
public static void mystery(int n) {
System.out.println(n+1);
}
You would "solve the mystery" by telling me that this method prints out the number that comes after n. Nothing else is special here.
In the example you gave, your job would be to tell me why the method prints out 0 0 when n = 0, or 6 2 when n = 6.
I think the usage of the term "mystery method" is rather misleading, as it has clearly made you (and many, many, many others) believe that something about these methods is special and something that you need to learn about. There isn't anything special about them, and there's nothing to learn.
I think a lot of people would understand this better if instructors just said "tell me what this method does" instead of trying treat students like 5 year olds by saying "Here's a mystery method (ooh, fancy and entertaining). Can you play detective and solve the mystery for me?"

How to reduce an algorithm into smaller parts so I can scale it?

I have updated this question(found last question not clear, if you want to refer to it check out the reversion history). The current answers so far do not work because I failed to explain my question clearly(sorry, second attempt).
Goal:
Trying to take a set of numbers(pos or neg, thus needs bounds to limit growth of specific variable) and find their linear combinations that can be used to get to a specific sum. For example, to get to a sum of 10 using [2,4,5] we get:
5*2 + 0*4 + 0*5 = 10
3*2 + 1*4 + 0*5 = 10
1*2 + 2*4 + 0*5 = 10
0*2 + 0*4 + 2*5 = 10
How can I create an algo that is scalable for large number of variables and target_sums? I can write the code on my own if an algo is given, but if there's a library avail, I'm fine with any library but prefer to use java.
One idea would be to break out of the loop once you set T[z][i] to true, since you are only basically modifying T[z][i] here, and if it does become true, it won't ever be modified again.
for i = 1 to k
for z = 0 to sum:
for j = z-x_i to 0:
if(T[j][i-1]):
T[z][i]=true;
break;
EDIT2: Additionally, if I am getting it right, T[z][i] depends on the array T[z-x_i..0][i-1]. T[z+1][i] depends on T[z+1-x_i..0][i-1]. So once you know if T[z][i] is true, you only need to check one additional element (T[z+1-x_i][i-1]) to know if T[z+1][i-1] will be true.
Let's say you represent the fact whether T[z][i] was updated by a variable changed. Then, you can simply say that T[z][i] = changed && T[z-1][i]. So you should be done in two loops instead of three. This should make it much faster.
Now, to scale it - Now that T[z,i] depends only on T[z-1,i] and T[z-1-x_i,i-1], so to populate T[z,i], you do not need to wait until the whole (i-1)th column is populated. You can start working on T[z,i] as soon as the required values are populated. I can't implement it without knowing the details, but you can try this approach.
I take it this is something like unbounded knapsack? You can dispense with the loop over c entirely.
for i = 1 to k
for z = 0 to sum
T[z][i] = z >= x_i cand (T[z - x_i][i - 1] or T[z - x_i][i])
Based on the original example data you gave (linear combination of terms) and your answer to my question in the comments section (there are bounds), would a brute force approach not work?
c0x0 + c1x1 + c2x2 +...+ cnxn = SUM
I'm guessing I'm missing something important but here it is anyway:
Brute Force Divide and Conquer:
main controller generates coefficients for say, half of the terms (or however many may make sense)
it then sends each partial set of fixed coefficients to a work queue
a worker picks up a partial set of fixed coefficients and proceeds to brute force its own way through the remaining combinations
it doesn't use much memory at all as it works sequentially on each valid set of coefficients
could be optimized to ignore equivalent combinations and probably many other ways
Pseudocode for Multiprocessing
class Controller
work_queue = Queue
solution_queue = Queue
solution_sets = []
create x number of workers with access to work_queue and solution_queue
#say for 2000 terms:
for partial_set in coefficient_generator(start_term=0, end_term=999):
if worker_available(): #generate just in time
push partial set onto work_queue
while solution_queue:
add any solutions to solution_sets
#there is an efficient way to do this type of polling but I forget
class Worker
while true: #actually stops when a stop work token is received
get partial_set from the work queue
for remaining_set in coefficient_generator(start_term=1000, end_term=1999):
combine the two sets (partial_set.extend(remaining_set))
if is_solution(full_set):
push full_set onto the solution queue

I would like the Arrays to remember it all

This is about my assignment so I would appreciate generic answers with explanation.
I have a for-loop which I have to make for an online ordering system. The for-loop and ordering all works fine but if the same item is put in twice, then it forgets the previous order for the same item and only remembers the latest one. I am required to use simple arrays and for-loops so I would appreciate if the solution/help was also of this basic level.
My code looks something like this (NOTE: The following is just an example of what part of the loop looks like--this is not a complete program):
for (int i = 0; i < 3; i++) { //I changed the loop so there's no confusion about
//what I am actually asking about.
if (order.equalsIgnoreCase(computer) {
int price = quantity[i] + itemcode;
}
}
To explain further, this loop and the if statement work perfectly if a certain item is only ordered once. But if the user enters, say, an order for a computer once and then after 3 more orders, orders another computer, then the output does not add the previous order in the new order but only remembers the latest one.
I would appreciate any work around suggested for this but again, since this is for my studies, I would appreciate explanations rather than direct solutions.
Please ask me questions in case this is not clear.
"Forgets" suggests that you are overwriting something in your code rather than, say, just incrementing. Go through your code, see what parts of it gets reset when you place a new order. For instance, if you are doing
quantity[1] = getNumberFromUser("How many apples?");
then this would obviously erase the old value each time. If you want to merely increment the number of apples, do something like
quantity[1] += getNumberFromUser("How many apples?");
Another general advice is to use print statements to debug your code. That way you can see for yourself what really happens. Learning to use a real debugger would also be of great benefit.
if you have two or more typres of products and want to calculate the price for all the orders together then you can try the following code,, i think thats very simple,,
int price=0;
for (int i = 0; i < 3; i++) { //I changed the loop so there's no confusion about
//what I am actually asking about.
if (order.equalsIgnoreCase(computer) {
price += quantity[i] + itemcode; //use the previous value of price
}
}
or else if you want to have history for each product separately then you have to try the same with a array of price for each product type..
If you cant get the answer then comment here,,

Categories

Resources