Alex Rivera | Logout

Is there a better way of writing v = (v == 0 ? 1 : 0);

Asked 2011-08-02T11:22:54.547
490

I want to toggle a variable between 0 and 1. If it's 0 I want to set it to 1, else if it's 1 I want to set it to 0.

This is such a fundamental operation that I write so often I'd like to investigate the shortest, clearest possible way of doing it. Here's my best so far:

v = (v == 0 ? 1 : 0);

Can you improve on this?

Edit: the question is asking how to write the above statement in the fewest characters while retaining clarity - how is this 'not a real question'? This wasn't intended to be a code-golf exercise, though some interesting answers have come out of people approaching it as golf - it's nice to see golf being used in a constructive and thought-provoking manner.

Edit
Report

4 Answers

37

in general whenever you need to toggle between two values , you can just subtract the current value from the sum of the two toggle values :

    0,1 -> v = 1 - v
    1,2 -> v = 3 - v
    4,5 -> v = 9 - v 
answered 2011-08-03T13:37:18.227
24

List of solutions

There are three solutions I would like to propose. All of them convert any value to 0 (if 1, true etc.) or 1 (if 0, false, null etc.):

  • v = 1*!v
  • v = +!v
  • v = ~~!v

and one additional, already mentioned, but clever and fast (although works only for 0s and 1s):

  • v = 1-v

Solution 1

You can use the following solution:

v = 1*!v

This will first convert the integer to the opposite boolean (0 to True and any other value to False), then will treat it as integer when multiplying by 1. As a result 0 will be converted to 1 and any other value to 0.

As a proof see this jsfiddle and provide any values you wish to test: jsfiddle.net/rH3g5/

The results are as follows:

  • -123 will convert to integer 0,
  • -10 will convert to integer 0,
  • -1 will convert to integer 0,
  • 0 will convert to integer 1,
  • 1 will convert to integer 0,
  • 2 will convert to integer 0,
  • 60 will convert to integer 0,

Solution 2

As mblase75 noted, jAndy had some other solution that works as mine:

v = +!v

It also first makes boolean from the original value, but uses + instead of 1* to convert it into integer. The result is exactly the same, but the notation is shorter.

Solution 3

The another approach is to use ~~

answered 2011-08-17T16:45:04.780
10

Another way to do it:

v = ~(v|-v) >>> 31;
answered 2011-08-18T19:51:29.530
5

If possible values for v are only 0 and 1, then for any integer x, the expression: v = Math.pow((Math.pow(x, v) - x), v); will toggle the value.

I know this is an ugly solution and the OP was not looking for this...but I was thinking about just another solution when I was in the loo :P

answered 2011-08-05T10:50:23.923

Your Answer