How many ways can you write a function such that f(1) = 2 and f(2) = 1. It doesn't matter what the function returns for other values. Here are the functions I came up with in c.

Using control flow:

int f1(int i) {
	if (i == 1) return 2;
	return 1;
}

Using bitwise xor:

int f2(int i) {
	return i^3;
}

Using subtraction:

int f3(int i) {
	return 3-i;
}

Using modulus:

int f4(int i) {
	return i%2 + 1;
}

Using an array:

int f5(int i) {
	static const int arr[] = {0, 2, 1};
	return arr[i];
}

Using logical not:

int f6(int i) {
	return !(i-1) + 1;
}

Can anyone think of more solutions?

Be Sociable, Share!