QUIZ: 3 Variables, only 1 if-else to print the difference - variables

I got question. How is it possible to solve a problem where I can only use 1 if-else statement to check 3 variables which one of them is different and print this?
Example:
A = 10
B = 3
C = 10
Answer: B

You didn't specify a language, so this is kinda pseudocode:
if (A == B) {
echo 'C';
} elseif (A == C) {
echo 'B';
} else {
echo 'A';
}
If A and B are equal, we know the different one is C.
Otherwise, if A and C are equal, the different one is B.
C and B aren't the problem? We're only left with A.

In C language it would like this:
int A = 10;
int B = 5;
int C = 10;
if ( A == B) // Check A and B for Equality
printf ("Answer: C");
else if (A == C) // Check A and C for Equality
printf ("Answer: B");
else // Then the answer must be A
printf ("Answer: A");

I found a answer to this! Also I forgot to mention, you're only allowed to use 1 if and else (So no elseifs).
if (A == B) {
print C;
}
else{
print A + B - C;
}

Related

IDEA doesn't offer to replace a null check + dot action to `?.`

I have the following code example below.
Replacing the following null check + dot action
a != null && a.toInt() == b
with ?.
a?.toInt() == b
"seems" to do the same job and even clearer.
But, as you can see in the image, IDEA doesn't suggest the replacement.
Perhaps the two expressions aren't equivalent?
Example code:
fun main() {
val a: String? = initA()
val b = 1
if (a != null && a.toInt() == b) {
println("true")
} else {
println("false")
}
}
Screencap:
The second I clicked post I understood.
If b's type is changes to nullable, meaning:
val b: Int?
Those expressions cease to be equivalent.
If both a and b are null, the behavior will be different.

Solidity ++ operator not assigning as expected

Sorry to completely rewrite this post, but I was way off on my troubleshooting. Hopefully this prevents someone's headache in the future...
Now, for example code.
function compare(uint8 a, uint8 b)
private
requireUnpaused
returns(bool)
{
// increment a by 1
a = a++;
// if a + 1 = 3, then loop it around the cycle to be 0
if (a >= 3) {
a = 0;
}
// compare a to b. If a = b, a is the winner - return true
return a == b ? true : false;
}
This code works as expected if I replace "a = a++" with "a = ++a", just "a++" or "++a", or even "a = a + 1".
This drove me crazy for a few days. My question for someone more versed in this than I: Why does "a = a++" not work, when every other way of incrementing "a" by 1 does?

how do i correctly use >= and <= in code?

