在程序C#中创建模式 [英] Make pattern in program C#

查看:71
本文介绍了在程序C#中创建模式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

输入:

N = 4

输出:

input :
N=4
Output:

1  2  3  4
12 13 14 5
11 16 15 6
10 9  8  7





我尝试了什么:



i已经使用嵌套循环和数组,但它不起作用。



What I have tried:

i already using nested loop and array but it did not work.

推荐答案

首先,您需要创建一个数组来保存值(因为它们不按顺序跟随,可以很容易地打印到控制台,您应该将它们放入一个数组中,然后在完成后打印它们。)

使数组2维:N x N

First, you need to create an array to hold the values (because they don't follow in sequence that can easily be printed to the console, you should put them into an array, and then print them when it's complete.)
Make the array 2 dimensional: N x N
int[,] data = new int[N, N];

并且它将预先填入零。

创建一对x和y索引器,并从零开始。

还创建两个名为dx和dy的整数,并将dx设置为1和dy为零。

现在从0循环到(N * N) - 1次变量名为i

在循环中,将data [x,y]的值设置为i + 1,

然后将dx添加到x并将dy添加到y,并查看结果。

如果x和y在数组中,请查看它们现在指向的元素。如果它为零,则为空,所以一切正常

否则,你需要改变方向。



dx和dy的值控制着你要移动的方向,所以看看它们,你应该如何更改它们应该是相当明显的:(1, 0)变为(0,1); (0,1)变为(-1,0); (-1,0)变为(0,-1),(0,-1)再次变为(1,0)。



试一试纸,你应该明白我的意思。经过深思熟虑后,将其转换为代码并不困难!

And it will be prefilled with zeros.
Create a pair of x and y indexers, and start them at zero.
Also create tow more integers called dx, and dy, and set dx to 1 and dy to zero.
Now loop from 0 to (N * N) - 1 times on a variable called i
Inside the loop, set the value of data[x, y] to i + 1,
Then add dx to x and dy to y, and look at the results.
If x and y are inside the array, look at the element they now point to. If it's zero, it's empty, so it's all ok
Otherwise, you need to change direction.

The values of dx and dy control which direction you will moving in, so look at them and it should be fairly obvious how you need to change them: (1, 0) becomes (0, 1); (0, 1) becomes (-1, 0); (-1, 0) becomes (0, -1), and (0, -1) becomes (1, 0) again.

Give it a try on paper, and you should see what I mean. With a bit of thought, it shouldn't be difficult to convert that into code!


希望击败死马,我添加无阵列解决方案。

Wishing to beat the dead horse, I add my array-less solution.
public static int ring_contribution(int d, int x, int y)
{
  if (y == -d)
    return (d - 1) + (d + x) / 2;
  else if (y == d)
    return (d - 1) + 2 * d + (d - x) / 2;
  else if (x == -d)
    return (d - y) / 2 - 1;
  else
    return 2 * d + (d + y) / 2 - 1;
}
public static void Main()
{
  Console.WriteLine("plaese enter the dimension");
  string line = Console.ReadLine();
  int n;
  if (!int.TryParse(line, out n)) return;

  int n2 = n * n;
  int N = n - 1;
  for (int y = N; y >= -N; y -= 2)
  {
    for (int x = -N; x <= N; x += 2)
    {
      int d = Math.Max(Math.Abs(x), Math.Abs(y)); // distance
      int v = (d - 1) * (d - 1); // inner squares contribution
      v += ring_contribution(d, x, y); // outer ring contribution
      Console.Write("{0,4:####}", n2-v);
    }
    Console.WriteLine();
  }
}


这篇关于在程序C#中创建模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