Coding Challenges

I like to pose programming challenges to my friends every now and again, usually when I want to share some programming knowledge in an interesting way. I figured these challenges might be fun for the wider public too, so I'll keep an updated list here. Enjoy! Solutions and post-mortem thoughts can be found here.


Challenge #1: Color Channel Picker

2015-08-03
Language: any
Challenge: Write a function that takes a single integer input, and returns a single character. Assume the input will only ever be 0, 1, or 2. If the input is 0, return 'r'. If the input is 1, return 'g'. If the input is 2, return 'b'.
How small can you make the function?


Challenge #2: Floating-point Negativity

2015-09-08
Language: any
Challenge: Write a function that takes in a single floating-point number as a parameter, and returns a boolean value. If the number is negative, return true, otherwise return false.
You are not permitted to use any of the following operators: >, <, >=, <=.


Challenge #3: Copy and Assign

2015-09-22
Language: C++
Challenge: Without compiling it, determine what the output of the following program will be.

#include <cstdio>

class Foo
{
public:
    Foo()
    {
        printf("constructor\n");
    }
    Foo(const Foo& p_arg)
    {
        printf("copy constructor\n");
    }
    Foo& operator =(const Foo& p_arg)
    {
        printf("assignment operator\n");
        return *this;
    }
};

int main()
{
    Foo a;
    Foo b(a);
    Foo c = a;
    getchar();
    return 0;
}

Now compile it and run it. Were you right?


Challenge #4: Untitled

2015-09-26
Language: C++
Challenge: Without compiling it, determine what the output of the following program will be.

#include <cstdio>

class Foo
{
public:
    Foo() { }
    int bar;
};

int main()
{
    Foo foo;
    printf("0x%08X\n", foo.bar);
    getchar();
    return 0;
}

Now compile it and run it. Were you right?


Challenge #5: Operators

2015-10-04
Language: C++
Challenge: Without modifying the main function, make this code compile and calculate the correct values of vf, fv, and vv. How many operators do you need?

class Vec3
{
public:
    Vec3(float x, float y, float z) : x(x), y(y), z(z) { }
    float x, y, z;
};

int main()
{
    Vec3 foo(1.f, 2.f, 3.f);
    Vec3 vf = foo * 5.f; // Vec3(5.f, 10.f, 15.f)
    Vec3 fv = 5.f * foo; // Vec3(5.f, 10.f, 15.f)
    Vec3 vv = foo * foo; // Vec3(1.f,  4.f,  9.f)
    return 0;
}

Challenge #6: Inconsistency

2015-10-07
Language: C/C++
Challenge: What might cause the following code to fail to compile? Assume that the included 'bar.h' file exists, and does not contain any symbol redefinitions or abuse of #define that would affect main.

#include <stdio.h>
#include "foo\bar.h"

int main()
{
    printf("Hello, World!\n");
    return 0;
}