Google考题试解 - DrawLines

习得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));
  }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值