Skip to content

Commit 7dc2345

Browse files
committed
Added #19 Game 2048 in C#.
1 parent 4b7b509 commit 7dc2345

File tree

1 file changed

+75
-0
lines changed

1 file changed

+75
-0
lines changed

019-csharp/Class1.cs

Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
1+
using System;
2+
using System.Collections.Generic;
3+
using System.Linq;
4+
using System.Text;
5+
using System.Threading.Tasks;
6+
using NUnit.Framework;
7+
8+
namespace CodingDojo2048
9+
{
10+
[TestFixture]
11+
public class Class1
12+
{
13+
// 4x4 grid
14+
// initialy 2 cells with value 2 or 4
15+
// after each round add one cell with value 2 or 4
16+
// moves:
17+
// row to left
18+
// row to right
19+
// column to up
20+
// column to down
21+
// bunky se pricapi
22+
// - two cells with same value merge and sums with direction from wall
23+
24+
[Theory]
25+
[TestCase(new[] { 0, 0, 0, 0 }, new[] { 0, 0, 0, 0 })]
26+
[TestCase(new[] { 0, 0, 0, 2 }, new[] { 0, 0, 0, 2 })]
27+
[TestCase(new[] { 0, 2, 0, 0 }, new[] { 0, 0, 0, 2 })]
28+
[TestCase(new[] { 2, 0, 0, 0 }, new[] { 0, 0, 0, 2 })]
29+
[TestCase(new[] { 2, 0, 2, 0 }, new[] { 0, 0, 0, 4 })]
30+
[TestCase(new[] { 2, 0, 2, 2 }, new[] { 0, 0, 2, 4 })]
31+
[TestCase(new[] { 2, 2, 2, 2 }, new[] { 0, 0, 4, 4 })]
32+
[TestCase(new[] { 4, 4, 2, 2 }, new[] { 0, 0, 8, 4 })]
33+
public void WhenEvaluateVectorToVector(int[] input, int[] expected)
34+
{
35+
var result = Evaluate(input);
36+
Assert.That(result, Is.EqualTo(expected));
37+
}
38+
39+
private int[] Evaluate(int[] values)
40+
{
41+
var nonZeroValues = values.Where(value => value != 0).ToList();
42+
var merged = Merge(nonZeroValues);
43+
return CompleteWithZeros(merged).ToArray();
44+
}
45+
46+
private IEnumerable<int> Merge(List<int> nonZeroValues)
47+
{
48+
var merged = new List<int>();
49+
50+
for (int i = nonZeroValues.Count() - 1; i >= 0; i--)
51+
{
52+
var current = nonZeroValues[i];
53+
var previous = (i == 0) ? 0 : nonZeroValues[i - 1];
54+
if (current == previous)
55+
{
56+
merged.Add(current + previous);
57+
i--;
58+
}
59+
else
60+
{
61+
merged.Add(current);
62+
}
63+
}
64+
65+
merged.Reverse();
66+
return merged;
67+
}
68+
69+
private static IEnumerable<int> CompleteWithZeros(IEnumerable<int> merged)
70+
{
71+
return Enumerable.Repeat(0, 4 - merged.Count()).Concat(merged);
72+
}
73+
74+
}
75+
}

0 commit comments

Comments
 (0)