"함수 swap()"의 두 판 사이의 차이

6번째 줄: 6번째 줄:
==PHP==
==PHP==
[[category:PHP]]
[[category:PHP]]
;swap with temp
{{소스헤더|swap with array}}
<source lang='php'>
<source lang='php'>
list($a,$b) = array($b,$a);
list($a,$b) = array($b,$a);
15번째 줄: 15번째 줄:
}
}
</source>
</source>
{{소스헤더|swap with temp}}
<source lang='php'>
<source lang='php'>
function swap(&$a, &$b) {
function swap(&$a, &$b) {
22번째 줄: 23번째 줄:
}
}
</source>
</source>
;xor swap
{{소스헤더|xor swap}}
<source lang='php'>
<source lang='php'>
$a ^= $b ^= $a ^= $b;
$a ^= $b ^= $a ^= $b;

2018년 8월 10일 (금) 17:57 판

1 개요

swap
스왑, 교체 연산, 교체
  • 두 변수에 들어 있는 값을 서로 맞바꾸는 연산

2 PHP

swap with array
list($a,$b) = array($b,$a);
function swap(&$a, &$b) {
	list($a,$b) = array($b,$a);
}
swap with temp
function swap(&$a, &$b) {
	$temp = $b;
	$b = $a;
	$a = $temp;
}
xor swap
$a ^= $b ^= $a ^= $b;
function xor_swap(&$a, &$b) {
    $a = $a ^ $b;
    $b = $a ^ $b;
    $a = $a ^ $b;
}

3 Python

a = 3
b = 5
a, b = b, a
print( a )
# 5
print( b )
# 3
(a, b) = (b, a)

4 Perl

my ($a, $b) = (3, 5);
($a, $b) = ($b, $a);
print $a . "\n"; # 5
print $b . "\n"; # 3

5 Ruby

a = 3
b = 5
a,b = b,a
puts a
# 5
puts b
# 3

6 같이 보기

7 참고

문서 댓글 ({{ doc_comments.length }})
{{ comment.name }} {{ comment.created | snstime }}