Google考题试解 - DrawLines
来源:互联网 发布:网络存储技术 编辑:程序博客网 时间:2024/05/22 12:07
习得Java不久,请高手指教 :)
public class DrawLines {
public String[] execute(String[] commands){
final int LIMITX=20, LIMITY=20;
char[][] canvas=new char[LIMITX][LIMITY];
final char ink='X', blank='.';
int direction;
final int RIGHT=0, UP=1, LEFT=2, DOWN=3;
final int[][] offset={{1,0}, {0,-1}, {-1,0}, {0,1}}; // x,y offset of each direction
int x, y;
//init canvas
for(y=0; y<LIMITY; y++)
for(x=0; x<LIMITX; x++)
canvas[y][x]=blank;
//init cursor
x=y=0;
direction=DOWN;
//canvas[y][x]=ink; the problem may be a fault about the cursor init behavior
//process commands
for(int i=0; i<commands.length; i++){
if(commands[i].equals("LEFT")){ //command LEFT
direction=(direction+1)%4;
}else if(commands[i].startsWith("FORWARD")){ //command FORWARD
canvas[y][x]=ink; // only for first pixel!! sigh...
int step=Integer.parseInt( commands[i].substring(8) );
for(int j=0; j<step; j++){
canvas[y+=offset[direction][1]][x+=offset[direction][0]]=ink;
}
}
}
String[] result = new String[LIMITY];
for(int i=0; i<LIMITY; i++){
result[i]=new String(canvas[i]);
}
return result;
}
private static void draw(String[] line){
for(int i=0; i<line.length; i++){
System.out.println(line[i]);
}
}
public static void main(String[] args) {
String[] cmd0= {"FORWARD 19", "LEFT", "FORWARD 19", "LEFT", "FORWARD 19", "LEFT", "FORWARD 19"};
String[] cmd1= {"LEFT", "LEFT", "LEFT", "LEFT", "LEFT", "LEFT", "LEFT", "LEFT"};
String[] cmd2={"FORWARD 1"};
String[] cmd3={"LEFT", "FORWARD 19", "LEFT", "LEFT", "LEFT",
"FORWARD 18", "LEFT", "LEFT", "LEFT", "FORWARD 17",
"LEFT", "LEFT", "LEFT", "FORWARD 16", "LEFT",
"LEFT", "LEFT", "FORWARD 15", "LEFT", "LEFT", "LEFT",
"FORWARD 14", "LEFT", "LEFT", "LEFT", "FORWARD 13",
"LEFT", "LEFT", "LEFT", "FORWARD 12", "LEFT", "LEFT",
"LEFT", "FORWARD 11", "LEFT", "LEFT", "LEFT", "FORWARD 10",
"LEFT", "LEFT", "LEFT", "FORWARD 9", "LEFT", "LEFT",
"LEFT", "FORWARD 8", "LEFT", "LEFT", "LEFT", "FORWARD 7"};
DrawLines d=new DrawLines();
draw(d.execute(cmd0));
draw(d.execute(cmd1));
draw(d.execute(cmd2));
draw(d.execute(cmd3));
}
}
- Google考题试解 - DrawLines
- Google考题试解 - BusStops
- 考题
- 考题
- 考题
- 考题
- 考题
- java drawlines()方法
- 华为2013机试考题拉灯泡
- 【机器学习】 机器学习方法解幼儿园考题
- android drawText/drawLines不显示的原因
- VC.NET + MFC 使用 GDI+ DrawLines 画线
- 华为2014暑期实习生招聘机试考题回忆
- IPAT考题
- 考题大全
- ajax考题
- 高考题
- 删除考题
- [B原创] Install Gentoo From Stage1 - Part 3
- 疑惑
- [转贴】十大职场困惑出炉 十帖妙方镇痛(上)
- 算法设计——问一个算法题(算法导论的作业题) (转载自水木清华Programming)
- 日期对话框的JS
- Google考题试解 - DrawLines
- 【转贴】十大职场困惑出炉 十帖妙方镇痛(下)
- struts的结构
- MAIGO的同济题解1
- 工作近半年的感受
- MAIGO的同济题解2
- [转]技术人员的最终出路
- 乡愁
- 妨碍你晋升的八种坏习惯