[Boards: 3 / a / aco / adv / an / asp / b / bant / biz / c / can / cgl / ck / cm / co / cock / d / diy / e / fa / fap / fit / fitlit / g / gd / gif / h / hc / his / hm / hr / i / ic / int / jp / k / lgbt / lit / m / mlp / mlpol / mo / mtv / mu / n / news / o / out / outsoc / p / po / pol / qa / qst / r / r9k / s / s4s / sci / soc / sp / spa / t / tg / toy / trash / trv / tv / u / v / vg / vint / vip / vp / vr / w / wg / wsg / wsr / x / y ] [Search | Free Show | Home]

Let's see what you got, /g/. Swap the values in the most

This is a blue board which means that it's for everybody (Safe For Work content only). If you see any adult content, please report it.

Thread replies: 130
Thread images: 13

File: 1492494388261.jpg (52KB, 480x480px) Image search: [Google]
1492494388261.jpg
52KB, 480x480px
Let's see what you got, /g/. Swap the values in the most efficient way possible. Any language is valid.

a = 5
b = 7
>>
b = 5
a = 7
>>
>>59957782
winrar
>>
>>59957764
Pseudolanguage:: C++ ish

int a = 5;
int b = 7;

temp = a;
a = b;
b = temp;
>>
File: 1463521789082.gif (1MB, 300x200px)
1463521789082.gif
1MB, 300x200px
function swap(&$x,&$y) {
$x ^= $y ^= $x ^= $y;
}
>>
a = 5
b = 7

c = a
a = b
b = c


>>59957845

XOR swap is actually pretty inefficient, especially when you have to dereference a pointer.
>>
>>59957764
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);
}
}
>>
>>59957818
>>59957904
using a third variable is inefficient.

>>59957845
too much bullshit

>>59957931
wtf are you doing? worst of both worlds, desu
>>
>>59957998
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
>>
>>59957764
if a == int('5'):
a=b
b=a
else:
print('Already done Retard')
>>
File: 3oz8xLd9DJq2l2VFtu.gif (1MB, 480x287px) Image search: [Google]
3oz8xLd9DJq2l2VFtu.gif
1MB, 480x287px
>>59957998
>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.
>>
>>59958007

this, >>59958033, 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.
>>
>>59958034
2nd line = instead of :=
>>
>>59958101
uh, nope. this >>59958033 is more efficient. Same amount of operations, no extra variables.
>>
>>59958109

you are correct
>>
echo "100" > /proc/sys/vm/swappiness
>>
>>59957998
>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.
>>
>>59957764

>Any language is valid.

Well then..

a,b = b,a
>>
>>59958033
Beautiful
I really hope you got that answer yourself
>>
>>59958160
>>I just completed the introductory programming course on codecadamy

completed it a few months ago ;^)
>>
>>59957764
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
>>
>>59958033

I don't see how that is efficient in any way.
>>
>>59958108
>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
>>
File: swap-optimization.png (128KB, 1920x1080px)
swap-optimization.png
128KB, 1920x1080px
>>59958129
>>59958101

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.
>>
>>59958129
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 >>59958033 would be useless.
>>
var c=a
a=b
b=c

seems pretty obvious, am I missing something here
>>
>>59958238
Number()
>>
>>59957764
a+=2;
b-=2;
duh
>>
>>59957764
a += b;
b = a - b;
>>
>>59958306
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.
>>
>>59957764
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
>>
>>59958414
Forgot
a = a - b;
>>
>>59958424
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
>>
File: scoob.jpg (52KB, 576x472px)
scoob.jpg
52KB, 576x472px
>>59958033
a = 0.1
b = 0.2
>>
>>59957764
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;
>>
>>59958306
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.
>>
>>59958209

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
>>
File: swap-optimization.png (152KB, 1920x1080px)
swap-optimization.png
152KB, 1920x1080px
>>59958501
>>59958424

Well well well

