Let's see what you got, Sup Forums. Swap the values in the most efficient way possible. Any language is valid

Let's see what you got, Sup Forums. Swap the values in the most efficient way possible. Any language is valid.

a = 5
b = 7

Other urls found in this thread:

68k.hax.com/EXG
twitter.com/SFWRedditGifs

b = 5
a = 7

winrar

Pseudolanguage:: C++ ish

int a = 5;
int b = 7;

temp = a;
a = b;
b = temp;

function swap(&$x,&$y) {
$x ^= $y ^= $x ^= $y;
}

a = 5
b = 7

c = a
a = b
b = c

XOR swap is actually pretty inefficient, especially when you have to dereference a pointer.

c=b-a
a=c+a
b=c-b

import java.io.*;
import java.util.*;

public class CumSwap (String args[]) throws IOexecption {
public static void main (void) {
int a = 5;
int b = 6;

if (a < 6) {
a = 6;

}
System.out.println ("a = " + a);

if (b > 5) {
b = 5;
}
System.out.println ("b = " + b);
}
}

using a third variable is inefficient.

too much bullshit

wtf are you doing? worst of both worlds, desu

Please give the correct answer, then.

a = 5
b = 7

a = a + b
b = a - b
a = a - b

:^)

a, b := 5, 7
a, b := b, a

if a == int('5'):
a=b
b=a
else:
print('Already done Retard')

>using a third variable is inefficient.

Unless your CPU architecture literally consists of 2 registers, that's the most efficient way. It's certainly the most efficient way in x86.

this, , for example

Reminder that a temporary swap variable will be optimized away by the compiler on platforms with a swap instruction.
Reminder that xor swap will *not* be optimized by the compiler, and will also fail if the two variables being swapped are the same value, so you have to add an extra if statement to check for that making it even slower.

The correct answer in C++ is to use std::swap
The correct answer in any other compiled language that lacks a dedicated pre-optimized swapping function is to use a temporary variable and let the compiler optimize it away.

2nd line = instead of :=

uh, nope. this is more efficient. Same amount of operations, no extra variables.

you are correct

echo "100" > /proc/sys/vm/swappiness

>I just completed the introductory programming course on codecadamy
Using a third variable is not inefficient and will be optimized out by a compiler if the architecture supports it.

>Any language is valid.

Well then..

a,b = b,a

Beautiful
I really hope you got that answer yourself

>>I just completed the introductory programming course on codecadamy

completed it a few months ago ;^)

In Monkey
A vale 5 e B vale 7 só que ao contrário.

it seems easy to do in assembly
push a onto the stack
load b into a
load the top value (a) from the stack into b

I don't see how that is efficient in any way.

>a temporary swap variable will be optimized away by the compiler on platforms with a swap instruction

how do I know if my compiler has a swap instruction?

What if the two values are strings?

Nice try math fags you fail again

Actually we were both wrong, gcc optimizes both into a single instruction. Compiled with gcc 6.3 -O3 on Ryzen 1700, YMMV.

>worrying about the efficiency of trivial shit like this
you are all failures.

Define "more efficient".

I doubt an ADD or SUB will use fewer cycles than a MOV. At any rate you are unlikely to experience performance problems with such a simple example that this sort of optimization is futile.

Now if the challenge was to exchange 2 large buffers efficiently that would make more sense. And this solution would be useless.

var c=a
a=b
b=c

seems pretty obvious, am I missing something here

Number()

a+=2;
b-=2;
duh

a += b;
b = a - b;

Compile it as a function that takes a and b because GCC is optimizing it based on A and B being different in your current example.

public static void main(String[] args) {
int a = 5;
int b = 8;
int temp;

temp = a + b;
b = temp - b;
a = temp - a;

System.out.println("variable (a) is now " + a);
System.out.println("variable (b) is now " + b);
}
}

b ^= a
a ^= b
b ^= a

Forgot
a = a - b;

Doesn't really work. Without optimization the one with the c variable wins by one instruction, with optimization it edits everything out because the function does nothing, as they are all stack variables. You want me to do it with pointers to variables?

>caring about optimization on something as trivial as this
lol

a = 0.1
b = 0.2

a = a + b
b = a - b
a = a - b

for(i in range(b)):
a++
for(i in range(a)):
b--
for(i in range(-b)):
a++
b++

a = 7;
b = 5;

Are you retarded?
That just makes EAX 0 then returns that 0.
The compiler optimised the code and saw that you didnt need either of that and juat removed it. Try printing the values afterward, nigger.

Humor refinado

Eh.... Idk.... Pudding?

Anything that the compiler turns into an XCHG instruction (x86) is efficient

void swap(int *a, int *b)
{
int c = *a;
*a = *b;
*b = c;
}


void swap2(int *a, int *b)
{
*a = *a + *b;
*b = *a - *b;
*a = *a - *b;
}

-O3
swap(int*, int*):
mov eax, DWORD PTR [rdi]
mov edx, DWORD PTR [rsi]
mov DWORD PTR [rdi], edx
mov DWORD PTR [rsi], eax
ret
swap2(int*, int*):
mov eax, DWORD PTR [rsi]
add eax, DWORD PTR [rdi]
mov DWORD PTR [rdi], eax
sub eax, DWORD PTR [rsi]
mov DWORD PTR [rsi], eax
sub DWORD PTR [rdi], eax
ret

Well well well

Oyyy beat me to it

mov eax, [rsi]
xchg eax, [rdi]
xchg eax, [rsi]

