I need help understanding this. I really don't understand this piece of code and could someone here explain exactly what happens?
So this is the code:
static bool IsEven(int n)
{
if (n == 0) return true;
if (IsEven(n - 1))
{
return false;
}
else
{
return true;
}
}
And then I do this:
Console.WriteLine(IsEven(10));
How does it actually work? If I enter in number 10, it prints out true. If I enter number 7, it prints out false. But I don't understand why it even works.
It checks if the number is 0, then it returns true. But I entered 10 (which clearly is not 0) and it still print out true. Then it checks number -1.
So that would be 10-1, which is 9. But how does it know that 9 is NOT even? (it returns false).
I don't understand this code, but it works. I am so confused honestly.
Walk through it logically using a lower number like 3 so there are not as many recursions to think about.
The first time we call IsEven(3); it does this:
if (3 == 0) return true;
Well 3 does not equal 0 so it continues with this:
if (IsEven(3 - 1))
Which is the same as:
if (IsEven(2))
So now we're in the next call to IsEven. The first check is 2 == 0 which of course it is not, so it continues with IsEven(2 - 1).
Now we're in the third call to IsEven with IsEven(1). Well again 1 == 0 is not true so it continues with IsEven(1 - 1).
Now we're in the final (fourth) call to IsEven with IsEven(0). Well now 0 == 0 is true so we return true back to the third call.
So now back in the third call IsEven(1 - 1) is true so it performs the action in the first bracket which is to return false.
Back in the second call IsEven(2 - 1) is now false so it takes the action in the second bracket which is return true.
Back in the first call IsEven(3 - 1) is true so it takes the action in the first bracket which is to return false indicatining that 3 is indeed not even.
It's like integer inception.
Of course a real example would probably use the modulo % operator like this.
public static bool IsEven(int number)
{
return number % 2 == 0;
}
Think of it like this:
IsEven(3)
| IsEven(2)
| | IsEven(1)
| | | IsEven(0)
| | | Return True
| | Return False
| Return True
Return False
It's always going to eventually get to 0 if the input was non-negative and start going back up the chain. IsEven(1) above means that IsEven(2) and IsEven(3) is still being executed. Those method calls have not ended yet.
What the IsEven(n) method is doing is returning the opposite of the lower number. Passing in 4 means it has to check if 3 is even. Since it isn't, it will return true for 4.
As others have mentioned, I would suggest writing it out, but I would also suggest a breakpoint and using the Step-In IDE command to go into the IsEven method so you can watch the parameter value change and follow the flow as it is happening. Or at least add in some Console.WriteLine for you watch.
Let's try to understand it starting with mathematics. 0 is even by a definition. We know that each addition of 1 will flip the "eveness" of the number. So we can write the reursive rule as follows:
Base case: IsEven(0) = true
Induction: IsEven(n) = NOT( IsEven(n-1) ) ; for n > 0
So we can easily code it:
static bool IsEven(int n)
{
if (n == 0) return true;
return (!IsEven(n - 1));
}
So far so good. But note, the (!A) can be rewritten instead as this awkward condition:
if (A)
{
return false;
}
else
{
return true;
}
You can convince yourself by substituting A with true or false.
Now we just substitute A with IsEven(n-1) and paste it to the above code and get the original
static bool IsEven(int n)
{
if (n == 0) return true;
if (IsEven(n - 1))
{
return false;
}
else
{
return true;
}
}
Related
I have been googling for two days now, but can't figure this out and it seems to be basic.
Within the void OnTick(), I would like to create a variable int a;. Lets say it starts out with no value int a;, then I test condition if a is NULL or || equals 1 like this if (a == NULL || a == 1) which should always return true the first time the if statement runs due to NULL. I then assign a value to the variable a = 0;, so now a should equal 0.
This should trigger the else if(a == 0) the next time OnTick() is called, at this point I assign a = 1; resulting in the if being triggered next time round, etc and infinitum, constantly checking and assigning values switching between 0 and 1.
void OnTick()
int a;
if (PositionsTotal() < 1)
{
if(a == NULL || a == 1)
{
a = 0;
}
else if(a == 0)
{
a = 1;
}
}
I do not know what is going on, but during Testing in Strategy tester, I am getting a long string of numbers which switches between negatives and positives always with the same number -123456789 or 123456789, always 9 digits long.
Or during Debugging from Meta Editor. A random positive 3 digit number which never changes!
So far I have had both 303 and 597.
Beyond frustrating and most likely answered somewhere else.
Just not sure how to phrase the search term.
Thanks for you help.
I think the problem is that you declare your variable a inside the method OnTick, so it starts with an arbitrary value every time you call this method. Try declaring it outside this method.
In math, we have -1 * -1 = 1. When 2 negatives multiplies together, we get a positive.
However in C# bool, I am not able to find a way to do so.
int i = -1
int j = -1
bool bi = i>0
bool bj = j>0
Console.writeLine (bi)
Console.writeLine (bj)
Console.writeLine (bi && bj)
result:
false
false
false
obviously, the && is the not the right operator.
Which operator allows me to have 2 Boolean when both are false, returning true
i.e.
Console.Writeline (false false)
result true
The closest to your logic is using negated XOR:
! (bi ^ bj);
This way you'd get something like:
1 * 1 = 1
-1 * 1 = -1
1 * -1 = -1
Also you could use simple comparison operator ==:
bi == bj;
Which operator allows me to have 2 Boolean when both are false,
returning true
If you want to check two values are equal (e.g. both are true or both are false) then == (the equality operator) is your best bet.
var bob = true == true;
var bob2 = false == false;
Both bob and bob2 will be true.
This is perfect for your problem since you want to know if both numbers are negative or both numbers are positive (since in either of those scenarios, multiplying them will result in a positive number).
Console.Writeline(bi == false && bj == false) or for short (!bi && !bj)
So the assignment is as follows: you can enter all sorts of numbers but when you enter 0 two times in a row it needs to stop. The first time you enter a number your not allowed to enter 0.
This is the code I have setup:
class MainClass
{
public static void Main (string[] args)
{
int givenNumber, prevNumber;
Console.WriteLine ("Enter a number: ");
int.TryParse (Console.ReadLine (), out givenNumber);
// I've set the prevNumber to givenNumber because the variable has to be initialized
// before I can use it in the condition below. I thought setting it to the giveNumber
// wouldn't harm. Note that the first time your not allowed to enter 0
prevNumber = givenNumber;
while (givenNumber != 0 && prevNumber != 0) {
prevNumber = givenNumber; //Here is where they both are 0 at a given moment, but only after the condition.
Console.WriteLine ("Enter a number: ");
int.TryParse (Console.ReadLine (), out givenNumber);
}
Console.WriteLine ("Tada");
}
}
The problem is that it already stops when you've only entered one 0. For example if I'd first enter a 7 to start with, and my next number would be 0. When I debug it it says that my givenNumber is 0 and prevNumber is 7, when it goes back to the while condition it stops and finishes. When the program finishes the debug clearly says prevNumber = 7 and givenNumber = 0. I am using the conditional AND correct am I not?
Any clue? I'm not allowed to use arrays for this matter.
Thanks in advance
Ooh, right, you've got the logic wrong. It should be this:
while ((givenNumber != 0) || (prevNumber != 0)) {
Look up DeMorgan's laws to see why...
Your problem is with your conditional statement.
Right now you're checking whether both the givenNumber and the PrevNumber DO NOT equal 0.
So, if neither of them equals 0 then the statement will evaluate to TRUE. However, if either one of the numbers is 0 then the statement will evaluate to FALSE, since (TRUE) && (FALSE) evaluates to FALSE.
There are two ways to fix this: You can either use || (the "OR" operator) with the two "!=" statements, or you can negate the whole thing and use regular equality rather than "!=" as such: !(givenNumber == 0 && prevNumber == 0)
while (givenNumber != 0 && prevNumber != 0)
For first read value from console - number 7
givenNumer will be 7
prevNumber will be 7 too (because of assignment prevNumber = givenNumber;)
Thus while (7 != 0 && 7 != 0) will pass
Second read from Console - number 0
Thus while (0 != 0 && 7 != 0) will not pass because 0 != 0 is FALSE and while loop ends if condition is result is FALSE
I have this Or condition in an IF statement (in a foreach loop) in a Windows Form C# program:
if ((splittedFile.Count() != 3) || (splittedFile.Count() != 4))
continue;
and it always does continue, even if splittedFile.Count() is 3 or 4.
The thing is that if I remove the Or condition:
if ((splittedFile.Count() != 4))
continue;
it works properly!! Any ideas why?
This is the correct behavior, you need to use &&.
The reason is that the count is fixed number, let's say n. Now the condition reads:
n is not 3 or n is not 4.
Given n is 4, this means it is not 3, thus the test succeeds and vice versa.
A compiler can't detect this is trivially true, because between the two if statements, the Count() might change (for instance in a multithreading setting where the second thread would add/remove something to/from the collection). I agree however some analysis tools could be capable in some conditions to detect such trivial behavior. In general however such analysis can't be implemented because of Rice's theorem.
If you use &&, the expression reads:
n is not 3 and n is not 4.
Thus both conditions should be true. In other words only if n is less than three and greater than 4, the condition holds.
Try:
if ((splittedFile.Count() != 3) && (splittedFile.Count() != 4))
continue;
I know || sound logical because : if splittedFile.count is not 3 OR it is not 4 then continue; But because there are 2 NOT ! operators in the if expression an AND && is needed.
put a real number into your expression:
if( 3 != 3 || 3 != 4)
which is
if( false || true )
your expression will always be true, as splittedFile.Count() is always (not 3) or (not 4)
you want to && your results together, which looks like
(x != 3) || (x != 4)
or
!( x == 3 || x == 4)
Because one of your expressions will be always true. That's why true || something always returns true.
Let's analyze your splittedFile.Count() is 3, 4 and other than these values.
For 3, your expression will be false || true and this returns true.
For 4, your expression will be true || false and this returns true.
For other than 3 or 4, your expression will be true || true and this returns true.
Strongly suspect you are looking for && operator which provides logical-AND.
I don't understand how 's' is being used in '(+s[i])'. What is the '+' for? Also I do not understand the use of the || symbol in this way, what is it doing?
var draw = function(s){
...
if (+s[i]) a = (a+90)%360||360; // Right
else a = (a-90||360); // Left
In the code below I do not understand what 'while (n--)' does?
var getS = function(n){
var s = '';
while (n--) s += getNext(0);
return s;
};
If you want to look at this code in context go to http://fractal.qfox.nl/ and press F12 to get the developer tools up and look for dragon.js in the scripts. Please feel entirely free to post a complete translation to C# as well if you fancy the challenge.
Putting + in front of an expression coerces it into a number, e.g. from a string.
The || operator has the value of its left side if that can convert to true, otherwise the value of its right side. And so a||b would mean "use a if it's not null, false, zero or an empty string, otherwise use b".
And n-- will have boolean value false when n reaches zero.
if (+s[i]) is checking if s[i] exists and is a number != 0. In C# it would be the same as
int n;
if (int.TryParse(s[i], out n) && n != 0) { }
a = (a-90||360); is basically saying if leftside of || is null, undefined, false or zero, then take rightside. In C# it would look something like
a = (a-90 > 0)? a-90 : 360;
but a would have to be declared prior to that line.
while (n--){ } keeps repeating itself until n is 0. n must be declared prior to running that code though such as var n = 10;. In C# it would be
int n = 10;
while (n >= 0)
{
n--;
}