Hi!
How do you swap two variable?
Look at this! It's a C++ code.
It's the result:
This is a C code.
It's the result:
And finally, Erlang :)
It's the result:
How do you swap two variable?
Look at this! It's a C++ code.
#include <iostream> using namespace std; inline void swap_var(int& _x, int& _y) { int _ = _x; _x = _y; _y = _; } inline void swap_xor(int& _x, int& _y) { _x ^= _y; _y ^= _x; _x ^= _y; } inline void swap_math(int& _x, int& _y) { _x += _y; _y = _x - _y; _x -= _y; } int main(void) { int a = 5; int b = 77201; cout << a << ":" << b << endl; swap_var(a, b); cout << a << ":" << b << endl; swap_xor(a, b); cout << a << ":" << b << endl; swap_math(a, b); cout << a << ":" << b << endl; }
It's the result:
$ rm -f t; g++ -Wall -Wextra -Werror -O2 t.cpp -o t; ./t; 5:77201 77201:5 5:77201 77201:5 $
This is a C code.
#include <stdlib.h> #include <stdio.h> void swap_var(int* _x, int* _y) { int _ = *_x; *_x = *_y; *_y = _; } void swap_xor(int* _x, int* _y) { *_x ^= *_y; *_y ^= *_x; *_x ^= *_y; } void swap_math(int* _x, int* _y) { *_x += *_y; *_y = *_x - *_y; *_x -= *_y; } int main(void) { int a = 5; int b = 77201; (void) printf("%d:%d\n", a, b); swap_var(&a, &b); (void) printf("%d:%d\n", a, b); swap_xor(&a, &b); (void) printf("%d:%d\n", a, b); swap_math(&a, &b); (void) printf("%d:%d\n", a, b); return EXIT_SUCCESS; }
It's the result:
$ rm -f t; gcc -Wall -Wextra -Werror -O2 t.c -o t; ./t 5:77201 77201:5 5:77201 77201:5 $
And finally, Erlang :)
-module(t). -export([t/0]). swap({X, Y}) -> {Y, X}. t() -> A = {1, 2}, swap(A).
It's the result:
$ erl Erlang/OTP 18 [erts-7.3] [source] [64-bit] [smp:8:8] [async-threads:10] [kernel-poll:false] Eshell V7.3 (abort with ^G) 1> c(t). {ok,t} 2> t:t(). {2,1} 3> q(). ok 4> $
Best regards,
Vasiliy V. Bodrov aka Bodro,
May 16, 2017.
No comments:
Post a Comment