This question already has answers here:
What is the difference between these (bCondition == NULL) and (NULL==bCondition)? [duplicate]
(6 answers)
Closed 9 years ago.
[I thought this would have been asked already, but I can't find an answer].
When writing an if statement, should the thing I'm comparing against come first or second? (I am specifically curious about both C / C++ and Java).
Does it matter, or is it just stylistic? (Convention seems to be "variable first, value second").
Consider the following code:
#include <iostream>
int main() {
int x = 5;
if ( 5 == x ) {
std::cout << "X == 5, true." << std::endl;
}
if ( x == 5 ) {
std::cout << "5 == X, true." << std::endl;
}
return 0;
}
which outputs:
X == 5, true.
5 == X, true.
so there doesn't appear to be any difference. Are there subtleties I'm missing?
These are called Yoda Conditions and to my knowledge the main idea is to guard against accidental assignment (i.e. you can't assign to literals).
Yes, worth mentioning that something like if (a = 5) where a is not a bool is not allowed in languages such as Java (though OK in C/C++), but as the Wikipedia article points out it is still possible to guard against unwanted behavior:
It can also solve some types of unsafe null behavior.
String myString = null;
if (myString.equals("foobar")) { /* ... */ }
// This causes a NullPointerException in Java
With Yoda Conditions:
String myString = null;
if ("foobar".equals(myString)) { /* ... */ }
// This is false, as expected
Putting the constant first (aka "Yoda style") prevents problems from a simple typo:
if (x = 5) // if (x == 5) was intended
...still compiles but does the wrong thing (though most current compilers will warn about the problem).
if (5 = x) // if (5 == x) was intended
...absolutely cannot compile on anything even approaching a properly functioning compiler.
No, there is no difference. It doesn't matter. Do whatever you like. Personally I'd do:
x == 5
Because it reads better (or so I think). 5 == x just doesn't sound right. But again, personal opinion.
I think you'll find that most people do x == 5 because you are comparing x, rather than comparing 5.
Both are ok.
But it is more accepted to do so when the parameter on left side.
example:
if ( x == 5 )
Anyway. it doesn't matter, do whatever you pleased and feel more comfortable with.
In most cases you'll find the common practice is to have the variable come first because the operator == means assignment and here you are assigning the value 5 so it only makes sense to have the variable come first.
Your if statement should then look like this:
if ( 5 == x ) {
std::cout << "X == 5, true." << std::endl;
}
Related
This question already has answers here:
How can I perform multiplication without the '*' operator?
(31 answers)
Closed 4 years ago.
I had an interesting interview yesterday where the interviewer asked me a classic question: How can we multiply two numbers in Java without using the * operator. Honestly, I don't know if it's the stress that comes with interviews, but I wasn't able to come up with any solution.
After the interview, I went home and breezed through SO for answers. So far, here are the ones I have found:
First Method: Using a For loop
// Using For loop
public static int multiplierLoop(int a, int b) {
int resultat = 0;
for (int i = 0; i < a; i++) {
resultat += b;
}
return resultat;
}
Second Method: Using Recursion
// using Recursion
public static int multiplier(int a, int b) {
if ((a == 0) || (b == 0))
return 0;
else
return (a + multiplier(a, b - 1));
}
Third Method: Using Log10
**// Using Math.Log10
public static double multiplierLog(int a, int b) {
return Math.pow(10, (Math.log10(a) + Math.log10(b)));
}**
So now I have two questions for you:
Is there still another method I'm missing?
Does the fact that I wasn't able to come up with the answer proves that my logical reasoning isn't strong enough to come up with solutions and that I'm not "cut out" to be a programmer? Cause let's be honest, the question didn't seem that difficult and I'm pretty sure most programmers would easily and quickly find an answer.
I don't know whether that has to be a strictly "programming question". But in Maths:
x * y = x / (1 / y) #divide by inverse
So:
Method 1:
public static double multiplier(double a, double b) {
// return a / (1 / b);
// the above may be too rough
// Java doesn't know that "(a / (b / 0)) == 0"
// a special case for zero should probably be added:
return 0 == b ? 0 : a / (1 / b);
}
Method 2 (a more "programming/API" solution):
Use big decimal, big integer:
new BigDecimal("3").multiply(new BigDecimal("9"))
There are probably a few more ways.
There is a method called [Russian Peasant Multiplication][1]. Demonstrate this with the help of a shift operator,
public static int multiply(int n, int m)
{
int ans = 0, count = 0;
while (m > 0)
{
if (m % 2 == 1)
ans += n << count;
count++;
m /= 2;
}
return ans;
}
The idea is to double the first number and halve the second number repeatedly till the second number doesn’t become 1. In the process, whenever the second number become odd, we add the first number to result (result is initialized as 0) One other implementation is,
static int russianPeasant(int n, int m) {
int ans = 0;
while (m > 0) {
if ((m & 1) != 0)
ans = ans + n;
n = n << 1;
m = m >> 1;
}
return ans;
}
refer :
https://www.geeksforgeeks.org/russian-peasant-multiply-two-numbers-using-bitwise-operators/
https://www.geeksforgeeks.org/multiplication-two-numbers-shift-operator/
[1]: https://web.archive.org/web/20180101093529/http://mathforum.org/dr.math/faq/faq.peasant.html
Others have hit on question 1 sufficiently that I'm not going to rehash it here, but I did want to hit on question 2 a little, because it seems (to me) the more interesting one.
So, when someone is asking you this type of question, they are less concerned with what your code looks like, and more concerned with how you are thinking. In the real world, you won't ever actually have to write multiplication without the * operator; every programming language known to man (with the exception of Brainfuck, I guess) has multiplication implemented, almost always with the * operator. The point is, sometimes you are working with code, and for whatever reason (maybe due to library bloat, due to configuration errors, due to package incompatibility, etc), you won't be able to use a library you are used to. The idea is to see how you function in those situations.
The question isn't whether or not you are "cut out" to be a programmer; skills like these can be learned. A trick I use personally is to think about what, exactly, is the expected result for the question they're asking? In this particular example, as I (and I presume you as well) learned in grade 4 in elementary school, multiplication is repeated addition. Therefore, I would implement it (and have in the past; I've had this same question in a few interviews) with a for loop doing repeated addition.
The thing is, if you don't realize that multiplication is repeated addition (or whatever other question you're being asked to answer), then you'll just be screwed. Which is why I'm not a huge fan of these types of questions, because a lot of them boil down to trivia that you either know or don't know, rather than testing your true skills as a programmer (the skills mentioned above regarding libraries etc can be tested much better in other ways).
TL;DR - Inform the interviewer that re-inventing the wheel is a bad idea
Rather than entertain the interviewer's Code Golf question, I would have answered the interview question differently:
Brilliant engineers at Intel, AMD, ARM and other microprocessor manufacturers have agonized for decades as how to multiply 32 bit integers together in the fewest possible cycles, and in fact, are even able to produce the correct, full 64 bit result of multiplication of 32 bit integers without overflow.
(e.g. without pre-casting a or b to long, a multiplication of 2 ints such as 123456728 * 23456789 overflows into a negative number)
In this respect, high level languages have only one job to do with integer multiplications like this, viz, to get the job done by the processor with as little fluff as possible.
Any amount of Code Golf to replicate such multiplication in software IMO is insanity.
There's undoubtedly many hacks which could simulate multiplication, although many will only work on limited ranges of values a and b (in fact, none of the 3 methods listed by the OP perform bug-free for all values of a and b, even if we disregard the overflow problem). And all will be (orders of magnitude) slower than an IMUL instruction.
For example, if either a or b is a positive power of 2, then bit shifting the other variable to the left by log can be done.
if (b == 2)
return a << 1;
if (b == 4)
return a << 2;
...
But this would be really tedious.
In the unlikely event of the * operator really disappearing overnight from the Java language spec, next best, I would be to use existing libraries which contain multiplication functions, e.g. BigInteger.multiply(), for the same reasons - many years of critical thinking by minds brighter than mine has gone into producing, and testing, such libraries.
BigInteger.multiply would obviously be reliable to 64 bits and beyond, although casting the result back to a 32 bit int would again invite overflow problems.
The problem with playing operator * Code Golf
There's inherent problems with all 3 of the solutions cited in the OP's question:
Method A (loop) won't work if the first number a is negative.
for (int i = 0; i < a; i++) {
resultat += b;
}
Will return 0 for any negative value of a, because the loop continuation condition is never met
In Method B, you'll run out of stack for large values of b in method 2, unless you refactor the code to allow for Tail Call Optimisation
multiplier(100, 1000000)
"main" java.lang.StackOverflowError
And in Method 3, you'll get rounding errors with log10 (not to mention the obvious problems with attempting to take a log of any number <= 0). e.g.
multiplier(2389, 123123);
returns 294140846, but the actual answer is 294140847 (the last digits 9 x 3 mean the product must end in 7)
Even the answer using two consecutive double precision division operators is prone to rounding issues when re-casting the double result back to an integer:
static double multiply(double a, double b) {
return 0 == (int)b
? 0.0
: a / (1 / b);
}
e.g. for a value (int)multiply(1, 93) returns 92, because multiply returns 92.99999.... which is truncated with the cast back to a 32 bit integer.
And of course, we don't need to mention that many of these algorithms are O(N) or worse, so the performance will be abysmal.
For completeness:
Math.multiplyExact(int,int):
Returns the product of the arguments, throwing an exception if the result overflows an int.
if throwing on overflow is acceptable.
If you don't have integer values, you can take advantage of other mathematical properties to get the product of 2 numbers. Someone has already mentioned log10, so here's a bit more obscure one:
public double multiply(double x, double y) {
Vector3d vx = new Vector3d(x, 0, 0);
Vector3d vy = new Vector3d(0, y, 0);
Vector3d result = new Vector3d().cross(vx, vy);
return result.length();
}
One solution is to use bit wise operations. That's a bit similar to an answer presented before, but eliminating division also. We can have something like this. I'll use C, because I don't know Java that well.
uint16_t multiply( uint16_t a, uint16_t b ) {
uint16_t i = 0;
uint16_t result = 0;
for (i = 0; i < 16; i++) {
if ( a & (1<<i) ) {
result += b << i;
}
}
return result;
}
The questions interviewers ask reflect their values. Many programmers prize their own puzzle-solving skills and mathematical acumen, and they think those skills make the best programmers.
They are wrong. The best programmers work on the most important thing rather than the most interesting bit; make simple, boring technical choices; write clearly; think about users; and steer away from stupid detours. I wish I had these skills and tendencies!
If you can do several of those things and also crank out working code, many programming teams need you. You might be a superstar.
But what should you do in an interview when you're stumped?
Ask clarifying questions. ("What kind of numbers?" "What kind of programming language is this that doesn't have multiplication?" And without being rude: "Why am I doing this?") If, as you suspect, the question is just a dumb puzzle with no bearing on reality, these questions will not produce useful answers. But common sense and a desire to get at "the problem behind the problem" are important engineering virtues.
The best you can do in a bad interview is demonstrate your strengths. Recognizing them is up to your interviewer; if they don't, that's their loss. Don't be discouraged. There are other companies.
Use BigInteger.multiply or BigDecimal.multiply as appropriate.
This question already has answers here:
Double Negation in C++
(14 answers)
Closed 9 years ago.
Sometimes, I saw the following code:
if ( !!on_debugging )
which is the same as
if ( on_debugging )
I don't understand why these two !s are used. Is there any kind of difference?
!!a is almost equivalent to a. It converts it to a boolean value.
Usually this does not make a difference, but sometimes it does.
#include <iostream>
int a(int x) {
return 1;
}
int a(bool x) {
return 2;
}
int main() {
std::cout << a(0) << std::endl; //prints 1
std::cout << a(!!0) << std::endl; //prints 2
std::cout << -1 << std::endl; //prints -1
std::cout << !!-1 << std::endl; //prints 1
}
In your case, there is no difference, unless there is overloading. (But even if there is overloading, I hope there is no difference.)
(FYI, this is done even more commonly in Javascript because of its types, e.g. false != null but false == !!null. I include this comment because you tagged your question with C, C++, and Java, and Javascript shares similar syntax.)
If operator! is not overloaded, the two statements are equivalent.
Where !! might be useful is if you need to change a zero / non-zero value, or a nullptr / non-null pointer value into a 0/1 value in an integer expression.
For a (dubious) example, the following loop counts the number of non-zero elements in a vector:
for (size_t i = 0; i != v.size(); i++)
count += !!v[i];
You will sometimes see !! in bit-level hacks as a result. But in the if statement you show above? Unless operator! is overloaded, that's not a useful operation.
There must be some form of operator overloading else, it means the same.
Take this as an live example:
#include <stdio.h>
int main(void) {
int a = 5;
printf("%d\n", a);
printf("%d\n", !!a); // will print 1
return 0;
}
The main difference is a silly-warning from Visual C++.
Secondary (rare) differences include the case where you have an operator!, and the case where the argument is used in a non-boolean context, e.g. arithmetic.
Double ! simplily means a unary NOT and another unary not. See it as (!(!on_debugging))
Yes, you are right, most of the time the results is the same as on_debugging. I think this is for preciseness or strictness to use !! because the ! operator only returns integer 0 or 1, which corresponds to false and true. While the variable can be anything of int and point type.
For Java !!on_debugging is the opposite of !!!on_debugging.
You can negate stuff as often as you want, thus there is no difference between on_debugging and !!on_debugging.
Also see Java Language Specification for this operator:
The type of the operand expression of the unary ! operator must be
boolean or Boolean, or a compile-time error occurs.
(see JLS 15.15.6).
This question already has answers here:
Why are these constructs using pre and post-increment undefined behavior?
(14 answers)
Closed 9 years ago.
public class main {
public static void main(String[] args) {
int x=20,y=35;
x = y++ + x++;
y = ++y + ++x;
System.out.printf("%d %d\n",x,y);
}
//Output : 56,93
#include<stdio.h>
void main()
{
int x=20,y=35;
x = y++ + x++;
y = ++y + ++x;
printf("%d %d ",x,y);
}
//Output : 57 94
According to Operator Precedence Rules whatever output I got through Java code is right but when executing the same in 'C' code it incremented the output values by 1. I am using ubuntu 12.04 64-bit Operating System.
It's not the same thing because Java and C are different languages.
The behaviour of post increment in Java is defined as performing the increment after the expression has been evaluated.
The behaviour in C is undefined but often follows the order of precedence.
Note: order of evaluation and precedence are different things and this is more obvious for post increment/decrement and short cut boolean operations.
e.g.
Sting s = null;
if (s == null || !(s.length() > 0))
In this case ! has the highest precedence, but in reality will never be evaluated because the lower precedence || prevents it.
Precedence only determines where the implied brackets are, but only suggest how the expression might be evaluated.
I'm doing some small program for a beginners programming course and in my program I have 2 variables which hold numbers. Anyway I need to find out which number is bigger and print the appropriate message according to it, for example I have:
int x = 5;
int y = 10;
I need to print:
"it is true that y is bigger than x";
Now the thing is that I know I can use a simple if statement but I'm not allowed to use it, now it makes me wonder, is it even possible? If so, how can I do that? How can I check which number is bigger WITHOUT doing something like:
if (x > y)
answer = true;
...
Thanks in advance.
Well you can do:
boolean answer = x > y;
The expression x > y is just an expression of type boolean. While boolean expressions are often used for conditions in if statements, loops etc, they don't have to be - simple assignment works fine too.
It sounds like you want the reverse though:
boolean answer = y > x;
Then you can use the value of answer to build the string to display...
Use the ternary operator:
System.out.println(x > y ? "It is true that x is greater than y" : "");
ternary operator "?:"
String output = (x > y)? "x is greater than y":"y is greater than x";
The ternary conditional operator that others mentioned will work. Assuming you are looking for creative ways to do this rather than practical ones, here's another method:
int x = 5;
int y = 10;
while(y > x){
System.out.println("It is true that y is bigger than x.");
return;
}
System.out.println("It is false that y is bigger than x.");
The while is just acting as a fancy if, because the return means the otherwise infinite loop will only execute at most once.
Here's another example that instead relies upon short-circuit boolean evaluation:
public static void main(String...args){
int x = 5;
int y = 10;
boolean answer = (y > x);
boolean testTrue = answer && printTrue();
boolean testFalse = testTrue || printFalse();
}
private static boolean printFalse() {
System.out.println("It is false that y is bigger than x.");
return true;
}
private static boolean printTrue() {
System.out.println("It is true that y is bigger than x.");
return true;
}
Of course you shouldn't do this in real production code, but it can be fun to think of unorthodox ways to code something and it can be helpful for exploring the language.
Your question is tagged as Java but you do not specify Java in your question. In Java there are multiple ways to get the same result that involve testing the boolean expression x > y somehow, such as the ternary operator. I would consider these equivalent to an explicit if statement.
Other possibilities:
Compute the square root of x - y. This will raise an exception if y is bigger. Catch the exception in the caller and report that y is the larger quantity. If there is no exception, report that x is the larger.
In LISP, Ruby or another language that supports the symbol type, form a list ((symbol x, x), (symbol y, y)) and sort the list. Then report the second symbol as the variable with the larger value.
If using assembly, BASIC, PL/1, etc. you can use an arithmetic expression to choose the target of a GOTO statement. Depending on whether x or y is larger, execution will resume at a different part of the code. Or use the list-sorting trick in the previous bullet to select the GOTO label.
In general, the expression ((x - y) / abs(x - y) + 1) / 2 will produce 1 if x is larger and 0 if y is larger. This result could be used to choose data, a function, etc. out of a list of two alternatives, producing conditional behavior without an if statement.
You could use recursion (but I would not recommend it)
public int compare ( int a , int b )
{
switch ( a )
{
case Integer.MIN_VALUE :
switch ( b )
{
case Integer.MIN_VALUE :
return 0 ;
default :
return -1 ;
}
default :
switch ( b )
{
case INteger.Min_VALUE :
return 1 ;
default :
return compare ( a-1 , b-1 ) ;
}
}
}
(a+b)/2 + Abs(a-b)/2 is the bigger number.
I know in some languages you can use short-circuit evaluation to construct the answer.
The expression (A && B) always evaluates to B if A is true. If A is false then B is never evaluated.
Similarly (A || B) evaluates to B if A is false. If A is true B is never evaluated.
Though I'm not 100% sure of Java, the expression you want is:
String output = ((x > y) && "it is true that X is greater than Y")
|| (((x < y) && "it is true that X is less than Y")
|| "it is true that X is equal to Y");
(a > b) & (c < d), the components are evaluated left to right, so (a >
b) is evaluated first. If (a > b) is false, the entire expression is
false regardless of the result of the component (r < d). Nevertheless,
the component (c < d) will still be evaluated. However, in the
expression (a > b) && (c < d), the component (c < d) will not be
evaluated if (a > b) evaluates to false. This is known as short
circuiting.
Came across this paragraph in a Java book. I have been programming in various languages before, but I've never found a need for '&'. Why would one want to evaluate the second statement if it's known that the end result is not affected by it? Is there any use for it; does it come due to historical reasons?
Same question applies to | and || as well.
The && operator is defined by the Java Language Specification to perform short-circuit evaluation.
However, the & operator is not, even when applied to boolean arguments.
You could exploit this if one of the arguments had side-effects that you did not want short-circuited. However, in my experience this is uncommon, and you'd face the risk of someone "fixing" it. It would be better separated into steps. For example, instead of:
if ( foo() & bar() ) {... }
you could say:
boolean isFoo = foo();
boolean isBar = bar();
if ( isFoo && isBar ) { ... }
if you expect your code to be under attack from timing attacks you want the least amount of branches (conditional execution paths) possible, this is one way to eliminate them
The difference between '&' and '&&' is not well-known and that example from the book doesn't help much.
Here's another example to show how short-circuiting work (using horrible methods having side-effects, but that's not the point).
Imagine you have this:
private int cnt;
private boolean a() {
cnt++;
return false;
}
private boolean b() {
cnt++;
return false;
}
If you execute the following:
cnt = 0;
if ( a() && b() ) {}
System.out.println( cnt );
It shall print 1.
While if you execute the following:
cnt = 0;
if ( a() & b() ) {}
System.out.println( cnt );
It shall print 2. Because in the latter case b() must be evaluated as per the language specs while in the first case b() must not be evaluated, as per the language specs.
You can use & in situations where you have to evaluate both subexpressions. For example, if they both have side effects that are observable by the rest of your application.
Perhaps the 2nd evaluation is in the form of an assignment statement or method call, in which case you might want it to execute. I wouldn't use bitwise operators in place of logical operators like this tho. If you need something to execute passed &&, then do it prior to your logical statement and store the result in a variable.
if(0 != ((a > b) ? 1 : 0) & ((c < d) ? 1 : 0)) {
// but really... (a > b) && (c < d), assuming no side-effects
}
...just use the logical operators (&& and ||) for conditions ;-) That is what they were designed for. If non-shortcircuit behavior is required, then restructure the code accordingly.
I think I have seen one case that had a somewhat valid use of & in this context, but I do not recall what it was so I mustn't have found it that valid ;-) In languages like C/C++ where there is no discreet "boolean" type, the (input) and result of & can be treated such that 0 -> false and non-0 -> true. As can be seen, however, Java has to jump through some fun to get bool -> int -> bool.
The only justification for a bit-wise operator is, well, bit-wise operations, IMOHO. Bit-wise operators are most useful when performing some sort of encoding including "bit fields" and "bit masks". They are also useful when dealing with fun arising from Java's signed-only bytes, etc.
I think the bigger (only?) point to take away is that && and || are short-circuiting -- they are actually the only operators with this behavior (arguments over ?: excluded); the rest is just to explain the eager-behavior of bit-wise operators. This just goes to re-enforce the rule: do not cause side-effects in conditionals (outside of a few well-accepted idioms, but even then, keep it simple).
Happy coding.
Examples of bit-wise usage:
Imagine the use of flags which are stored into a single "integer" slot in a serialized format:
int flags = 0;
if (this.encypted) {
flags |= EncryptedMode;
}
out.write(flags);
// later on
int flags = in.readInt();
this.encrypted = (flags & EncryptedMode) != 0;
Reading the "unsigned value" of a byte:
byte[] data = {-42, ...}; // read in from file or something
int unsignedByte = data[0] & 0xFF;
Your book is confusing things. For the most part, you will only use '&&' and '||'. The single ones, '&' and '|', are bitwise operators - you can read more about them here: http://download.oracle.com/javase/tutorial/java/nutsandbolts/op3.html
The use of a non-short-circuit operator may speed up performance-critical code by avoiding branch mis-prediction stalls, which could easily amount to a dozen or more clock cycles.