Challenge
Write a function that takes 2 integer operands
left
andright
(both >= 0) and evaluates one of the following basic arithmic operations:
- addition
- multiplication
- exponentation
The challenge is you are prohibited from using any built-in operator, except for an incrementation (
++
or+1
). The entropy is all results that are in bounds of the maximum value of an integer.
Provided Classes
public enum Operation { Addition, Multiplication, Exponentation } public static class Expression { public static int Evaluate(int left, int right, Operation operation) { throw new NotImplementedException(); // .. this should be implemented } }
Unit Tests
[TestClass] public class Fixtures { [TestMethod] public void Fixture() { Assert.AreEqual(5, Expression.Evaluate(2, 3, Operation.Addition)); Assert.AreEqual(6, Expression.Evaluate(2, 3, Operation.Multiplication)); Assert.AreEqual(8, Expression.Evaluate(2, 3, Operation.Exponentation)); } }
My Solution
I have decided to use the hyperoperation (Wikipedia Link). The only arithmic operator used is in the first branch (if (n == 0)
->b + 1
).
$$ H_n(a,b) = a[n]b = \begin{cases} b + 1 & \text{if } n = 0 \\ a & \text{if } n = 1 \text{ and } b = 0 \\ 0 & \text{if } n = 2 \text{ and } b = 0 \\ 1 & \text{if } n \ge 3 \text{ and } b = 0 \\ H_{n-1}(a, H_n(a, b - 1)) & \text{otherwise} \end{cases}$$
And my implementation of Evaluate
:
public static class Expression { public static int Evaluate(int left, int right, Operation operation) { return Hyper(left, (int)operation + 1, right); } static int Hyper(int a, int n, int b) { // https://en.wikipedia.org/wiki/Hyperoperation // a = left operand (a >= 0) // n = hyper operator (n >= 0) // b = right operand (b >= 0) if (a < 0) throw new ArgumentOutOfRangeException(nameof(a)); if (b < 0) throw new ArgumentOutOfRangeException(nameof(b)); if (n < 0) throw new ArgumentOutOfRangeException(nameof(n)); if (n == 0) return b + 1; if (b == 0) return n == 1 ? a : n == 2 ? 0 : 1; return Hyper(a, n - 1, Hyper(a, n, b - 1)); } }
Questions
- Are there any overlooked flaws in my solution?
- Could this be optimized for performance?
- Are there perhaps better alternatives, and why would they be better?
- Any general review of my code, style, conventions are invited.