58
fiktion
9d

Deal with it bitych! 😂

Comments
  • 10
    My favorite:

    b ^= a;
    a ^= b;
    b ^= a;
  • 6
    Bitch please.

    [a, b] = [b, a];

    This is valid TypeScript.
  • 1
    @kamen TypeScript is da bae
  • 2
    @sak96
    1: b = 10 ^ 10 = 0
    2: a = 10 ^ 0 = 10
    3: b = 0 ^ 10 = 10

    Works perfectly fine.
  • 8
    Guess what's hiding behind that nifty Py syntax :)
  • 6
    XCHG R1, R2
  • 2
    Now that I checked, destructuring is also available in vanilla ES6 (though not in IE).
  • 1
    a = str(a)+str(b)
    b = int(a[:len(b)-1])
    a = int(a[len(b)-1:])

    Technically this would work in Python but the original Python method would be easier.
  • 1
    @LinusTorvald we're talking generally, not edge cases. However, if you have 2 variables with INT_MAX, why swap them?
  • 2
    @kamen even valid js
  • 2
    I've once written a Fibonacchi program in Java using only two variables. Without recursion!
    https://codegolf.stackexchange.com/...

    With recursion, it would be easy with one variable, but also horribly slow. My version has basically normal runtime.
  • 3
    a ^= b ^= a ^= b;
    // Single Line in C.
  • 3
    @Sanjeev Readable as fuck too.
  • 1
    Golang

    a, b = b, a
  • 2
    @LinusTorvald in most programming languages, INT_MAX+1 = INT_MIN, because the way overflowing works.

    Given the case of a=6 and b=7 and INT_MIN=-10 and INT_MAX = 10:
    a=a+b
    b=a-b
    a=a-b

    a = 6+7 = 13 = -7
    b= -7 - 7 = -14 = 6
    a=-7 - 6 = -13 = 7

    Therefore a and b are indeed swapped. The only case where it doesn't work if either a or b are larger than INT_MAX or less than INT_MIN
  • 1
    @LinusTorvald Not accurate. If the sum overflows, then it will just overflow back when you subtract from it.
    Let's say the range is 0-9 and a = 5, b = 7:
    a = 5 + 7 = 2
    b = 2 - 7 = 5
    a = 2 - 5 = 7
  • 1
    @Rocket3G DAMN IT
    3 MINUTES LATE
  • 1
    @Rocket3G @PaperBag That's only true for C-like languages though, and only in architectures where signed numbers are either twos complement or biased. Technically speaking, implicitly overflowing signed integers is undefined behavior because of the varying implementations in the general case.
  • 1
    @LinusTorvald the way you put it made it look like you were using an edge case where both a AND b were INT_MAX.
  • 1
    okay, which is faster? ; )
  • 1
    @tokumei
    Was about to mention that...
    (make sure to check if they are not similar!)
  • 1
    @Gregozor2121 No, it definitely should work even if they are equal.
  • 1
    @tokumei
    Wouldnt you get null if both of them are similar?
  • 2
    @Gregozor2121

    a = 0xf00d
    b = 0xf00d

    a ^= b // 0xf00d ^ 0xf00d == 0
    b ^= a // 0xf00d ^ 0 == 0xf00d
    a ^= b // 0 ^ 0xf00d == 0xf00d
  • 0
    @tokumei
    Well Cnotesforprofessionals have said otherwise that is why i had doubts
Your Job Suck?
Get a Better Job
Add Comment