## Introduction

### What is Code Hunt?

On May 15th, as seen on Reddit the Microsoft Research Team announced Code Hunt, an online "game" that claims to help you learn to code.  Not too sure about that, but it is certainly an interesting way to pass the time and may even teach you a few things along the way.  Inevitably, though you get stuck and need hints.

### This post

The purpose of this post is not to give you all the answers to Code Hunt.  If you're looking for that, you're in the wrong place!  What it will do is explain how to find all the answers and why your answers are not optimal.  With the information given here, you should be able to receive full marks and learn something along the way.  We only use C# here, but the information can equally be applied to Java.

### Resources

You may find use for:

## Walkthrough

### General approach

The problems do not come with any specification of what the tested method should achieve, so the first thing is to reverse engineer the specification from the input->output expectations presented by the system.  One approach to achieving this is to use concatenated ternary operators using the tested input parameters as follows:

Once you have reverse engineered the method's intended purpose, you should apply documentation comments with triple-slashes.  Always document your code!

Finally, implement the function as efficiently as you can:

If Microsoft agree that your code is both correct and succinct, you get maximum points!

### 00 Training

#### 00.02 Inky fingers

Look at the input value.  Look at the output value.  Not much difference is there?

#### 00.03 Doubly tricky

Output is a multiple of input.

#### 00.04 Nonplussed?

Output combines inputs.

### 01 Arithmetic

#### 01.01 Are you positive?

Output is a simple function of input.

#### 01.02 A bit more different

Add a constant to the input value.

#### 01.03 Don't be so square

A higher order function.

#### 01.04 Magic numbers

A lower order function

Magic!

Sounds like...

Why fewer?

#### 01.08 Why try more?

...than x.  First order.

Go forth...

#### 01.10 Tricky

The first one, the second third.

#### 01.11 Get this one over with

The other goes down under.

#### 01.12 A modern approach

Read up on the modulo operator (the percent sign).

#### 01.13 Even more modern

Similar to the previous puzzle.  But more. so.

#### 01.14 WHAT?!

I must confess, originally I only managed to get the following:
It then took a LOT of staring to realise that this was some sort of modulo, but I didn't get it.  Thanks and kudos go to MegjelenőNév for pointing out that this one requires x both before AND after the modulo.  Spoiler: answer in comments below.

#### 01.14 Of Average difficulty

You know what I mean.

### 02 Loops

Now the loops can all be achieved using regular loops, but in this modern age of LINQ, who uses loops?  I have provided all my Linq-based answers.  Please work out WHY these are correct (though not necessarily the highest-scoring) answers...

#### 02.01 Simple Range

Read up on The LINQ Range method.  It may not do what you think!

#### 02.03 More Squares

This one is a little weird and requires a pair of casts...

### 03 Loops 2

#### 03.01 Ternary operator

For this one, I AM going to directly give you the right answer, and it's a single line.  Read up on the C# ternary operator to find out how this works...

return power==0?1:power==1?number:number*Puzzle(number, power-1);

Here's how to read the above...

Return the following value:
• If power is 0 then 1 otherwise
• If the power is 1 then number otherwise
• The number multiplied by a recursive call to this function against the number but for one lower power.

#### 03.02 LINQ Aggregate

For this one, again, I am going to give you the answer.  Read up on the LINQ Aggregate function, which recursively multiplies.  You should then be able to see why this is an acceptable solution:

return Enumerable.Range(1,i).Aggregate(1, (x,y) => x * y);

#### 03.03 More Range, More Aggregate

Now that you have the answer to 03.02, you should be able to solve 03.03.  Of course, you read up on exactly how LINQ Range works didn't you?  No?  Shame!  Go read up on EXACTLY what each term does.

Now, can you explain why this works?:

return Enumerable.Range(lowerBound,upperBound-lowerBound).Aggregate(upperBound, (soFar,newValue) => soFar * newValue);

#### 03.04 Wot no LINQ?

No LINQ needed for this one really...  Half one fewer by half one more.