>>59958542
Oyyy beat me to it
>>
>>59958542
mov eax, [rsi]
xchg eax, [rdi]
xchg eax, [rsi]
>>
>>59958471
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 <typename T>
void swap(T& a, T& b)
{
T temp;
temp = a;
a = b;
b = temp;
}


No dumb trickery.
>>
VHDL?
process (clk)
begin
a<=b;
b<=a;
end process;
>>
>>59957998

>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.
>>
>>59958033
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.
>>
>>59957904
This is the best way, any modern compiler should be able to optimize that away.
>>
>>59958599
>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.
>>
>>59958479
>>59958033

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
>>
>>59958833

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)
>>
>>59958992
kek
>>
You motherfuckers are incredibly dense. This thread is the most literal definition of stupidity.
>>
>>59959069
kek

a, b = b, a


/thread
>>
>>59957931
are you retarded?
>>
>>59957764
a = 5;
b=7;

b ^= a;
a ^= b;
b ^= a;
>>
a += b;
b = -(b - a);
a = a - b;
>>
>>59958728

Euros use cents too
>>
>>59957764
lmao those drumpftards are totally stumped now
>>
>>59957764
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.
>>
>>59957764
just type a in place of b and vice versa from now on in the program
>>
>>59959707
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
>>
>>59957764
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)
>>
>>59960279
>a,b = swapVar(a,b)
Or, you know,
a, b = b, a
>>
>>59960334
Yeah yeah, I wanted to create a retarded function.
>>59960363
>>
File: 1492381645410.jpg (69KB, 692x1000px)
1492381645410.jpg
69KB, 692x1000px
>>59957764
move.l #5, d0
move.l #7, d1
exg.l d0, d1
>>
>>59957764
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
>>
>>59958171
You still have to specify what the language is if it's not one that's easily recognized.

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

>>59958542
>not passing arguments in registers
>not using the xchg instruction
>>
>>59959683
If you're going to implement your function in pure asm, you might as well write it in asm and not in C.
>>
>>59957764
C++11+: std::swap(a,b);
>>
>>59958542
>>59958583
why yall assemblies different
>>
>>59961103
>>not passing arguments in registers
>>not using the xchg instruction

See
>>59960763

99% of the time the values you're swapping aren't in registers, they're in arrays. xchg implicitly locks when used with memory.
>>
>>59960632
>exg.l
what trickery is this
>>
>>59957764
xchg a, b
>>
>>59961199
http://68k.hax.com/EXG
>>
>>59961199
long exchange
>>
File: 1492471070861.jpg (46KB, 306x513px) Image search: [Google]
1492471070861.jpg
46KB, 306x513px
>>59959427
why would you create a tuple
faggot
>>
File: 18+fantano.jpg (53KB, 930x930px) Image search: [Google]
18+fantano.jpg
53KB, 930x930px
>>59958637
>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]
>>
>>59957764

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?
>>
>>59958765
We're working with a machine that only has 4 bytes of memory
>>
>>59962891
>what are registers
>>
>>59958882
You're the most annoying trip by far, so you're a retard
>>
File: 20.jpg (13KB, 225x225px)
20.jpg
13KB, 225x225px
haskell

main :: IO ()
main = do
let a = 5
let b = 7
let c = a
let a = b
let b = c
print a
print b
>>
>>59963092
I am honestly surprised that Haskell doesn't have some magical bullshit way to do this.
>>
File: 1483131407584.png (1MB, 1200x1198px) Image search: [Google]
1483131407584.png
1MB, 1200x1198px
>>59963159
It does have some bullshit mutable variables but they're hardly ever used, because nearly all the time you don't need something that does that. Mine is just a bit of a joke, it doesn't actually change the value of the variable, it just overrides the binding with a new binding.
>>
>>59961294
You are the most retarded person in this thread
>>
>>59958134
>using a swap partition
>>
>>59957764
mov eax, 5
mov ebx, 7
xor eax, ebx
xor ebx, eax
xor eax, ebx

what do I win?
>>
>>59963258
Nothing because you created a dependency chain. 3 xors is literally the slowest way to do this.
>>
>>59958108

> will also fail if the two variables being swapped are the same value

