2017-11-17 66 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 –