#### 03.05 Non-optimal LINQ

Enumerable.Range(1, upperBound).Sum(a=>a%2==upperBound%2?a*a:0);
Now make it optimal.

#### 03.06 LINQ Repeat

Here's part of the answer.  Now if only there were a way of JOINing STRINGs...
Enumerable.Repeat('_', word.Length)

#### 03.08 I am not a number!

I'm a free string!

#### 04.09 (i%NUM!=0?STRING1:STRING2) + STRING3

One is empty - which one?

### 06 Strings

#### 06.01 I did not write elegant code.

But then I didn't need to!?

#### 06.11 WHAT?! again

See Andrew Furdell's hint below.

### 07 Strings 2

Use IndexOf

#### 07.09 Enumerable Repeat string Join

Do it all in one line

#### 07.10 Hmm

I have the following:
var alphabet = "a b c d e f g h i j k l m n o p q r s t u v w x y z";
return string.Join(" ",Enumerable.Range(0,t).Select(n=>n!=t-1?alphabet:alphabet.Substring(0,50-n*2) + "z").ToArray());

Now how to improve?

### 08 Nested Loops

OK, so everyone can write nested for loops.   But we're better than that now aren't we? ;-)  Unfortunately, these efforts are not appreciated by Microsoft so most of these are considered non-optimal answers.  IF that is the case, there is something wrong either with their compiler optimisations, or with their code evaluation algorithm.

#### 08.01 Factorial sums

Now Microsoft have just got this one plain wrong.  The following code is a quite reasonable attempt to sum the factorials between i and j:

return Enumerable.Range(i, j-i+1).Sum(x=>Enumerable.Range(1,x).Aggregate((a, b) => b * a));

However, this get rejected for two really weird cases:
For input values of i=12, j=13, Microsoft give the answer -1883912192.  Clearly wrong.  12! + 13! is 6706022400.
For input values of i=3, j=64, Microsoft gives the answer null.  Null?!  Null is not even a legitimate return value.  Don't bother with this one, it can't be done.

UPDATE: Kudos to MW, who (SPOILER) has given a full 3-star answer in the comments, below.

#### 08.02 Hashes

This one is easy to do with nested loops or new string('#', x), but can you do it with LINQ?
Here's the kind of code you should be writing by now...:

return string.Join("", Enumerable.Range(1,n).Select(a=>new string('#', a) + " "))

#### 08.03 Alpha underscores

Easy to see what they are wanting here, and easy to lazily implement in for loops.
Microsoft didn't give full marks to the following, so I don't feel bad about sharing the following:

return string.Join("", Enumerable.Range(0,n+1).Select(a=>string.Join("",Enumerable.Range(0,n+1).Select(x=>x>a?"_":x.ToString())) + " "));

#### 08.04 Dash on N

More LINQ awesomeness:

return string.Join(" ",Enumerable.Range(1,n).Select(a=>string.Join("", Enumerable.Range(1,n).Select(y=>y!=a?b:"-"))));

#### 08.05 Underscore at N

Blah blah LINQ blah:

return string.Join(" ",Enumerable.Range(0,a.Length).Select(b=>string.Join("", Enumerable.Range(0,a.Length).Select(y=>y!=b?a.Substring(y,1):"_"))));

#### 08.06 Have LINQ hammer.  Everything is a nail.

return string.Join(" ",Enumerable.Range(1,size).Select(b=>string.Join("", Enumerable.Range(1,size).Select(y=>b!=1&&b!=size&&y!=1&&y!=size?"_":"\$"))));

#### 08.07 LINQ -> Noughts and Crosses

return string.Join(" ",Enumerable.Range(0,height).Select(heightPos=>string.Join("", Enumerable.Range(0,width).Select(widthPos=>(widthPos+heightPos)%2==0?"x":"o"))));

#### 08.08 OK, I admit, not pretty, but I'm committed to it now...

I will tidy this one up later with Math.Abs()...