Are you retarded? that's like saying it'll fail if any of the bits are set in both variables.

a = 5
b = 5

a ^= b # a = 0, b = 5
b ^= a # a = 0, b = 5
a ^= b # a = 5, b = 5


I mean I agree that xor swap is stupid, but the fact that it gets set to zero in the middle is no different than the fact that it gets set to the xor of both values if they're anything else.
>>
>>59961294
This doesn't create a tuple.
  1           0 LOAD_NAME                0 (b)
3 LOAD_NAME 1 (a)
6 ROT_TWO
7 STORE_NAME 1 (a)
10 STORE_NAME 0 (b)
>>
>>59957764
if (a == 5)  {
a = b
}
if (b ==7) {
b = a
}

wasnt hard
>>
>>59964172
I think he meant if they point to the same value, or are the same variable.

>>59964207
Anon, I...
>>
>>59964207
> a = 7
> b = 7
> nice b8
>>
File: 1479328557531.jpg (74KB, 640x460px)
1479328557531.jpg
74KB, 640x460px
you're a ok guy OP
>>
a,b = b,a
>>
>>59957764
#include <string>
#include <cmath>
#include <iostream>
#include <vector>

int a = 5;
int b = 7;
bool done = false

while(!done)
{
int orig_A = 5;
int orig_B = 7;

for(int x = 0; x <= b; x++)
{
a = x;
}

for(int y = 0; y <= a; y++)
{
b = x;
}
if (a == orig_B && b == orig_A)
{
done = true;
}
}


rate my efficiency
>>
>>59965647
>for(int x = 0; x <= b; x++)
> {
> a = x;
> }
> for(int y = 0; y <= a; y++)
> {
> b = x;
> }
whoops
>>
File: swap.png (907KB, 1478x545px)
swap.png
907KB, 1478x545px
>>59957764
can I just do this?
>>
>>59957764
a=a+b
b=a-b
a=a-b
>>
>>59959650
yeah like 0.05
>>
swap(a,b);
>>
>>59958129
>Same amount of operations
>three stores vs three stores and 3 arithmetic operations

kys
>>
>>59957764
std::swap(a,b);
>>
>>59957931
b = b - c
>>
>>59958306
/g/ is fucking retarded, I have no hope for you fucks.
>>
>>59961103
>You still have to specify what the language is if it's not one that's easily recognized.

It's Python.
>>
>>59957764
(let ((t b))
(setf b a)
(setf a t))
>>
>>59957764

 move.b #a, D1
move.b #b, <a>
move.b #D1, <b>


Y'all cowards don't even smoke crack
>>
>>59958306
Typical ryzen user.
Thread posts: 130
Thread images: 13


[Boards: 3 / a / aco / adv / an / asp / b / bant / biz / c / can / cgl / ck / cm / co / cock / d / diy / e / fa / fap / fit / fitlit / g / gd / gif / h / hc / his / hm / hr / i / ic / int / jp / k / lgbt / lit / m / mlp / mlpol / mo / mtv / mu / n / news / o / out / outsoc / p / po / pol / qa / qst / r / r9k / s / s4s / sci / soc / sp / spa / t / tg / toy / trash / trv / tv / u / v / vg / vint / vip / vp / vr / w / wg / wsg / wsr / x / y] [Search | Top | Home]

I'm aware that Imgur.com will stop allowing adult images since 15th of May. I'm taking actions to backup as much data as possible.
Read more on this topic here - https://archived.moe/talk/thread/1694/


If you need a post removed click on it's [Report] button and follow the instruction.
DMCA Content Takedown via dmca.com
All images are hosted on imgur.com.
If you like this website please support us by donating with Bitcoins at 16mKtbZiwW52BLkibtCr8jUg2KVUMTxVQ5
All trademarks and copyrights on this page are owned by their respective parties.
Images uploaded are the responsibility of the Poster. Comments are owned by the Poster.
This is a 4chan archive - all of the content originated from that site.
This means that RandomArchive shows their content, archived.
If you need information for a Poster - contact them.