[原创]Google™ Code Jam - 中国编程挑战赛2005 训练题解答

greenland 2005-11-24 12:10:52
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. -- 谁说眼泪是醉
...全文
129 1 打赏 收藏 转发到动态 举报
写回复
用AI写文章
1 条回复
切换为时间正序
请发表友善的回复…
发表回复
fanweiwei 2005-11-24
  • 打赏
  • 举报
回复
mark

110,538

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