return
string.Join(" ",Enumerable.Range(1,number).Select(index=>string.Join("", Enumerable.Range(0,index).Select(a=>index.ToString()))))
+ " " +
string.Join(" ",Enumerable.Range(1,number-1).Select(index=>string.Join("", Enumerable.Range(0,number - index).Select(a=>(number-index).ToString()))));

### 09 1D Arrays

#### 09.12 Buggy test?

return Enumerable.Range(numbers.Length-amount, numbers.Length).Select(a=>numbers[a%numbers.Length]).ToArray();
This results in...
I have NO idea.

UPDATE: Kudos to MW, who (SPOILER) has given a full 3-star answer in the comments, below.

### 11 Arrays 2

#### 11.03 This one makes me cross..

Can someone explain to me why this does not work?!
return
Enumerable.Range(0, input.Length).Sum(arrayIndex=>(long)input[arrayIndex][arrayIndex])
==
Enumerable.Range(0, input.Length).Sum(arrayIndex=>(long)input[arrayIndex][input.Length-1-arrayIndex])
;

### 12 Search Sort

#### 12.03 Cleverness gives 1*

Use FirstOrDefault()
list.Select((item, index) => new { Item = item, Index = index })

### 14 Puzzles

#### 14.04 Coming soon...

1. I'm stuck on a couple in Sector 12 as well as 06.11. You didn't quite give hints to that point. Have you finished the entire game?

1. More hints to follow shortly. I'm on holiday this week, but plan to finish them all soon :-)

2. I'm down to 4 left to solve, but for the life of me can't find the optimal solution to 07.04 that they are looking for. Let me know if you need hints on any of them.

3. 07.04 was one of the easiest ones to solve! It even shocked me that you had to use something already used before to solve another puzzle.
All you have to do is reverse...

4. Andrew -- You are right that it was super easy to solve, I just can't find a solution that gives more than two stars. Do you have a solution that gives you all three stars? I've tried everything from multiple versions of Linq, StringBuilder, recursion, xor, and brute force loop with string/character array.

5. For 07.04 3 stars the solution is ToCharArray(), Array.Reverse() and then new string() ;)

6. I tried that first and it only gets me 2 stars...

char[] charArray = s.ToCharArray();
Array.Reverse(charArray);
return new string(charArray);

7. Very strange! The only change is var instead of char[] :-s

var c = s.ToCharArray();
Array.Reverse(c);
return new string(c);

8. Sorry I never replied... This gives 3 stars for that level:
return new string(s.Reverse().ToArray());

2. Do yo know the answer of 1.15 question? It is quite difficult. Thanks.

1. I would say that 1.15 was of **average** difficulty ;-)

2. Flash - For 01.15, try adding the numbers and doing a math operation with the result.

3. 1.14 is only one line :
return (10+x)%x;

1. This can be made more efficient. Look carefully at what you have done!

2. return 10%x;

4. How interesting the hint about 5.03. You talk about triangles, but when we sum all three angles of a triangle, it always has to be 180º. Maybe you're refering to another triangle's characteristics? (sorry for my english)

1. Yes, yes I am talking about other characteristics.

2. 3 star solution for Java (and I suppose C#):

int max = Math.max(Math.max(a, b), c);
return a * a + b * b + c * c == 2 * max * max;

5. I'm stuck at 06.11 and I have no idea how to solve it, could someone shed some light into this one?

Thanks!

1. Here's a good way to solve that one...
Write a bunch of conditional return statements that look like this:

if (i == x && j == y && s.length() == z) return ???

...where x, y, and z are combinations of values you see in the tests, and ??? works for all similar cases. Don't worry if the first few don't look similar...after you do seven or eight of them (and s.length() starts to grow) you should start to see a pattern emerge in the newer cases. Once you see that, try to refactor your earlier return statements to resemble your later ones. Finally, now that you have a pattern that fits all the test cases, you should be able to refactor into a one-liner.

2. I still can't find the logic :(

3. Concatenate 2 substrings of s, first part based on some magic with i, the second with j.

This is as close as I can hint without given the solution :)

4. Oooh, thanks. Found it luckily! Very wierd logic...

