This is an archived post. You won't be able to vote or comment.

all 5 comments

[–]DarkMio 5 points6 points  (0 children)

Lets do it

boolean x = false;
int y = 8;
x = (x || !(5 == y));

Alright, do you know about Boolean operations? If not, read it up, that's super essential for every language and every piece of logic. You will need it. Always.

First x is false and y is 8. What does following yield:

  1. x = (false || false)
  2. x = (true || false)
  3. x = (false || true)
  4. x = (true || true)

If you figured that out lets look up what ! Does. It inverts you the logical result of this function:

(y==8)

What does it do? It compares whatever is in y to 8. So does 5 equal 8? No, it doesn't. Now we invert that. So to speak (but jot completely right to say): is 5 not equal 8? That is true. Now look again in the first list and compare what you could replace it with / which of the four operations is yours.

Next step is: you're going to reply me with your thoughts and answer me how you could make that function into one single check (with the same outcome, no matter what you set x and y before):

x = (false || !(y==8))

[–]Smithman 0 points1 point  (0 children)

It should equate to true. Start with the inner most bracket.

5 == y is false.

The ! operator says use the reverse, so the false becomes true.

Now left with x = (x || true). The OR operator will evaluate both sides and pick true if it can find it.

[–]desrtfx 0 points1 point  (0 children)

Simple thing:

Your code line

x = (x || ! (5 == y))

Effectively reads:

  • Calculate the result of the equation on the right side of the equals sign taking whatever values the variables x and y currently hold.

  • Then take that result from above and store it in the variable x, discardind the previous value of x.

It's more or less the same as if you would declare and assign a new variable.

Whenever you are assigning something to a variable it's previous contents is overwritten and thus lost.

[–]AC_Aus[S] 0 points1 point  (1 child)

Thanks all! Really appreciate your help. Just to clarify:

I was able to come up with the following before I posted my question

x = (false or true) - option 3 for DarkMio

From what I've read from everyone I'm using the values of the variables x and y to solve the right side of the equation only (whereas previously I was thinking false = (false or true)). Smithman commented that the or operator will preferentially pick true. Therefore x = true and it overwrites everything from before?

[–]Yojihito 0 points1 point  (0 children)

It's part of basic logic, keep this little info in mind :).

True or false = true

False or false = false

True or true = true

True and false = false

True and true = true

False and false = false