Change a value from 0->1 or 1->0 with only mathematic operations
Asked Answered
P

6

11

I have a variable on javascrit, initialized at 0. What I'd like to do is this :

  • if the value is 0, change it to 1;
  • if the value is 1, change it to 0;

and I'll avoid conditional statement (like if/else) to check what the value is.

I think I just do it with some matematic operation; I thought to a NOT operation, but I don't know how to do that operation without

Photocell answered 2/11, 2011 at 10:7 Comment(7)
Why do you want to avoid if/else? Any reason?Efficacious
There aren't a specific reason. Just I think there is a way more quick to change a value from 0->1 or 1->0, without first check and than set the value...Photocell
By "quick" do you mean performance of the code? If so, you're looking at the wrong end: your micro-optimizing and you're probably doing it at the wrong side of the code. Make sure that you measure before you try to optimize.Efficacious
possible duplicate #1779786Trevino
@Joachim Sauer : you solution looks brillant. You don't think apply a SUM (1-x) is faster than check a variable, than edit the value?Photocell
@markzzz: I do have an intuition, but I've seen enough "optimizations" that are actually worse than the original code to know that doing optimizations by intuition is a terribly bad idea. VMs (and most JS these days is executed by a virtual machine) have a tendency to optimize common code blocks very well. So doing something the "naive" way may actually turn out to run faster than the "optimized" code. Again: measure, then optimize, then measure again!Efficacious
ok! ;) In fact I need to work on array with lenght 4, so the time to execute the code will be small in any case. I need this solution for a fast implementation of the code, and with your intuition, changing those values is a good way for me :) Thanks youPhotocell
E
45
x = 1-x;
Efficacious answered 2/11, 2011 at 10:9 Comment(0)
R
10

Short XOR syntax:

x ^= 1

Swaps 0 to 1 and 1 to 0.

Reform answered 30/3, 2017 at 18:41 Comment(2)
x ^= 0 returns 0Doublet
@Doublet its always x ^= 1 - x is switching between 0 and 1Reform
F
4

you can use xor operator:

x = x XOR 1;
Fye answered 2/11, 2011 at 10:10 Comment(1)
Note that the syntax would use ^, not XOR. So x = x ^ 1; developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…Candlenut
C
2

If the variable is let's say i

i = 1 - i, should do the trick

if i = 0, 1 - 0 = 1 than i = 1

if i = 1, 1 - 1 = 0 than i = 0

Communitarian answered 2/11, 2011 at 10:12 Comment(0)
T
2

Here is another notation, it also changes true, false to 1, 0.

x = +x;

If you want to switch the value

x = +!x;
Triparted answered 28/12, 2016 at 15:25 Comment(0)
S
0
let flip = (...array)=> {

  let res = []

for(let each of array){
 res.push([1,0][each])
 }

console.log(res)
 }

flip(0,1,1,1,0,0,1)
Smug answered 20/10, 2022 at 14:44 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.