5. I'm still stuck on the 6.11. Sometimes this game is not fun. Is not about learning or trying things, is just finding a lucky solution. Some more hints or maybe a full solution?

6. Ratt Vis's hint was enough for me. so here's 3 stars solution:
return s.Substring(i, s.Length - 1 - i) + s.Substring(j, s.Length - j - 1);
i'd hide it under [spoiler] tag or smth, but there's no such thing here =\

7. This comment has been removed by the author.

8. Sorry, but unless I'm doing something wrong, your solution is not working.
Even written properly:
return s.substring(i, s.length() - 1 - i) + s.substring(j, s.length() - j - 1);
So there are two posibilities: Microsoft updated the game and that solutions stopped working or you made a mistake copying your code.

9. that was solution for c# ;)

10. Sorry exhostosis, my mistake. I'm doing the game in Java. I don't know why, but that solution, even "translated" to Java language is not working (what is Microsoft doing?).

Well, thank you for your time anyway. Now, I have to wait for some Java solution :(

11. 6.11 has no logic in it. i've failed to find pattern after seeing near 20 variations. my 3 star answer : return s[i] + s.Substring(j, s.Length - j - 1); which does not cover even 50% of seen variations

12. 06.11 is solved with max score with this:
return s.Substring(i, s.Length - 1 - i) + s.Substring(j, s.Length - 1 - j);

13. int min = Math.min(i, j);
int max = Math.max(i, j);
return s.substring(min, max + 1) + s.charAt(max);

6. Have 3blook solution for 6.2:
using System;
public class Program {
public static string Puzzle(string s) {
char[]a=s.ToCharArray();
for (int i=0;i<s.Length;i++)
if (i%2==0)
a[i]=(char)((int)a[i]-32);
return s=String.Join("",a);
}
}

1. You can just do a ToUpper instead of casting to int and then just do a new String on the return.

char [] ca = s.ToCharArray();
for (int i=0; i<ca.Length; i+=2)
ca[i] = Char.ToUpper(ca[i]);
return new String(ca);

7. Flash for 09.12 (only one star):
move number from field with index "i" to field with index increased by "amount". For target index out of bounds continue from beginning. {1,2,3,4} with amount 1 => {4,1,2,3}, with amount 2 => {3,4,1,2}

Any idea with solution in 10.08, 11.03 and 11.06? I can´t find logic between input values and solution.

1. I don't have a solution for 10.08 or 11.03 either, but for 11.06 it gives you a list of grades and then the lower bound for each of the grade letters (A, B, C, D). You just need to return an array of grade letters instead of grade numbers.

2. Thanx, it shed light on it:-)

3. David has a hint for 10.08 above that allowed me to solve.

4. For 11.03, look at the input as a NxN Matrix, then have a look at the elements on both diagonals.

For 10.8, again look at the input as a Matrix and then have a look at the columns.

8. Starting out learning C# here. Managed to make it through Levels 00 and 01, but having an issue with 02.01. My problem is that I can't get any return at all, there is always some error. I've tried various forms of:
for (n=0; n<=10; n++);
but I usually get told that I cannot implicitly convert type 'int' to 'int[]'
After finding this blog, I tried using:
Enumerable.range(0,n).ToArray();
as shown in the picture, but was told The name 'Enumerable' does not exist in the current context. Again, if I was getting SOME kind of output and I just needed to adjust the formatting or logic, I could probably figure it out, but I just keep getting errors. Any pointers?

1. Hi Richard :-)

You will need to include the following at the top of the snippet:

using System.Linq;

Let me know if that worked!

David

2. Amazing, thank you!

9. 8.01 can be done, it's just that MS is relying on the fact that int will overflow and the Linq solution doesn't allow that. Here's an example of how it will pass with 3 stars...

public class Program {
public static int Factorial(int x) {
if (x == 1)
return 1;
return x*Factorial(x-1);
}
public static int Puzzle(int i, int j) {
int sum = 0;
for (int s=i; s<=j; s++)
sum += Factorial(s);
return sum;
}
}

