Does using the Random class "unnecessarily complicate" things? [closed] - java

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 7 years ago.
Improve this question
I handed in an assignment recently, for my Computer Science course. In it I used the Random classover the Math.random() method in order to generate random numbers. My lecturer marked me down for this, stating that it was an "unnecessary complication" and that I should avoid importing classes when not absolutely needed.
I've nothing against her for this, and I accept that this is her preferred method that does have it's merits, but I would appreciate the opinion of a wider (perhaps more experienced) group- since Math.random() calls the Random class anyway and (afaik) creates a new Random object each time the method is called, wouldn't it make sense to just cut out the middleman?
Thanks

Math.random() does use Random, but it uses a single instance.
However since Math.random() is equivalent to Random.nextDouble(); which is usually not very useful, it would be foolish to use it instead of the Random class, which has plenty of convenience methods that make your intention clear and bugs less likely, as demonstrated in the following snippet.
int x = (int)(Math.random() * 100); // Without parentheses you'll always get 0
int y = rnd.nextInt(100);
I suspect your lecturer has a strong theoretical knowledge about programming.

I'd argue that your instructor is flat-out wrong. Maintainability should be one of your primary goals, and reproducibility is essential to debugging and maintainability. Math.random() gives you no control over the seeding, and consequently no reproducibility if something weird is noted during testing and debugging.

I would not be surprised if this question became closed for being too subjective.
But anyway -
I would say this depends on the context. Did your 'mistake' of using Random cause bad perfomance, unreadable code, or anything at all? If not, then I think it is fine.
One can nitpick about these kind of things, but in reality - in my opinion at least - there are larger things to worry about than such theoretical problems.

Related

Should I put if(variable < 10) in own method? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 4 years ago.
Improve this question
I have a check in a loop where I have to check if the number of occurrence is less than 10 which could be written as either
if(occ < 10){
}
or
if(checkIfOccurencyIsLessThan10(occ)){
values.add(current+"0"+occ);
}
else{
values.add(current+occ);
}
I'm reading Clean Code a handbook of agile software craftsmanship, where they say a method should do the least amount, and code should be hacked up into more pieces. Is this necessary right here? I'm trying to get a better grasp on how long a method should be, and how much it should be doing.
It depends on if this condition is spread across multiple pieces of code, and if this check could change in the future to include checking additional edge cases. If both of those things are true or could be true, then sure, extracting the check to its own function is wise. However, I would definitely say you should rename the function to not specify the functions implementation, because that defeats the purpose of being able to change out the conditional, right? Naming it something like occurenceNeedsZero is a much more flexible solution. Because if you come up with other use cases that need checking you can add them to this function as well!
However, if your question is "should I always make a simple conditional check such as "is x < 10" into its own function, then I would say no. That would be overengineering, in my opinion. Functions should be used to 1) separate logical portions of code, 2) increase readability, or 3) extract small pieces of code that are spread across multiple locations and likely to change in the future, as it simplifies future refactoring.
There are probably more cases than those 3, but those are the big ones.
It's better to use a static final variable to store this 10, instead hard code.
If there are other places need to check if occ < 10, you need extract it as a method. Otherwise it is unecessary.

How to find the position of single bit set in a long very fast [closed]

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
I have a long with a single bit set and I need to know which it is, e.g. the index. I need to calculate this as fast as possible.
The naive idea is to divide by 2 and check whether the result is 1. But this would need up to 63 iterations (worst case).
My next idea was to make like a binary search, e.g. to look wether it is bit 63-32 or 31-0 then 63 - 48, 47 - 31, 31 - 16, 15 - 0 and so on having many if-else statements, but this gives me hell of a bunch of code...
Furthermore I'd like to minimize object creation and memory used. You might suggest that I'm wrong then with Java and should use perhaps C/C++. Well it's for a school competition and I don't have a choice :)
I'd like to see some sample code!
Use Long.numberOfTrailingZeros - this will be exactly the index you are looking for.
Long.numberOfLeadingZeros can be also useful if you count bits starting from the highest one.
Both methods are JVM intrinsics, i.e. they are treated specially by JIT compiler. These methods are translated to a special CPU instruction (TZCNT / LZCNT) and thus are very efficient.
You could prepare a Map<Int, Int>, holding the number of the set bit for each possible value, but I'm not sure if it is really faster than a loop.
Maybe bit shifting is faster than dividing by 2.

