Wednesday, May 23, 2007

Topic on echo forum

Now, i just wanna post one "great topic" from echo discussion board, the topic started by az001 (session are using indonesian language )
teman- teman,
Gini , gw cuma mo tau gimana caranya teman2 menyelesaikan soal berikut
Ada dua variabel a & b
a = 10;
b = 20;

Nah .. gimana caranya agar dua variabel itu ditukar nilainya tanpa menambah variabel tambahan
Bisa gak ya ? ....
kharm respond it with some simple mathematic operation.
yg lbih sederhana bisa pake operasi tambah kurang kaya gini:
a:= 10;b:=12
a:= a + b; {22}
b:= a - b; {10}
a:= a - b; {12}


Interesting, isnt it ?

11 comments:

  1. versi oneliner:

    a ^= b ^= a ^= b;

    ReplyDelete
  2. lah ntu dah ada jwbnnya bos...
    versi kharm..boljug tuh

    ReplyDelete
  3. fajran : interesting one :)

    ReplyDelete
  4. raindust : kali aja ente punya ide lain bos, biar otak ente ga bulukan, **kidding**; peace:peace

    ReplyDelete
  5. versi ruby:
    a, b = b, a

    :)

    ReplyDelete
  6. kalo ga salah itu soal buat olimpiade komputer ya? iya kayaknya... :D

    ReplyDelete
  7. anonymous : wah ndak tau juga yah :), maybe yes .. maybe no :)

    ReplyDelete
  8. haha, mana ada soal olimpiade kayak gitu, toooo simple :p

    ReplyDelete
  9. anonymous: wah ndak tau juga bos, belun pernah ikut olimpiade :)

    ReplyDelete
  10. Another trick is by using xchg instruction in x86 32/64 bit. Put it inside inline asm and we're done.

    int main(int argc, char *argv[])
    {
    int a = 5;
    int b = 10;

    printf("a is %d\n",a);
    printf("b is %d\n",b);

    __asm__ __volatile__ ("xchg %0, %1":
    "=r"(a),"=r"(b):
    "0"(a),"1"(b)

    printf("a is %d\n",a);
    printf("b is %d\n",b);

    return 0;
    }
    );

    ReplyDelete