1. You'd think a recursive solution wouldn't get a perfect score in the Nested Loops section..

10. 9.12 solution for 3 stars...

using System;
using System.Collections.Generic;

public class Program {
public static int[] Puzzle(int[] numbers, int amount) {
int len = numbers.Length;
var numList = new List(numbers);
var remList = numList.GetRange(0,len-amount);
numList.RemoveRange(0,len-amount);
return numList.ToArray();
}
}

1. I have this solution too :

var arr = new int[numbers.Length];
var len = numbers.Length - amount;
Array.Copy(numbers, 0, arr, amount, len);
Array.Copy(numbers, len, arr, 0, amount);
return arr;

11. For 06.09 an idea to have 3 stars?
Actually I have one return with two ?: conditions...

1. Same here, best I could get was 2 stars.

2. I've tried refactoring a single-line answer and the best I can come up with (for 2 stars) is:
return (a.Length >= b.Length ? a : string.Empty) + (b.Length >= a.Length ? b : string.Empty);

3. And no extra stars for reducing the redundancy:

using System;
public class Program {
public static string Puzzle(string a, string b) {
return Fn(a,b) + Fn(b,a);
}

private static string Fn(string a, string b) {
return (a.Length >= b.Length ? a : string.Empty);
}
}

4. I've tried about everything in 6.9, always getting just 2 bars, the latest I tried was:

return new[]{a,a+b,b}[b.Length.CompareTo(a.Length)+1];

5. 3 stars :

if(a.length()>b.length())
return a;
if(b.length()>a.length())
return b;
return a+b;

can u give me a hint for 7.08 pls ????

6. and 12.08

7. Hypatia -- The code you provided doesn't work in C#, I only get 2 stars when modifying and using .Length.

7.08 -- See my hint below, try using StartsWith, IndexOf and EndsWith.

8. oh ok , i'm using Java

9. 3 stars in 6.09:
return (a.Length == b.Length) ? a + b : (a.Length > b.Length) ? a : b;

so, anyone guessed the algorithm in 12.08?

10. 12.08 and 14.03 pls :)

11. Hmm, exhostosis solution still only gets me 2 stars...

14.03 - Divides evenly and is prime

12. This comment has been removed by the author.

13. 12.08 :
You have to return the (Index) when (the sum of previous numbers x2) =
(the sum of all numbers).
Think with Long and Modulo for great negative numbers...

14. 12.08:
Pay attention Sum() with an Array of integers doesn't work properly when there some great negative numbers in the array that are, finally, not integers at all...

15. oh thanks. that wasn't quite obvious )

12. David for 07.10 I have this code :

var abc = "a b c d e f g h i j k l m n o p q r s t u v w x y z";
var res = string.Join(" ", Enumerable.Repeat(abc, t));
return res.Substring(0, res.Length - t * 2) + " z";

13. I have problem with solution for 14.08. First solution with compared sorted char arrays leads only to 2 stars.

I have tried:
using System;
using System.Linq;
public class Program {
public static bool Puzzle(string a, string b) {
return new string((a.ToCharArray()).OrderBy(c=>c).ToArray())==new string((b.ToCharArray()).OrderBy(d=>d).ToArray());
}
}

It is only 1 line and in standard C# project everything seems to be OK. But in "Code Hunt" it leads to error:
"Bad dependency", "Invalid referenced types" "System.Linq.IOrderedEnumerable`1"

Any idea what's wrong? Thanx

1. The Code Hunt puzzles don't seem to let you use Linq OrderBy. Here's a solution that will get 3 stars:

public static bool Puzzle(string a, string b) {
char[] charArray = b.ToCharArray();
Array.Reverse(charArray);
return string.Compare(a, new string(charArray)) == 0;
}

2. Or if you really want a single line solution you could use the following:

return a.SequenceEqual(b.Reverse());

14. Três estrelas no 08.03