Java - long one line statements vs multiple lines [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 6 years ago.
Improve this question
My question is general. When should I consider splitting a statement to multiple lines?
I'm writing code on my own, and never worked in a team. I always prefer to make my code as compact as it can get.
For instance, instead of writing:
depth = depth - randomNumbers.nextInt(depth) -1;
Expression expA = createRandomExp(depth);
Expression expB = createRandomExp(depth);
SubtractionExpression subExp = new SubtractionExpression(expA,expB);
return subExp;
I will just write:
return new SubtractionExpression(createRandomExp(depth - randomNumbers.nextInt(depth) - 1), createRandomExp(depth - randomNumbers.nextInt(depth) - 1));
The pros as I see it are:
Less lines of code.
No need for declaration of variables.
Cons:
Can be less readable
Some stuff are written multiple times, like: randomNumbers.nextInt(depth) -1
What are the standards in the industry? And what should I consider when writing statements? Some guidelines might help.
I came over this, but it doesn't really answer my question.
Multiple lines make easy to read when another developer needs to read your code, and use comment lines to clarify functions, variables, classes, etc. Also, You may leave the company you work and someone needs to improve your code or there may be a dysfunctionality in your code so in case of those reasons, you should write your code with multiple lines in order to makes it easier to read and understand.
There should not be any standarts to my knowledge but above reasons will be enough to write codes with multiple lines not in a one line.Additionaly, when you get compiler error while writing single line codes, compiler will say "error found in X line" and you may not be able to understand where is the error in that line. However, multiple lines will ease the situation. I suggest you to write multiple lines instead of single line.
It is good practice to not declare one-use variables. I really like aproach, when you use your "(" bracket as "{" bracket, like:
return new SubtractionExpression(
createRandomExp(
depth - randomNumbers.nextInt(depth) - 1
),
createRandomExp(
depth - randomNumbers.nextInt(depth) - 1
)
);

Is introducing underscores in literals in java beneficial or a drawback? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
Though oracle technotes state that :
In Java SE 7 and later, any number of underscore characters (_) can
appear anywhere between digits in a numerical literal. This feature
enables you, for example, to separate groups of digits in numeric
literals, which can improve the readability of your code.
example : float pi = 3.14_15F;
is same as
float pi = 3.1415F;
But does it not become confusing to the developers working on code written by someone else?
Also does the use of underscore put any overhead on compiler or not?
But does it not become confusing to the developers working on code written by someone else?
Only if the developers don't understand the Java language! This construct has been been supported for long enough that every Java professional should recognize it ... even if they don't use it in their own code.
On the other hand, if your Java developers have not bothered to keep up to date with the new things in Java 7, they may be (temporarily) baffled. But the real solution is to educate your developers.
Also does the use of underscore put any overhead on compiler or not?
The overhead would be so small that it is impossible to measure.
There is no performance issue here.
The only time it would make any sense to use underscores is in a very large integer or with a binary integer. Like almost any bit of syntactical freedom the language provides, people are free to misuse it and write difficult to read code. I doubt this underscore thing will become a problem any more than the freedom to add extra white space is a problem.
The best example for when you would want to use this is with binary numbers where it is customary to place a space between every 4 bits.
For instance, compare:
int bitField = 0b110111011111;
int bitField2= 0b1101_1101_1111; //clearly more readable.
Other examples might include a credit card number or SSN as given in Oracle's documentation of this feature.

How do I use letter as a variable/placeholder in a math equation? [closed]

Closed. This question is off-topic. It is not currently accepting answers.
Want to improve this question? Update the question so it's on-topic for Stack Overflow.
Closed 11 years ago.
Improve this question
Sorry if that title confused you its kinda hard for me to ask this without explaining it.
I am writing a (fairly) simple program to find the roots of a quartic (biquadratic) function.
My main question (I should know this >.>) is how do i get x in the quartic function (ax^4 * bx^3 * cx^2 * dx * e = 0) to stay as x and not be given a value. just sorta a place holder. this is part of it: ( b1 * x * c1 / 2 ); so i dont want x to be replaced. i just want it to stay as x and everything else around it multiply as you normaly would when solving the problem by hand.
My second question is from this site:
http://easycalculation.com/algebra/learn-quartic-equation.php
We haven't covered Quartics in school yet but We have covered cubics and quadratics so I know enough that i can follow a long for the most part except for right after it talks about the discriminant.
y2=(- term1 + r13*cos(q3+(2∏)/3) )
y3=(- term1 + r13*cos(q3+(4∏)/3) )
i dont get the parts with 2∏ and 4∏. If you know a simple way to explain it, please do :D if not i can always look it up and try to figure it out from there.
And my last question. I know how with the discriminant of quadratics depending on what it is depends on one root, no roots, or two roots. How does that apply with quartics and what should i do to check for that in my code (if you think i cant figure it out lol).
ummm i believe thats it. i can add info if needed. I dont think my code would be needed but i would prefer not to post it either way.
Thanks for the help.
-Ryan
The approach cited relies on a trigonometric identity described here used to solve cubic equations. The symbol ∏ is a capital π, or Math.PI in Java.
See also this example that uses org.jscience.mathematics.function.Polynomial and references a convenient root-finding algorithm.
The approach that you are looking for is called Symbolic Programming.
I do not, however, know of any stable Java libraries which allow for such programming.

Categories

Resources