Write the implementation to pass this test

2

2

Given the following test, implement an addOne function in C# so it passes, without any modification to the test. TIP: Yes, it is possible.

[TestMethod]
public void TheChallenge()
{
    int a = 1;

    addOne(a);

    Assert.IsTrue(a == 2);
}

EDIT: clarified the Assert to avoid confusion. The value of a should be 2; there's no trick there.

istepaniuk

Posted 2013-01-10T21:13:59.433

Reputation: 139

do you mean void addOne(ref int a){a++;} – shiona – 2013-01-10T21:18:48.510

That wouldn't compile. The ref keyword is not in the test (you would need addOne(ref a);). – istepaniuk – 2013-01-10T21:22:27.137

Perhaps you could use reflection to somehow rewrite the IL for the test method to increment a after the return. That's all I can think of. – captncraig – 2013-01-10T22:11:40.050

4This isn't a very code golf friendly question. – MrZander – 2013-01-10T22:36:34.150

@istepaniuk oh, I've never actually written any C#, so I googled and tried to understand the syntax for pass by reference. MrZander: it isn't tagged code golf. It's awfully simple for puzzle though. – shiona – 2013-01-10T23:06:59.123

No need to rewrite IL on runtime. But it goes on those lines of nasty hack. TIP: unsafe code is allowed – istepaniuk – 2013-01-11T09:10:35.147

@MrZander, @shiona; please tag accordingly, I'm new here. – istepaniuk – 2013-01-11T11:35:04.097

Answers

14

Ummm, simply provide an implementation of AssertTrue that doesn't throw anything?

void addOne(int a){}

void AssertTrue(bool b) { }

You never specified what testing framework is used here. It looks like MSTest, but I fired up a new test project and AssertTrue doesn't exist, so I took the liberty of implementing it myself.

EDIT

This solution might be what you were fishing for:

void addOne(int x)
{
  unsafe
  {
    int* i = &x;
    i += 4;
    *i += 1;
  }
}

I feels pretty fragile, but it works on my box consistently. It probably depends heavily on the compiler, so hopefully it is reproducible elsewhere.

captncraig

Posted 2013-01-10T21:13:59.433

Reputation: 4 373

+1 for lateral thinking, but the question states "Implement an addOne function" I will clarify the Assert to make it pure mstest. – istepaniuk – 2013-01-11T09:08:35.010