string output = "";
for (int s = 0; s <= n; s++)
{
var numeros = Enumerable.Range(0, s+1).ToArray();
output += string.Join("", numeros) + new string('_', n - s) + " "; ;
}
return output;

15. Três estrelas no 09.06:

return Enumerable.Repeat(true, 10).ToArray();

16. Três estrelas no 09.08
return Enumerable.Range(0, i + 1).Reverse().ToArray();

17. Três estrelas no 09.11
return new string(s.ToCharArray().Reverse().ToArray());

18. Anyone got a 3 star tip for 14.04?
This is what I have but only gets me 2 stars:

return Regex.Replace(s, ".{2}", match => ""+(char)(match.Value.Average(x=>(int)x)));

3 star hints for 6.9 and 14.9 are also appreciated, got 2 on both and I assume the 3 star solution is very similar on both (branch-wise)

1. 14.04
I got 3 stars with a wrong answer.
(Once you got 3 stars, you won't get 1~2 anymore. Cant try other code...)

14.09
Code hunt only test 1 data(not parallel/same)...

2. 06.09
return a.Length > b.Length? a : (a.Length == b.Length ? (a+b) : b);

19. for 9.13 ---> swap

could u help me with 7.08 ? still can't get it !!

1. For 7.08, try using StartsWith, IndexOf and EndsWith. If you still need more help, let me know.

2. thank you :)

20. Três estrelas no 09.13

public static int[] Puzzle(int[] numbers, int i, int j) {
var valorI = numbers[i];
numbers[i] = numbers[j];
numbers[j] = valorI;
return numbers;
}

21. Finalmente 3 estrelas no 09.14:
public static int[] Puzzle(int[] a, int[] b)
{
if (a.Length > b.Length)
{
Array.Resize(ref b, a.Length);
}
else if (a.Length < b.Length)
{
Array.Resize(ref a, b.Length);
}
return a.Zip(b, (x, y) => x + y).ToArray();
}

22. 3 estrelas no 10.03
public static int[][] Puzzle(int length, int x)
{
int[] numbers = Enumerable.Repeat(x, length).ToArray();
return Enumerable.Repeat(numbers, length).ToArray();
}

23. kkkkk...
3 Estrelas no 10.04
public static int[][] Puzzle(int[][] input) {
return input.Select(x => x.Select(y => y * 2).ToArray()).ToArray();
}

Foi dificil heim?

24. Isso ai... 3 estrelas no 10.05;
public static int Puzzle(int[][] input, int i)
{
return input.Select(x => x.Count(y => y == i)).Sum();
}

25. 3 Estrelas no 10.06
public static int Puzzle(int[][] input, int i)
{
return input.Select(x => x.Max()).Max();
}

26. This comment has been removed by the author.

27. 3 estrelas no 02.05

using System;
using System.Linq;
public class Program {
public static int Puzzle(int n) {
return Enumerable.Range(0,n).Sum(a=>a*a);
}
}

28. This comment has been removed by the author.

29. 3 estrelas no 03.01

using System;
public class Program {
public static int Puzzle(int number, int power) {
return power==0?1:number*Puzzle(number, power-1);
}
}

30. 03.02: factorial: return i==0?1:i*Puzzle(i-1);

31. Anyone got a 3 star tip for 06.03 and 06.08 ?

1. 06.03
return Regex.Replace(s, @"([a-z]\s+)|([a-z]\$)", match => match.ToString().ToUpper());

06.08
return a.Length > b.Length ? a.Length : b.Length;

2. The answer for 6.03 only returns 2 stars for me..

32. 12.08
public static int Puzzle(int[] numbers) {
for (var i = 0; i < numbers.Length; i++)
{
if (numbers.Take(i + 1).Aggregate(0, (i1, i2) => i1 + i2) ==
numbers.Skip(i + 1).Take(numbers.Length).Aggregate(0, (i1, i2) => i1 + i2))
return i;
}
return -1;
}

You cannot use Sum() which captures OverflowException.

33. Hi CodeHunt doesn't work in Windows 10 Pro 20H2

34. CodeHunt has been taken down, so you can no longer play it.