如何从二维数组生成序列

问题描述 投票:0回答:1

我被告知要生成附图中的数字序列

以蓝色突出显示的数字

为此我使用了

int[][] generate2DArray(int numberOfRows, int noOfColumns){
    int[][] dynamic2DArray = new int[12][12];

    int outerRowLimit = dynamic2DArray.length;
    int innerColumnLimit = dynamic2DArray[0].length;

    int outerLoopCounter = 0;
    int innerLoopCounter = 0;

    while(outerLoopCounter < outerRowLimit){
        while(innerLoopCounter < innerColumnLimit){
            int currentElement = (outerLoopCounter + 1) * (innerLoopCounter + 1);
            dynamic2DArray[outerLoopCounter][innerLoopCounter] = currentElement;
            innerLoopCounter++;
        }
        innerLoopCounter = 0;
        outerLoopCounter++;
    }
    return dynamic2DArray;
}

现在的问题是我被告知生成那些以黄色突出显示的内容。有人可以帮忙吗?

我试过了

int currentElement = (innerLoopCounter + 10)-2;

java arrays 2d
1个回答
0
投票

有一个非常简单的方法可以做到这一点,我不太确定这个动态二维数组应该是什么样子我假设你想突出显示点并将其余的点设为 0。你可以只使用 2 嵌套时间复杂度小于 O(n^2) 的循环[因为您没有迭代每个元素]。这是一个示例,您可以尝试将其合并到您的程序中:

import java.util.*;
public class StackOverflow{
    // example of a random 2d arr
    public int[][] arr = {
            {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15},
            {16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30},
            {31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45},
            {46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60},
            {61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75},
            {76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90},
            {91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105},
            {106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120},
            {121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135},
            {136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150},
            {151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, 165},
            {166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179, 180},
            {181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, 195},
            {196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210},
            {211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223, 224, 225}
        };
    public int[][] dynamicArr(int r, int c){
        int[][] dynamicRetArr = new int[r][c];
        for(int i = 0; i < dynamicRetArr.length; i++)
            dynamicRetArr[i][i] = arr[i][i];

        for(int i = 0; i < dynamicRetArr.length; i++)
            for(int j = dynamicRetArr.length-1; j >= 0; j--)
                dynamicRetArr[i][j] = arr[i][j];
        return dynamicRetArr;
    }
}

旁注,但请确保使用方法的参数,而不是对行和列使用 12 和 12

© www.soinside.com 2019 - 2024. All rights reserved.