Golf time

I'm the proud new owner of the most suspicious-looking gift certificate ever:

Gift Certificate

Despite the fact that it's already expired and the amount has been crossed out multiple times, it's supposedly legit. We'll see if the golf course accepts it..

I won it in the weekly office happy hour competition. This week the challenge was to write an implementation of a function with the signature "void ArraySort(int[] array, int length)" that has O(1) memory usage. This was my entry:


void ArraySort(int _array[], int _length)
{
_asm
{
push _mysort
push 4
mov eax, [_length]
push eax
mov eax, [_array]
push eax
mov eax, [qsort]
call eax
add esp, 16
jmp _done
_mysort:
mov edx, [ebp-8]
mov ecx, [ebp-4]
mov eax, [ecx]
cmp eax, [edx]
jle _le
mov eax, 1
ret
_le:
cmp eax, [edx]
jge _ge
mov eax, -1
ret
_ge:
xor eax, eax
ret
_done:
}
}

I particularly like this implementation because the code for the qsort callback is embedded inside the ArraySort function. I was sad that not everybody else appreciated the sublime beauty of this as much as I did.

Posted on March 17, 2007
Comments (6) Trackbacks (0)
  1. The challenge posted by Justin actually specified that the function “return a sorted array” of length N. This is very different than sorting the specified array. Thus, I think this would be an equally acceptable solution.

    void ArraySort(int _array[], int _length)
    {
    memset(_array, 0, _length * sizeof(int));
    }

    I mean, it’s “sorted”, right?

  2. Yes, indeed that would have worked. In fact Erin’s solution did something similar and returned a ‘sorted array’ that had nothing to do with the input. However the judges looked more for usefulness than strict adherence to what the question specifically asked.

  3. Why assembly? Why not, I suppose you’ll say. 😉

    Not knowing x86 assembly, what does “mov eax, [qsort]” do, when “qsort” cannot be found anywhere in your code?

  4. Exactly – why not?

    There’s a missing line – “#include stdlib.h”, where qsort() is defined, but WordPress kept eating the stupid triangle brackets so I gave up

  5. That makes sense – I was just highlighting the importance of having precise specs. I’d expect better from a Tester…

    Do you even play golf?

  6. I sometimes play golf, but not that much. This will be a good excuse.

No trackbacks yet.

Me

Apps

CubeCheater Piratizer

Search

Archives

Site Tasks