C#控制台应用程序网格计算

时间:2017-11-17 23:51:31

标签: c# console-application

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

应用程序处理机器人行进一次的块数,如果机器人路径的X坐标和Y坐标在任何时间交叉,则该块计数一次而不是两次。例如,如果机器人行进N4,2E,2S和4W,则机器人在其开始运动的第二个区块上将存在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);
        }



    }

1 个答案:

答案 0 :(得分: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);