文章目录
- 01.程序结构划分
- 02.去零
- 03.合并
- 04.上移
- 05.下移/左移/右移,只是取数据的方向不同
- 06.提高可读性
01.程序结构划分
02.去零
有序向量“唯一化”的思路。
/// <summary>
/// 去零
/// </summary>
/// <param name="row">对于一行或一列元素</param>
private static void Remove0(int[] row)
{
int pos = 0;
for (int i = 0; i < 4; ++i) if (row[i] != 0) row[pos++] = row[i];
for (; pos < 4; ++pos) row[pos] = 0;
}
03.合并
/// <summary>
/// 合并
/// </summary>
/// <param name="row">对于一行或一列元素,完成一次向左合并的操作</param>
private static void Merge(int[] row)
{
// 去零
Remove0(row);
// 相邻相同则合并
for (int i=0; i<4-1; ++i)
{
if (row[i] != 0 && row[i] == row[i+1])
{
row[i] *= 2;
row[i + 1] = 0;
}
}
// 去零
Remove0(row);
}
04.上移
/// <summary>
/// 上移
/// </summary>
/// <param name="map">原棋盘</param>
/// <returns></returns>
private static void Up(int[,] map)
{
int[] arr = new int[4] ;
for (int j=0; j<4; ++j)
{
for (int i=0; i<4; ++i) arr[i] = map[i, j];
Merge(arr);
for (int i = 0; i < 4; ++i) map[i, j] = arr[i];
}
}
05.下移/左移/右移,只是取数据的方向不同
比如,“下移” 取数据和还数据的方向与“上移”相反。
/// <summary>
/// 下移
/// </summary>
/// <param name="map">原棋盘</param>
/// <returns></returns>
private static int[,] Down(int[,] map)
{
int[] arr = new int[4];
for (int j = 0; j < 4; ++j)
{
for (int i = 0; i < 4; ++i) arr[3-i] = map[i, j];
Merge(arr);
for (int i = 0; i < 4; ++i) map[i, j] = arr[3-i];
}
return map;
}
/// <summary>
/// 左移
/// </summary>
/// <param name="map"></param>
/// <returns></returns>
private static int[,] Left(int[,] map)
{
int[] arr = new int[4];
for (int i = 0; i < 4; ++i)
{
for (int j = 0; j < 4; ++j) arr[j] = map[i, j];
Merge(arr);
for (int j = 0; j < 4; ++j) map[i, j] = arr[j];
}
return map;
}
/// <summary>
/// 右移
/// </summary>
/// <param name="map">原棋盘</param>
/// <returns></returns>
private static int[,] Right(int[,] map)
{
int[] arr = new int[4];
for (int i = 0; i < 4; ++i)
{
for (int j = 0; j < 4; ++j) arr[3-j] = map[i, j];
Merge(arr);
for (int j = 0; j < 4; ++j) map[i, j] = arr[3-j];
}
return map;
}
06.提高可读性
枚举
enum Direction { up, down, left, right }
/// <summary>
/// 进行一次移动操作
/// </summary>
/// <param name="map">原棋盘</param>
/// <param name="dir">移动的方向(枚举)</param>
private static void Move(int[,] map, Direction dir)
{
switch (dir)
{
case Direction.up:
Up(map); break;
case Direction.down:
Down(map); break;
case Direction.left:
Left(map); break;
case Direction.right:
Right(map); break;
}
}