this

Fuck your magic tricks. Just write semantic code: the third wheel swap is perfect. This bullshit here with the little math trick might work in practice but anyone reading it is gonna have to think and figure out wtf you intend that block of code to do. You're adding and subtracting shit when all that was said was "swap these". So just swap em like you would items on your desk.

Also fuck any numbers that aren't integers: the fucking inaccuracy where 0.3-.0.2!=0.1 rustles my jimmies. I actually wrote a store stock management program that had to do all sorts of math using nothing but integers. The base unit was 1/1000th of a euro so that the rounding error from integers wouldn't matter unless someone cares about a single stupid cent in the end of year report. If it mattered that much I could just keep increasing the fraction, nobody cares about a price being off by 0.0001 cents.

template
void swap(T& a, T& b)
{
T temp;
temp = a;
a = b;
b = temp;
}


No dumb trickery.

VHDL?
process (clk)
begin
a

>using a third variable is inefficient
Variables are not guaranteed to be stored in memory or in registers. An optimizing compiler will track the lifetime of variables and optimize out various interactions with them. In my code, since c is only read from once, it is obvious to the compiler that it is a temporary. The compiler can therefore optimize it out to an xchg instruction (in x86) or an xor swap, or a couple of mov instructions with a temporary register if one is available. It may also do none of the above, and simply use a to mean b in the future, and b to mean a. For instance, if a is r0, and b is r1 beforehand, when I reference a after the swap, I might use r1 instead and optimize the swap to a no-operation.

This sort of solution is cute and all, but it only works for numbers. In practice you often work with more complex structures or larger buffers and can't rely on basic arithmetic to swap.

This is the best way, any modern compiler should be able to optimize that away.

>nobody cares about a price being off by 0.0001 cents

you mean 0.0001 euros, right?

temp = a
a = b
b = temp

Truly the most efficient use of your time
inb4 some moron starts whining about how his program is too slow to execute this way, what the fuck are you doing?

LDA a
LDX b
STA b
STX a

12 cycles if on the zero page.

this is the correct solution to the OP, and even though it's practically useless, it is a common question at interviews: "do a swap without using a third variable" and the interviewee just opens his eyes wide like an idiot. Useless, but it could save your ass

We were not asked to do a swap without a third variable. We were asked to do a swap in the most efficient way. It so happens that the use of a third variable is the most optimal way to swap.

a = 5
b = 7

print("A = ",B, "And B =",A)

kek

You motherfuckers are incredibly dense. This thread is the most literal definition of stupidity.

kek

a, b = b, a


/thread

are you retarded?

a = 5;
b=7;

b ^= a;
a ^= b;
b ^= a;

a += b;
b = -(b - a);
a = a - b;

Euros use cents too

lmao those drumpftards are totally stumped now

ARM Assembly
#define SWAP_32P(X,Y) \
({__asm("ldr r5, [%0, #0];" \
"ldr r4, [%1, #0];" \
"str r5, [%1, #0];" \
"str r4, [%0, #0];" \
: "+r"(X), "+r"(Y) :: "r4","r5");})

int a = 5;
int b = 7;

SWAP_32P(&a, &b);

If you need to swap you fucked up.

just type a in place of b and vice versa from now on in the program

it's a pointless academic/recreational thing. this is not an advice thread.

>language has state

Assuming eax = 0005h, and ebx=0007h, here it is in x86 ASM:

CPU optimized:
xor eax,ebx
xor ebx,eax
xor eax,ebx

Memory Optimized (not sure why you'd want this but whatever)
push eax
push ebx
pop eax
pop ebx

ezpz

What swap the values of the variable? Or just output to stdout?

Python:
def swapStdout(a,b):
print("a swapped with b: " + str(b))
print("b swapped with a: " + str(a))

def swapVar(a,b):
return b,a
a=5
b=7
a,b = swapVar(a,b)

>a,b = swapVar(a,b)
Or, you know, a, b = b, a

Yeah yeah, I wanted to create a retarded function.

move.l #5, d0
move.l #7, d1
exg.l d0, d1

if both values are in registers
xchg r32, r32

if one or both are in memory, xchg locks the processor to support multiple threads and the instruction takes 30x as many clock cycles. you would need to move both to registers and takes 4 instructions:
movzx eax, m32-1
movzx ebx, m32-2
mov m32-1, ebx
mov m32-2, eax

You still have to specify what the language is if it's not one that's easily recognized.

Look at the assembly output. Not that it matters anyway, optimization is the compiler's job.

>not passing arguments in registers
>not using the xchg instruction

If you're going to implement your function in pure asm, you might as well write it in asm and not in C.

C++11+: std::swap(a,b);

why yall assemblies different

>>not passing arguments in registers
>>not using the xchg instruction

See
99% of the time the values you're swapping aren't in registers, they're in arrays. xchg implicitly locks when used with memory.

>exg.l
what trickery is this

xchg a, b

68k.hax.com/EXG

long exchange

why would you create a tuple
faggot

>the only smart person in the thread was a trip
;|

ruby
a,b = b,a
go
a,b = b,a

python
a, b = b, a

Javascript
[a,b]=[b,a]

format ELF executable 3
entry start

segment readable executable

start:
push dword[a]
push dword[b]
pop dword[a]
pop dword[b]
ret

segment readable writeable
a dd 5
b dd 7

is this supposed to be difficult?

We're working with a machine that only has 4 bytes of memory