Jump to content

Switching Variables Game

- - - - -

  • Please log in to reply
5 replies to this topic

#1
BlaineSch

BlaineSch

    Writes binary right handed and hex left handed

  • Members
  • PipPipPipPipPipPipPipPipPip
  • 2,448 posts
So the point of the game, using any language, is to switch the value of two variables in a unique way. It does not have to be efficient.

Traditionally you'd have a temporary variable, assign the first variable to it, assign the second variable the first variable, then the first the temporary variable.

<?PHP
$a = "CodeCall!";
$b = "Hello ";

$t = $b;
$b = $a;
$a = $t;

echo $a.$b; //Hello CodeCall!


#2
nicckk

nicckk

    Programming God

  • Members
  • PipPipPipPipPipPipPip
  • 629 posts
In Java


public class XOR

{

	public static void main(String[] args)

	{

		int ii1 = 1;

		int ii2 = 2;


		System.out.print(ii1 + " ");

		System.out.println(ii2);

		ii1 ^= ii2;

		ii2 ^= ii1;

		ii1 ^= ii2;

		System.out.print(ii1 + " ");

		System.out.println(ii2);

	}


}



#3
Alexander

Alexander

    It's Science!

  • Moderators
  • 4,118 posts
  • Location:Vancouver, Eh! Cleverness: 200
XOR is for sissies.
#include <stdio.h>

int main(void) {
  int ii1 = 1234567890;
  int ii2 = 42;
  ii1 = ii1 + ii2;
  ii2 = ii1 - ii2;
  ii1 = ii1 - ii2;
  printf("%d %d", ii1, ii2);
  return 0;
}

Be sure to read the updated FAQ! || Health is achieved through the same 10,000 steps.
If a suggested code/method fails, informing us is less important than telling us why or what errors occurred.

#4
wim DC

wim DC

    Writes binary right handed and hex left handed

  • Members
  • PipPipPipPipPipPipPipPipPip
  • 2,084 posts
  • Programming Language:Java, JavaScript, PL/SQL
  • Learning:Java
Hmmmm, sounds like I need to store the variables in a list, reverse the list, and then take them out again.

import java.util.ArrayList;

import java.util.Collections;

import java.util.List;


public class Whatever{

public static void main(String[] args) {

        int a=0;

        int b=2;

        List<Integer> list = new ArrayList<Integer>();

        list.add(a);

        list.add(b);

        Collections.reverse(list);

        a = list.get(0);

        b = list.get(1);

        System.out.println("a: " + a + "   b: " + b);

}

}



#5
eafkuor

eafkuor

    Programming Professional

  • Members
  • PipPipPipPipPip
  • 218 posts
Using RSA, ladies :thumbup:

int main(){

	int a=2, b=8;


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

	a=a*a*a;

	b=(a*a*a)%15;

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

}


#6
BlaineSch

BlaineSch

    Writes binary right handed and hex left handed

  • Members
  • PipPipPipPipPipPipPipPipPip
  • 2,448 posts
This method required they both be an array:

<script type="text/javascript">
    var a = [0, 1];
    console.log(a); // [0, 1]
    a = [a[1], a[0]];
    console.log(a); // [1, 0]
</script>





1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users