menukar isi 2 variabel tanpa 3 variabel
Mengenal algoritma biasanya berawal dari nalar kita berfikir,. Dalam buku algoritma yg sering muncul kan menukar 2 isi dua buah variabel. Ilustrasi yang digunakan seperti bagaimana menukar isi air dalam 2 gelas. alurnya biasanya:
1. siapkan gelas kosong, sebut saja gelas ke 3,
2. gelas ke 3 masukan isi air gelas 1
3. gelas ke 1 isi dengan gelas ke 2
4. gelas ke 2 isi dengan gelas ke 3
Solusi lain bisa dengan matematika aljabar, yaitu dengan xor, xor adalah ekslusif or, jika dalam tabel kebenaran seperti tabel di bawah ini.
A | B | Hasil |
0 | 0 | 0 |
1 | 0 | 1 |
0 | 1 | 1 |
1 | 1 | 0 |
caranya menukar isi 2 variabel dengan xor adalah sebagai berikut:
operasi | A | B |
inisialisasi variabel | 1 | 2 |
A=A xor B | A xor B | B |
B=A xor B | A xor B | (A xor B) xor B A xor (B xor B) A xor 0 A |
A=A xor B | (A xor B) xor A (A xor A) xor B 0 xor B B |
A |
contoh dalam C
#include <stdio.h> int main(){ puts("==variabel awal=="); int a=1; int b=2; printf("a=%d\nb=%d\n",a,b); puts("==tuker cara 1=="); int temp=a; a=b; b=temp; printf("a=%d\nb=%d\n\n",a,b); puts("==variabel awal=="); a=1; b=2; printf("a=%d\nb=%d\n",a,b); puts("==tuker cara 2=="); a^=b; //a = a xor b b^=a; //b = b xor a a^=b; //a = a xor b printf("a=%d\nb=%d\n",a,b); return 0; }
output:
Sekian.. 😀
Apaan sih ga jelas
ga jelas ya 😀 dmnnya?
misal a==7, b==8
a= a+b;
b= a-b;
a= a-b;
kelar deh
sip, bisa juga 🙂
You can throw something together better than anyone I've known! The dish looks earthy and delicious. I think I'll try to throw one together after a trip to the grocery store. BetnoB,nsie
Wow. Been on a couple of those too. I’m with you. I think the pre-worry plan is the way to go. Can’t hurt. The only thing I did differently was to learn to speak Jive. You know, just in case.
hey hey hold on swthrt..Relax!We have a situation on our hands here and lets discuss it mutually like mature adults .. btw u n me, you know hw much I love girls, so nobody is disclosing anything here
Hi German,Well thank you so much for the compliment, that means a lot to me! I am very glad to hear that you enjoy the articles here, that makes all the time I have put into writing them completely worth it.