[原创]Google™ Code Jam - 中国编程挑战赛2005 训练题解答
Google™ Code Jam - 中国编程挑战赛 训练题解答
做完了一下训练题(3道),用C# 写的,已通过竞赛场提交通过。
我把三道题放在一起了。
有兴趣的战友不妨多多交流,题目虽然不难,可还是要花一点时间的。
挑战赛首页:
http://www.topcoder.com/pl/?module=Static&d1=gccj05&d2=ZH_schedule
我的参考代码:
--------------------------------
using System;
public class DrawLines
{
public string[] execute(string[] commands)
{
char[][] pixels = new char[20][];
for (int i = 0; i < 20; i++)
{
pixels[i] = new char[20];
for (int j = 0; j < 20; j++)
pixels[i][j] = '.';
}
int currentX = 0, currentY = 0;
int direction = 0;
foreach (string commandText in commands)
{
string[] splitCommandText = commandText.Split(' ');
if (splitCommandText.Length == 1)
direction = (direction + 1) % 4;
else
{
int step = int.Parse(splitCommandText[1]);
int deltaX = 0, deltaY = 0;
switch (direction)
{
case 0:
deltaY = step;
for (int i = 0; i <= deltaY; i++)
pixels[currentY + i][currentX] = '*';
break;
case 1:
deltaX = step;
for (int i = 0; i <= deltaX; i++)
pixels[currentY][currentX + i] = '*';
break;
case 2:
deltaY = -step;
for (int i = 0; i <= -deltaY; i++)
pixels[currentY - i][currentX] = '*';
break;
case 3:
deltaX = -step;
for (int i = 0; i <= -deltaX; i++)
pixels[currentY][currentX - i] = '*';
break;
}
currentX += deltaX;
currentY += deltaY;
}
}
string[] result = new string[20];
for (int i = 0; i < 20; i++)
Console.WriteLine(result[i] = new string(pixels[i]));
return result;
}
}
public class MatrixTool
{
public string[] convert(string s)
{
int length = s.Length;
int sqrt = (int)Math.Sqrt(length);
if (sqrt * sqrt != length)
return new string[] { };
string[] result = new string[sqrt];
for (int i = 0; i < Math.Sqrt(length); i++)
result[i] = s.Substring(i * sqrt, sqrt);
return result;
}
}
public class CursorPosition
{
public int getPosition(string keystrokes, int N)
{
int position = 0;
for (int i = 0; i < keystrokes.Length; i++)
{
switch (keystrokes[i])
{
case 'L':
if (position > 0)
position -= 1;
break;
case 'R':
if (position < N)
position += 1;
break;
case 'H':
position = 0;
break;
case 'E':
position = N;
break;
}
}
return position;
}
}
--------------------------------
Email: caiwen@mail.ustc.edu.cn
QQ: 28592801
No pains, no gains. -- 谁说眼泪是醉