I have tried many thing involving this, >=, >==, =>, ==>.i can not find one that works. hey all return either primary expression needed or expected initializer before '>'. I am creating a IR receiver latch switch and thus have to create parameters for the code because the receiver is not constant in all conditions. Full code below. Any suggestions to fix the code please reply and don't DM me. Thank you.
code:
int LEDState = 0;
int LEDPin = 8;
int dt = 100;
int recieverOld ==> 500 and recieverOld ==< 2000;
int recieverNew;
int recieverPin = 12;
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
pinMode(LEDPin, OUTPUT);
pinMode(recieverPin, INPUT);
}
void loop() {
// put your main code here, to run repeatedly:
recieverNew = digitalRead(recieverPin);
if((recieverOld >== 0 && recieverOld <== 10) && (recieverNew >== 500 && recieverNew <== 2000) {
if(LEDState == 0) {
digitalWrite(LEDPin, HIGH);
LEDState = 1;
}
}
recieverOld = recieverNew;
delay(dt);
}
error:
expected initializer before '==' token
if one = used line 4 and related, return error expected primary-expression before '>' token
if > before = line 4 and related, return error expected initializer before '>=' token
Any solutions or suggestions welcome.
TL;DR
Operators that do no exist, and that you should NOT use:
==>, ==<, >==, <==
Operators that works and you can use them:
>= - MORE THAN OR EQUAL, compare operator, for example X >= 5
<= - LESS THAN OR EQUAL, compare operator, for example X <= 5
> - MORE THAN, compare operator, for example X > 5
< - LESS THAN, compare operator, for example X < 5
== - compare operator, when you want to compare values of the variables if they have the same value, for example X == 5, Y == X, 10 == 7
=== - equality operator, similar to compare operator ==, but aditionally checks the type of a variable. for example X === Y, '10' === 10
= - assign operator, when you want to assign something to the variable, for example X = 5
<> OR != - NOT EQUAL, compare operator, for example X != 5, Y <> 10
!== - similar to != or <>, but also checks the type of a value. For example 10 !== '10', and will return opposite result of the equality operator ===

How can I get the value of the existing variable in a IF clause?

I am working on Objective C and I want to do something like this:
if (a && !b) {
// a do something...
} else if (!a && b) {
// b do something...
}
I wondered if there is something simpler, like:
if (a XOR b) {
// the existing variable do something...
}
Thanks in advance!!
Objective C is a superset of C, use the ^ operator. Or you can think logically (since xor is only true if either is true and the other is false) and use:
// This won't work for all types, be careful
if (a != b){
if (a){
// a do something
}
if (b){
// b do something
}
}
Note this solution, expanded from the xor, is more lengthy than the one you provided.
well I'm not sure if I misunderstood, but I guess a possibly solution would be to use the ? operator.
void *aux;
if( aux = a ? (b ? NULL : a) : (b ? b : NULL) )
//working with aux here
Never the less, if the idea is to keep it simple, this is quite unreadable. Also, this would expand to something like:
void *aux;
if(a){
if(b)
aux = NULL;
else
aux = a;
}else{
if(b)
aux = b;
else
aux = NULL;
}
My suggestion is that you leave the code as is. It's more readable and in terms of performance, I don't believe you'll notice much difference between the approaches
edit for clarity:
BTW, Inside the if block, the aux var will contain the value that exists. And if aux is NULL the if block won't be entered. Also, aux doesn't have to be void * or a pointer, it only has to be compatible with a and b datatypes.
if( !a != !b ) // same as a xor b

Number of possible combinations

How many possible combinations of the variables a,b,c,d,e are possible if I know that:
a+b+c+d+e = 500
and that they are all integers and >= 0, so I know they are finite.
#Torlack, #Jason Cohen: Recursion is a bad idea here, because there are "overlapping subproblems." I.e., If you choose a as 1 and b as 2, then you have 3 variables left that should add up to 497; you arrive at the same subproblem by choosing a as 2 and b as 1. (The number of such coincidences explodes as the numbers grow.)
The traditional way to attack such a problem is dynamic programming: build a table bottom-up of the solutions to the sub-problems (starting with "how many combinations of 1 variable add up to 0?") then building up through iteration (the solution to "how many combinations of n variables add up to k?" is the sum of the solutions to "how many combinations of n-1 variables add up to j?" with 0 <= j <= k).
public static long getCombos( int n, int sum ) {
// tab[i][j] is how many combinations of (i+1) vars add up to j
long[][] tab = new long[n][sum+1];
// # of combos of 1 var for any sum is 1
for( int j=0; j < tab[0].length; ++j ) {
tab[0][j] = 1;
}
for( int i=1; i < tab.length; ++i ) {
for( int j=0; j < tab[i].length; ++j ) {
// # combos of (i+1) vars adding up to j is the sum of the #
// of combos of i vars adding up to k, for all 0 <= k <= j
// (choosing i vars forces the choice of the (i+1)st).
tab[i][j] = 0;
for( int k=0; k <= j; ++k ) {
tab[i][j] += tab[i-1][k];
}
}
}
return tab[n-1][sum];
}
$ time java Combos
2656615626
real 0m0.151s
user 0m0.120s
sys 0m0.012s
The answer to your question is 2656615626.
Here's the code that generates the answer:
public static long getNumCombinations( int summands, int sum )
{
if ( summands <= 1 )
return 1;
long combos = 0;
for ( int a = 0 ; a <= sum ; a++ )
combos += getNumCombinations( summands-1, sum-a );
return combos;
}
In your case, summands is 5 and sum is 500.
Note that this code is slow. If you need speed, cache the results from summand,sum pairs.
I'm assuming you want numbers >=0. If you want >0, replace the loop initialization with a = 1 and the loop condition with a < sum. I'm also assuming you want permutations (e.g. 1+2+3+4+5 plus 2+1+3+4+5 etc). You could change the for-loop if you wanted a >= b >= c >= d >= e.
I solved this problem for my dad a couple months ago...extend for your use. These tend to be one time problems so I didn't go for the most reusable...
a+b+c+d = sum
i = number of combinations
for (a=0;a<=sum;a++)
{
for (b = 0; b <= (sum - a); b++)
{
for (c = 0; c <= (sum - a - b); c++)
{
//d = sum - a - b - c;
i++
}
}
}
This would actually be a good question to ask on an interview as it is simple enough that you could write up on a white board, but complex enough that it might trip someone up if they don't think carefully enough about it. Also, you can also for two different answers which cause the implementation to be quite different.
Order Matters
If the order matters then any solution needs to allow for zero to appear for any of the variables; thus, the most straight forward solution would be as follows:
public class Combos {
public static void main() {
long counter = 0;
for (int a = 0; a <= 500; a++) {
for (int b = 0; b <= (500 - a); b++) {
for (int c = 0; c <= (500 - a - b); c++) {
for (int d = 0; d <= (500 - a - b - c); d++) {
counter++;
}
}
}
}
System.out.println(counter);
}
}
Which returns 2656615626.
Order Does Not Matter
If the order does not matter then the solution is not that much harder as you just need to make sure that zero isn't possible unless sum has already been found.
public class Combos {
public static void main() {
long counter = 0;
for (int a = 1; a <= 500; a++) {
for (int b = (a != 500) ? 1 : 0; b <= (500 - a); b++) {
for (int c = (a + b != 500) ? 1 : 0; c <= (500 - a - b); c++) {
for (int d = (a + b + c != 500) ? 1 : 0; d <= (500 - a - b - c); d++) {
counter++;
}
}
}
}
System.out.println(counter);
}
}
Which returns 2573155876.
One way of looking at the problem is as follows:
First, a can be any value from 0 to 500. Then if follows that b+c+d+e = 500-a. This reduces the problem by one variable. Recurse until done.
For example, if a is 500, then b+c+d+e=0 which means that for the case of a = 500, there is only one combination of values for b,c,d and e.
If a is 300, then b+c+d+e=200, which is in fact the same problem as the original problem, just reduced by one variable.
Note: As Chris points out, this is a horrible way of actually trying to solve the problem.
link text
If they are a real numbers then infinite ... otherwise it is a bit trickier.
(OK, for any computer representation of a real number there would be a finite count ... but it would be big!)
It has general formulae, if
a + b + c + d = N
Then number of non-negative integral solution will be C(N + number_of_variable - 1, N)
#Chris Conway answer is correct. I have tested with a simple code that is suitable for smaller sums.
long counter = 0;
int sum=25;
for (int a = 0; a <= sum; a++) {
for (int b = 0; b <= sum ; b++) {
for (int c = 0; c <= sum; c++) {
for (int d = 0; d <= sum; d++) {
for (int e = 0; e <= sum; e++) {
if ((a+b+c+d+e)==sum) counter=counter+1L;
}
}
}
}
}
System.out.println("counter e "+counter);
The answer in math is 504!/(500! * 4!).
Formally, for x1+x2+...xk=n, the number of combination of nonnegative number x1,...xk is the binomial coefficient: (k-1)-combination out of a set containing (n+k-1) elements.
The intuition is to choose (k-1) points from (n+k-1) points and use the number of points between two chosen points to represent a number in x1,..xk.
Sorry about the poor math edition for my fist time answering Stack Overflow.
Just a test for code block
Just a test for code block
Just a test for code block
Including negatives? Infinite.
Including only positives? In this case they wouldn't be called "integers", but "naturals", instead. In this case... I can't really solve this, I wish I could, but my math is too rusty. There is probably some crazy integral way to solve this. I can give some pointers for the math skilled around.
being x the end result,
the range of a would be from 0 to x,
the range of b would be from 0 to (x - a),
the range of c would be from 0 to (x - a - b),
and so forth until the e.
The answer is the sum of all those possibilities.
I am trying to find some more direct formula on Google, but I am really low on my Google-Fu today...