Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/373.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 在二维数组中绘制数字菱形_Java_Arrays - Fatal编程技术网

Java 在二维数组中绘制数字菱形

Java 在二维数组中绘制数字菱形,java,arrays,Java,Arrays,我一直在解决一些编码问题,为编码面试做准备,发现了一个似乎有点令人费解的问题。我花了一些时间解决了这个问题;但是,代码看起来是硬编码的,没有样式。因此,我想知道我是否可以得到一些关于设计代码样式的反馈,或者也许可以得到更好的解决问题的方法 这个问题基本上要求你画一个二维数组中带有图案的菱形数字。 它给出了“x”的坐标和x的范围。从x开始,数字一个接一个地扩散,直到范围。因此,有4种不同的输入,N(数组的大小)、X、Y(X的坐标)和R(范围) 如果它们的大小为8,坐标为(4,5),范围为3,结果如

我一直在解决一些编码问题,为编码面试做准备,发现了一个似乎有点令人费解的问题。我花了一些时间解决了这个问题;但是,代码看起来是硬编码的,没有样式。因此,我想知道我是否可以得到一些关于设计代码样式的反馈,或者也许可以得到更好的解决问题的方法

这个问题基本上要求你画一个二维数组中带有图案的菱形数字。 它给出了“x”的坐标和x的范围。从x开始,数字一个接一个地扩散,直到范围。因此,有4种不同的输入,N(数组的大小)、X、Y(X的坐标)和R(范围)

如果它们的大小为8,坐标为(4,5),范围为3,结果如下:

0 0 0 0 3 0 0 0
0 0 0 3 2 3 0 0
0 0 3 2 1 2 3 0
0 3 2 1 x 1 2 3
0 0 3 2 1 2 3 0
0 0 0 3 2 3 0 0
0 0 0 0 3 0 0 0
0 0 0 0 0 0 0 0
下面是我所拥有的

    int n = sc.nextInt();
    char[][] arr = new char[n][n];
    int r = sc.nextInt() - 1;
    int c = sc.nextInt() - 1;
    int range = sc.nextInt();

    for (int i = 0; i < n; i++) {
        for (int j = 0; j < n; j++) {
            arr[i][j] = '0';
        }
    }

    arr[r][c] = 'x';


    int num = 1;
    for (int i = 0; i < range; i++) {
        //Cross
        if (c-num > -1) {
            arr[r][c - num] = (char) (num + '0');
        }
        if (c+num < n) {
            arr[r][c + num] = (char) (num + '0');
        }
        if (r-num > -1) {
            arr[r - num][c] = (char) (num + '0');
        }
        if (r+num < n) {
            arr[r + num][c] = (char) (num + '0');
        }
        //Diagonal
        if (i > 0) {
            int sum = num - 1, delta = 1;

            while (sum != 0) {
                if (r-sum > -1 && c+delta < n) {
                    arr[r - sum][c + delta] = (char) (num + '0');
                }
                sum--;
                delta++;
            }
            sum = num - 1; delta = 1;
            while (sum != 0) {
                if (r+sum < n && c-delta > -1) {
                    arr[r + sum][c - delta] = (char) (num + '0');
                }
                sum--;
                delta++;
            }
            sum = num - 1; delta = 1;
            while (sum != 0) {
                if (r-sum > -1 && c-delta > -1) {
                    arr[r - sum][c - delta] = (char) (num + '0');
                }
                sum--;
                delta++;
            }
            sum = num - 1; delta = 1;
            while (sum != 0) {
                if (r+sum < n && c+delta > -1) {
                    arr[r + sum][c + delta] = (char) (num + '0');
                }
                sum--;
                delta++;
            }
        }
        num++;
    }
int n=sc.nextInt();
字符[][]arr=新字符[n][n];
int r=sc.nextInt()-1;
int c=sc.nextInt()-1;
int range=sc.nextInt();
对于(int i=0;i-1){
arr[r][c-num]=(char)(num+'0');
}
如果(c+num-1){
arr[r-num][c]=(char)(num+'0');
}
如果(r+num0){
int sum=num-1,delta=1;
while(总和=0){
if(r-sum>-1&&c+delta-1){
arr[r+sum][c-delta]=(char)(num+'0');
}
总和--;
delta++;
}
总和=num-1;增量=1;
while(总和=0){
如果(r-sum>-1和&c-delta>-1){
arr[r-sum][c-delta]=(char)(num+'0');
}
总和--;
delta++;
}
总和=num-1;增量=1;
while(总和=0){
if(r+sum-1){
arr[r+sum][c+delta]=(字符)(num+'0');
}
总和--;
delta++;
}
}
num++;
}

除了使用四个不同的while循环,我想不出任何其他方法来处理对角线数字。我希望得到任何反馈。提前谢谢

您只需在阵列上循环一次,然后根据当前位置
(i,j)
到固定坐标
(x,j)
的相对距离设置值

您的代码可能如下所示:

import java.util.Arrays;

