Recently, in reddit / csharp sub-reddit, there is a post regarding an interview task. Here’s the original post:
https://www.reddit.com/r/csharp/comments/17nqel6/interview_task_2_review/
I asked ChatGPT 4.0 to try to generate a code for this task.
try to create a number-guessing game.
The desired number is between 1-100 (both inclusive),
and whenever the player guess a number,
the player should be told if he/she is closer to,
or further from, the correct answer.
The player should also - of course - be told if he/she is spot on.
use very complex, advance, very high sophisticated,
quantum physics-like mathematical equations to find this out
do this in pure C#
Result:
using System;
class QuantumGuessingGame
{
static Random random = new Random();
static int desiredNumber = random.Next(1, 101);
static int temperature = 100; // Start with a high temperature
static int coolingRate = 5; // Rate at which we decrease temperature (cool down)
static void Main()
{
Console.WriteLine("Welcome to the Quantum Number Guessing Game!");
Console.WriteLine("Guess a number between 1 and 100:");
int previousGuess = 0;
bool isFirstGuess = true;
while (true)
{
int guess = Convert.ToInt32(Console.ReadLine());
if (guess == desiredNumber)
{
Console.WriteLine("Spot on! You've found the correct number.");
break;
}
if (isFirstGuess)
{
Console.WriteLine("Getting warm.");
previousGuess = guess;
isFirstGuess = false;
}
else
{
if (Math.Abs(guess - desiredNumber) < Math.Abs(previousGuess - desiredNumber))
{
Console.WriteLine("Warmer, you're getting closer to the target.");
}
else if (Math.Abs(guess - desiredNumber) > Math.Abs(previousGuess - desiredNumber))
{
Console.WriteLine("Colder, you're moving further from the target.");
}
else
{
Console.WriteLine("Same distance, try a different direction.");
}
previousGuess = guess;
}
// Simulated annealing algorithm part (quantum physics-like overkill)
// Adjust the temperature and random factor for next guess.
temperature -= coolingRate;
if (temperature <= 0)
{
// Reset the game with a new number and temperature when cooling is complete.
desiredNumber = random.Next(1, 101);
Console.WriteLine("The quantum fields have fluctuated! A new number has been chosen.");
temperature = 100;
}
}
Console.WriteLine("Thank you for playing the Quantum Number Guessing Game!");
}
}
I’m thinking.. how about over-engineered it? I asked ChatGPT to try to make this block of code over-engineered; make it so complicated that it is hard to read and understand by humans:
and here is the over-engineered version:
using System;
using System.Reflection;
namespace QuantumNumberGuessingGame
{
class Program
{
static void Main(string[] args)
{
var game = new EnigmaticEngine<int>();
game.OnCorrectGuess += (sender, e) => Console.WriteLine("Quantum entanglement resolved. Precise match!");
game.StartGame();
}
}
public class EnigmaticEngine<T> where T : IComparable, IComparable<T>
{
private T SecretNumber;
private T PreviousGuess;
private bool IsFirstAttempt = true;
public event EventHandler OnCorrectGuess;
public EnigmaticEngine()
{
var type = typeof(T);
var boundedValue = type.GetField("MaxValue");
SecretNumber = (T)boundedValue.GetValue(null);
PreviousGuess = (T)Convert.ChangeType(0, typeof(T));
}
private void AdjustPreviousGuess(T guess)
{
PreviousGuess = guess;
}
public void StartGame()
{
Console.WriteLine("Commence the Quantum Number Prediction Ritual!");
while (true)
{
T guess = (T)Convert.ChangeType(Console.ReadLine(), typeof(T));
var compareResult = InvokeQuantumStateComparer(guess);
if (compareResult == 0)
{
OnCorrectGuess?.Invoke(this, EventArgs.Empty);
break;
}
InvokeQuantumWaveFluctuation(guess, compareResult);
AdjustPreviousGuess(guess);
IsFirstAttempt = false;
}
}
private int InvokeQuantumStateComparer(T guess)
{
return ((IComparable)guess).CompareTo(SecretNumber);
}
private void InvokeQuantumWaveFluctuation(T guess, int comparison)
{
var method = this.GetFluctuationMethod(comparison);
method.Invoke(this, new object[] { guess });
}
private MethodInfo GetFluctuationMethod(int comparison)
{
var methodName = comparison > 0 ? "InformColder" : "InformWarmer";
return this.GetType().GetMethod(methodName, BindingFlags.NonPublic | BindingFlags.Instance);
}
private void InformWarmer(T guess)
{
if (IsFirstAttempt || ((IComparable)guess).CompareTo(PreviousGuess) < 0)
{
Console.WriteLine("The cosmic winds favor you. Warmer!");
}
else
{
Console.WriteLine("A quantum disturbance... You are not closer.");
}
}
private void InformColder(T guess)
{
if (IsFirstAttempt || ((IComparable)guess).CompareTo(PreviousGuess) > 0)
{
Console.WriteLine("A shift in the quantum field. Colder!");
}
else
{
Console.WriteLine("The stars are silent... No change in proximity.");
}
}
}
public static class EnigmaticExtensions
{
public static MethodInfo GetMethod<T>(this T obj, string methodName, BindingFlags flags)
{
return obj.GetType().GetMethod(methodName, flags);
}
}
}
Okay, that’s cool. Let’s try to “upgrade” the level of “over-engineering.”
Next, I asked ChatGPT to create another even more “over-engineered” version.
At first, it expanded the code based on the second version, but it did not adhere to the original requirements of guessing a number between 1 and 100.
I reminded ChatGPT of the requirements and directed it to regenerate code that aligns with them.
In the subsequent version, the code had a few bugs that required manual debugging. I added some minor improvements and a text encryption function.
After the bugs were fixed and after a few iterations of improvements with ChatGPT-4, here’s the third version of the extended “over-engineered” code, based on the second “over-engineered” version:
using System;
using System.Linq.Expressions;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Dynamic;
using System.Security;
using System.Text;
using System.Security.Cryptography;
using System.Linq;
namespace QuantumNumberGuessingGame
{
class Program
{
static void Main(string[] args)
{
dynamic game = new EnigmaticEngine<int>().CreateDynamicEngine();
game.OnCorrectGuess += new EventHandler((sender, e) =>
Console.WriteLine(MissionImpossibleSecretInstructions.SuccessMessage));
game.StartGame();
}
}
public class EnigmaticEngine<T> where T : struct, IComparable<T>
{
private T SecretNumber;
private dynamic PreviousGuess;
private int PreviousDistance = int.MaxValue;
private bool IsFirstAttempt = true;
private ConditionalWeakTable<object, Delegate> EventTable = new ConditionalWeakTable<object, Delegate>();
private RandomNumberGenerator rng = RandomNumberGenerator.Create();
public dynamic OnCorrectGuess
{
get => EventTable.GetValue(this, key => null);
set
{
if (EventTable.TryGetValue(this, out var existing))
{
EventTable.Remove(this);
}
EventTable.Add(this, value);
}
}
public EnigmaticEngine()
{
SecretNumber = GenerateSecretNumber();
PreviousGuess = default(T);
}
private T GenerateSecretNumber()
{
if (typeof(T) == typeof(int))
{
byte[] randomNumber = new byte[4];
rng.GetBytes(randomNumber);
int value = BitConverter.ToInt32(randomNumber, 0);
return (T)(object)(Math.Abs(value % 100) + 1);
}
else
{
throw new InvalidOperationException(MissionImpossibleSecretInstructions.UnsupportedTypeMessage);
}
}
public DynamicObject CreateDynamicEngine()
{
return new EnigmaticDynamicEngine(this);
}
public void StartGame()
{
Console.WriteLine(MissionImpossibleSecretInstructions.InstructionMessage);
while (true)
{
Console.Write(MissionImpossibleSecretInstructions.ProvideGuessMessage);
T guess;
try
{
guess = (T)Convert.ChangeType(Console.ReadLine(), typeof(T));
}
catch
{
Console.WriteLine(MissionImpossibleSecretInstructions.InvalidInputMessage);
continue;
}
var compareResult = InvokeQuantumStateComparer(guess);
if (compareResult == 0)
{
EventTable.GetOrCreateValue(this).DynamicInvoke(this, EventArgs.Empty);
Console.WriteLine(MissionImpossibleSecretInstructions.CorrectGuessMessage);
Console.ReadKey();
break;
}
if (IsFirstAttempt)
{
Console.WriteLine(MissionImpossibleSecretInstructions.IncorrectTryAgainMessage);
}
else
{
InvokeQuantumWaveFluctuation(guess, compareResult);
}
IsFirstAttempt = false;
}
}
private int InvokeQuantumStateComparer(T guess)
{
var comparer = ComparerExpression(SecretNumber).Compile();
return comparer(guess);
}
private Expression<Func<T, int>> ComparerExpression(T value)
{
ParameterExpression valueParam = Expression.Parameter(typeof(T), "value");
Expression body = Expression.Call(Expression.Constant(value), typeof(T).GetMethod("CompareTo", new Type[] { typeof(T) }), valueParam);
return Expression.Lambda<Func<T, int>>(body, valueParam);
}
private Expression<Func<T, int>> DistanceExpression(T value)
{
ParameterExpression valueParam = Expression.Parameter(typeof(T), "value");
BinaryExpression subtractExpr = Expression.Subtract(valueParam, Expression.Constant(value, typeof(T)));
UnaryExpression convertToIntExpr = Expression.Convert(subtractExpr, typeof(int));
MethodCallExpression absExpr = Expression.Call(null, typeof(Math).GetMethod(nameof(Math.Abs), new[] { typeof(int) }), convertToIntExpr);
return Expression.Lambda<Func<T, int>>(absExpr, valueParam);
}
private void InvokeQuantumWaveFluctuation(T guess, int comparison)
{
int currentDistance = DistanceExpression(SecretNumber).Compile().Invoke(guess);
bool warmer = currentDistance < PreviousDistance;
if (warmer)
{
InformWarmer();
}
else
{
InformColder();
}
PreviousDistance = currentDistance;
}
[AdvancedCalculation]
private void InformWarmer()
{
Console.WriteLine(MissionImpossibleSecretInstructions.WarmMessage);
}
[AdvancedCalculation]
private void InformColder()
{
Console.WriteLine(MissionImpossibleSecretInstructions.ColdMessage);
}
}
public class EnigmaticDynamicEngine : DynamicObject
{
private object Instance;
private Type InstanceType;
public EnigmaticDynamicEngine(object instance)
{
this.Instance = instance;
this.InstanceType = instance.GetType();
}
public override bool TryInvokeMember(InvokeMemberBinder binder, object[] args, out object result)
{
var method = InstanceType.GetMethod(binder.Name, BindingFlags.Public | BindingFlags.Instance);
if (method != null)
{
result = method.Invoke(Instance, args);
return true;
}
return base.TryInvokeMember(binder, args, out result);
}
public override bool TrySetMember(SetMemberBinder binder, object value)
{
var prop = InstanceType.GetProperty(binder.Name, BindingFlags.Public | BindingFlags.Instance);
if (prop != null)
{
prop.SetValue(Instance, value);
return true;
}
return base.TrySetMember(binder, value);
}
public override bool TryGetMember(GetMemberBinder binder, out object result)
{
var prop = InstanceType.GetProperty(binder.Name, BindingFlags.Public | BindingFlags.Instance);
if (prop != null)
{
result = prop.GetValue(Instance);
return true;
}
return base.TryGetMember(binder, out result);
}
}
[AttributeUsage(AttributeTargets.Method)]
public class AdvancedCalculationAttribute : Attribute
{
}
public static class MissionImpossibleSecretInstructions
{
private static readonly byte[] SecretArray;
private static readonly int[] MessageIndices;
static MissionImpossibleSecretInstructions()
{
string allMessages = EncodeAllMessages();
SecretArray = Encoding.UTF8.GetBytes(allMessages).Select(b => (byte)(b ^ 0xAA)).ToArray();
MessageIndices = CalculateIndices(allMessages);
}
public static string UnsupportedTypeMessage => DecodeMessageAtIndex(0);
public static string ProvideGuessMessage => DecodeMessageAtIndex(1);
public static string InvalidInputMessage => DecodeMessageAtIndex(2);
public static string CorrectGuessMessage => DecodeMessageAtIndex(3);
public static string IncorrectTryAgainMessage => DecodeMessageAtIndex(4);
public static string WarmMessage => DecodeMessageAtIndex(5);
public static string ColdMessage => DecodeMessageAtIndex(6);
public static string InstructionMessage => DecodeMessageAtIndex(7);
public static string SuccessMessage => DecodeMessageAtIndex(8);
private static string DecodeMessageAtIndex(int index)
{
int start = MessageIndices[index];
int end = (index < MessageIndices.Length - 1) ? MessageIndices[index + 1] - 1 : SecretArray.Length;
var messageBytes = SecretArray.Skip(start).Take(end - start).ToArray();
return Encoding.UTF8.GetString(messageBytes.Select(b => (byte)(b ^ 0xAA)).ToArray());
}
private static string EncodeAllMessages()
{
string separator = "|";
string[] messages = {
"Unsupported type for secret number generation.",
"Provide your guess: ",
"Invalid input, try again",
"Congratulations! You've guessed the correct number.",
"Incorrect. Try again!",
"The cosmic winds favor you. Warmer!",
"A shift in the quantum field. Colder!",
"Initiating quantum leap... Brace for entanglement!\r\nCalibrate your intuition to the quantum frequency (1-100)\r\nEnter the quantum number you resonate with:\r\n",
"Quantum entanglement resolved. Precise match!"
};
return string.Join(separator, messages);
}
private static int[] CalculateIndices(string allMessages)
{
string[] messages = allMessages.Split(new[] { "|" }, StringSplitOptions.None);
int[] indices = new int[messages.Length];
int currentIndex = 0;
for (int i = 0; i < messages.Length; i++)
{
indices[i] = currentIndex;
currentIndex += Encoding.UTF8.GetBytes(messages[i]).Length + 1;
}
return indices;
}
}
}