Occasionally people share entertainingly bad solutions to basic programming interview questions. In that same spirit, I dump some compositions here.
Table of Contents
Checking whether a number is even by using C strings
bool isEven(int n) {
char a[30];
sprintf(a, "%d", ((n >> 1) << 1) - n);
sprintf(a + strlen(a) + 1, "%d", n - ((n >> 1) << 1));
return strlen(a + strlen(a) + 1) + 1 > strlen(a);
}
Checking whether a number is even by using AI data annotation
using System.Windows.Forms;
bool IsEven(int n)
=> DialogResult.Yes == MessageBox.Show($"Is {n} even?", default, MessageBoxButtons.YesNo, default, default, default, default, default);
Checking whether a number is even by using automated theorem proving
using Microsoft.Z3;
bool IsEven(int value) {
using var ctx = new Context();
var n = ctx.MkIntConst("n");
var solver = ctx.MkSolver();
solver.Assert(ctx.MkEq(ctx.MkInt(value), n));
solver.Assert(ctx.MkEq(n, ctx.MkMul(ctx.MkIntConst("k"), ctx.MkInt(2))));
return solver.Check() == Status.SATISFIABLE;
}
Checking whether a number is even by using a graph
class LinkedListNode<T> {
public T Value { get; set; }
public LinkedListNode<T> Next { get; set; }
}
static LinkedListNode<bool> MakeCycle(int length) {
var first = new LinkedListNode<bool> { Value = true };
var current = first;
for (int i = 1; i < length; ++i) {
var next = new LinkedListNode<bool> { Value = false };
current.Next = next;
current = next;
}
current.Next = first;
return first;
}
public static bool IsEven(int n) {
var current = MakeCycle(2);
if (n < 0)
n = -n;
while (n --> 0)
current = current.Next;
return current.Value;
}
Checking who won in a game of rock-paper-scissors by using bitwise rotation
enum Choice {
Rock = 1,
Paper = 2,
Scissors = 4
};
enum Outcome {
Tie, FirstWins, SecondWins
};
Outcome getOutcome(Choice first, Choice second)
{
if (first == second)
return Outcome::Tie;
if (((first >> 1 | first << 2) & 7) == second)
return Outcome::FirstWins;
return Outcome::SecondWins;
}