public class Test {
    public static void main(String[] args) {
        // variables
        int n = 8;
        int x = 4 - 1; // coordinates are one-based
        int y = 5 - 1; // coordinates are one-based
        int r = 3;
        char[][] array = new char[n][n];

        // logic
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++) {
                int dist = Math.abs(x - i) + Math.abs(y - j); // calculate distance

                if(dist == 0) {         // at x,y
                    array[i][j] = 'x';
                } else if (dist <= r) { // distance to x,y is within range
                    array[i][j] = (char) (dist + '0');
                } else {                // distance to x,y is outside of range
                    array[i][j] = '0';
                }
            }
        }

        // dump output
        System.out.println(Arrays.deepToString(array)
                           .replace("], ", "]\n")
                           .replace("[", "")
                           .replace("]", "")
                           .replace(", ", " "));
    }
}
如果希望更简洁,可以用三元运算符替换分支的
If…else If…else
语句:

array[i][j] = dist == 0 ? 'x' : dist <= r ? (char) (dist + '0') : '0';

array[i][j]=dist==0?”x':dist您可以尝试使用泛洪填充,尽管根据您的级别,它可能有点远

编辑:Robby Cornelissen的代码看起来比我的代码更干净、更简单,所以你应该看看他的代码。然而,洪水填充对于以后来说是一个非常重要的概念,所以不妨看看

这篇文章很长,但是文章中的GIF是最重要的部分

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.Queue;
import java.util.StringTokenizer;

public class test {

    public static void main(String[] args) throws IOException {
        //Get inputs (I used BufferedReader, Scanner works fine as well)
        //My inputs are formatted as 'N X Y R' (ex. '8 4 5 3')
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StringTokenizer st = new StringTokenizer(br.readLine(), " ");
        int N = Integer.parseInt(st.nextToken());
        int R = Integer.parseInt(st.nextToken()) - 1;
        int C = Integer.parseInt(st.nextToken()) - 1;
        int range = Integer.parseInt(st.nextToken());
        char[][] arr = new char[N][N];

        //Make everything in array '0'
        for (int i = 0; i < N; i++) {
            Arrays.fill(arr[i], '0');
        }

        //Floodfill using BFS
        //FYI: this BFS is iterative, not recursive
        Queue<int[]> q = new LinkedList<>();
        q.add(new int[]{0, R, C});
        while (!q.isEmpty()) {
            int[] current = q.remove();
            if (arr[current[1]][current[2]] == '0' && current[0] <= range) {
                arr[current[1]][current[2]] = (current[0]+"").charAt(0);
                if(current[1]+1 < N) q.add(new int[]{current[0]+1, current[1]+1, current[2]});
                if(current[1]-1>= 0) q.add(new int[]{current[0]+1, current[1]-1, current[2]});
                if(current[2]+1 < N) q.add(new int[]{current[0]+1, current[1], current[2]+1});
                if(current[2]-1>= 0) q.add(new int[]{current[0]+1, current[1], current[2]-1});
            }
        }
        arr[R][C] = 'x';

        //Print out the final grid
        for (int i = 0; i < N; i++) {
            for (int j = 0; j< N; j++) {
                System.out.print(arr[i][j] + " ");
            }
            System.out.println();
        }
    }
}
导入java.io.BufferedReader;
导入java.io.IOException;
导入java.io.InputStreamReader;
导入java.util.array;
导入java.util.LinkedList;
导入java.util.Queue;
导入java.util.StringTokenizer;
公开课考试{
公共静态void main(字符串[]args)引发IOException{
//获取输入(我使用了BufferedReader,扫描仪也可以正常工作)
//我的输入格式为'nxyr'(例如'84533')
BufferedReader br=新的BufferedReader(新的InputStreamReader(System.in));
StringTokenizer st=新的StringTokenizer(br.readLine(),“”);
int N=Integer.parseInt(st.nextToken());
int R=Integer.parseInt(st.nextToken())-1;
int C=Integer.parseInt(st.nextToken())-1;
int range=Integer.parseInt(st.nextToken());
字符[][]arr=新字符[N][N];
//在数组“0”中生成所有内容
对于(int i=0;i=0)q.add(new int[]{current[0]+1,current[1],current[2]-1});
}
}
arr[R][C]='x';
//打印出最终的网格
对于(int i=0;i
这里有一个相当简洁的方法。在每次迭代中,
i
我们用
i+1
菱形环填充一个单个字符宽的
i+1
,以
(行,列)
为中心,值
i
。为了避免填充菱形的内部,我们检查到
(行,列)
的曼哈顿距离是否等于
i
-这仅适用于菱形边界上的单元格

static char[][] buildDiamond(int n, int row, int col, int range)
{
  char[][] arr = new char[n][n];
  for(char[] a : arr) Arrays.fill(a, '0');
  arr[row][col] = 'x';

  for(int i=1; i<=range; i++)
    for(int j=0; j<=i; j++)
      for(int k=0; k<=i; k++)
        if(Math.abs(k-j) + Math.abs(k+j-i) == i)
          arr[row+k-j][col+k+j-i] += i;

  return arr;
}
输出:

0 0 0 3 0 0 0 
0 0 3 2 3 0 0 
0 3 2 1 2 3 0 
3 2 1 x 1 2 3 
0 3 2 1 2 3 0 
0 0 3 2 3 0 0 
0 0 0 3 0 0 0 

看起来X和Y被交换了。oo
0 0 0 3 0 0 0 
0 0 3 2 3 0 0 
0 3 2 1 2 3 0 
3 2 1 x 1 2 3 
0 3 2 1 2 3 0 
0 0 3 2 3 0 0 
0 0 0 3 0 0 0