2017-11-17 67 views
-4

我想在C#中编写一个控制台应用程序,它计算机器人在地板上的网格中移动的唯一块的数量。输入需要使用四个指南针点的移动指令,例如:N,E,S W.C#控制台应用程序网格计算

如果X坐标和Y坐标为机器人的路径在任何时候交叉,该块被计数一次而不是两次。例如,如果机器人行进N4,2E,2S和4W,则机器人在其移动开始时行进的第2个区块上会出现x和y的交点。

这是我到目前为止有:

static void Main(string[] args) 
    { 

     //List<string> movements = new List<string>(); 

     int x1 = 0; 
     int y1 = 0; 

     int x2 = 0; 
     int y2 = 0; 

     int x3 = 0; 
     int y3 = 0; 

     int x4 = 0; 
     int y4 = 0; 



     int N, S, E, W, Total; 
     string coordinate1, coordinate2, coordinate3, coordinate4; 


     Console.Write("Enter North : "); 
     N = int.Parse(Console.ReadLine()); 

     if(N != 0) 
     { 
      x1 += 0; 
      y1 += N; 

     } 
     coordinate1 = "(" + x1 + "," + y1 + ")"; 








     Console.Write("Enter East: "); 
     E = int.Parse(Console.ReadLine()); 

     if (E != 0) 
     { 
      y3 += 0; 
      x3 += E; 

     } 
     coordinate3 = "(" + x3 + "," + y3 + ")"; 



     Console.Write("Enter South: "); 
     S = int.Parse(Console.ReadLine()); 

     if (S != 0) 
     { 
      x2 += 0; 
      y2 -= S; 

     } 

     coordinate2 = "(" + x2 + "," + y2 + ")"; 


     Console.Write("Enter West: "); 
     W = int.Parse(Console.ReadLine()); 

     if (W != 0) 
     { 
      y4 += 0; 
      x4 -= W; 

     } 
     coordinate4 = "(" + x4 + "," + y4 + ")"; 




     if (coordinate1 == coordinate2|| coordinate1== coordinate3 || coordinate1 == coordinate4 || coordinate2 == coordinate3 || coordinate2 == coordinate4 || coordinate3 ==coordinate4) 
     { 
      Total = (N + S + E + W) - 1 ; 
      Console.WriteLine("The total Blocks travelled are " + Total); 
     } 

     else 
     { 
      Total = N + S + E + W; 
      Console.WriteLine("The total Blocks travelled are " + Total); 
     } 



    } 
+2

解决这个问题的最好方法是问问老师或助教。这里没有人会为你编写从头开始的代码。不知道你知道它有多少难以提供指针 – pm100

+1

@ pm100我已经更新了一些我已经完成的代码的问题,我能够对输入做一个基本的计算,我不知道如何去前进如何确定一个块是否已经通过。 –

+0

输入(“机器人将采取的步骤顺序”)是任意移动列表,例如, 'N7 E2 S4 E9 N6 W14'或者如您的代码所示,在四个方向中的每一个方向上只有一个偏移量? – HABO

回答

1

你可以用简单的数学做。如果你想要更复杂的话,这也是简单的方法。

int N,S,E,W,Total; 
    Console.Write("Enter North : "); 
    N=int.Parse(Console.Readline()); 

    Console.Write("Enter South: "); 
    S=int.Parse(Console.Readline()); 

    Console.Write("Enter East: "); 

    E=int.Parse(Console.Readline()); 

    Console.Write("Enter West: "); 
    W=int.Parse(Console.Readline()); 

    if(N > S) 
     Total = N-S; 
    else 
     Total = S-N; 

    if(E > W) 
     Total += (E-W) 
    else 
     Total += (W-E) 

    Console.Write("Final Total Step are : "+Total); 
+1

['Math.Abs​​()'](https://docs.microsoft.com/en-us/dotnet/api/system.math.abs?view=netframework-4.7.1)可以简化事情。 – HABO

+1

但Math.Abs​​()只需要1个参数,并且此方法不能与多个值进行比较 –

+1

@KadirKalkan感谢您的帮助先生,不幸的是,这不起作用。例如,我的机器人向北移动4个方块,向东移动2个方块,向南移动2个方块和向西移动4个方块,机器人总共移动了12个方块,但它已经通过了一个已经穿过的方块(X会与Y),因此唯一块的数量是11 –