3 lines

why not make some coding contests / quizzes.

for example, yesterday on another forum a guy posed a little challenge: write a swap function that doesn't use a temp variable.
It's not hard at all, it took me 3 mins to figure out, write, debug and re-write.

remember that thread about changing one character to make 20 times loop?

things like that would be cool (on another thread probably).

any ideas? let's start with that question:
write a swap function that doesn't use any temp variable.
 
hasan said:
write a swap function that doesn't use any temp variable.

void swap(int & a, int & b)
{
a = b + a;
b = a - b;
a = a - b;
}
 
Code:
void swap(int & a, int & b) {
	a ^= b ^= a;
	b ^= a;
}
here's another version.
 
Phisionary said:
Code:
void swap(int & a, int & b) {
	a ^= b ^= a;
	b ^= a;
}
here's another version.
Nice one, I suck at bitwise logic =P
The one I came up with was the same as ilian.

Anyone got more interesting chellenges?
 
honestly, I'd heard it could be done that way. I didn't think of it myself. I just 'rediscovered' the order. It's a neat trick though.
 
since you've just heard it, here is another one google told me about:
Code:
void swap2(int &x, int &y)
{
	x ^= y ^= x ^= y;
}

but look at this, a little fancy, not sure if it complies to the conditions, it doesn't really use a third variable, but it does kinda use storage space :/
Code:
__asm {
mov eax,a
mov ebx,b
mov b,eax
mov a,ebx
}
:p
but then again, when you add variables, the compiled code actually uses the registers. so .. go figure.
 
hasan said:
Code:
void swap2(int &x, int &y)
{
	x ^= y ^= x ^= y;
}
Don't know if you noticed it, but this is exactly the same as Phisionary's, only in 1 statement (I don't actually understand why he uses 2 :p)
 
Its the final countdown......

Hiya All,

Here's a simple countdown written in C# :-

using System;

namespace HL2CountDown
{

class CountDown
{
/// <summary>
/// Silly Half Life 2 Countdown util.
/// By FluffyERug 2004/10/05
/// </summary>
///
static System.DateTime releasedate, todaysdate;
static System.TimeSpan timeleft;

static string strReleaseDate;

[STAThread]
static void Main(string[] args)
{
if (args.Length > 1)
{
if (args[0] == "-r")
{
strReleaseDate = args[1];

System.Timers.Timer t;
t = new System.Timers.Timer(50);
t.Elapsed +=new System.Timers.ElapsedEventHandler(t_Elapsed);
t.Start();

while (1==1)
{
System.Threading.Thread.Sleep(10);
}
}
}
else
{
Console.WriteLine("Half Life 2 Countdown by FluffyERug.\n");
Console.WriteLine("Usage: HL2CountDown -r <dd/mm/yyyy>\n");
Console.WriteLine("E.g. HL2CountDown -r 01/11/2004\n");
Console.WriteLine("CTRL-C to Exit.\n");
}
}

static void Count()
{
releasedate = Convert.ToDateTime(strReleaseDate);
todaysdate = System.DateTime.Now;
timeleft = releasedate.Subtract(todaysdate);
Console.Write(timeleft.ToString() + "\r");
}

private static void t_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
Count();
}
}
}
 
Back
Top