将一串数字插入矩阵

时间:2014-11-28 11:48:24

标签: java

我有点卡在这个算法中。我在下面有这个函数得到一个字符串和一个矩阵[n] [m]。 字符串最多有n * m个数字,我需要分别从最后一个数字到矩阵的最后一个单元格反向插入它们,直到我到达第一个单元格;

例如:String =' 3'就像{[0] [0],[0] [3]}; String =' 123'就像{[0] [1],[2] [3]};和String =' 2222'就像{[2] [2],[2] [2]};

问题是:对于String' 123'我得到一个矩阵{[1] [1],[1] [1]}。似乎只有第一个数字插入矩阵。

stringToInteger(String correctBase, int [][] board)
{
    int integerNum;

    for(int i=correctBase.length()-1; i>=0; i--)         
    {
        integerNum=correctBase.charAt(i)-'0';               
        for(int row=board.length-1; row>=0; row--)       
            for(int col=board[row].length-1; col>=0; col--)
                board[row][col]=integerNum;
    }

3 个答案:

答案 0 :(得分:1)

试试这个:

stringToInteger(String correctBase, int [][] board)
{
    int integerNum;
    int row = board.length - 1;
    int col = board[0].length - 1;

    for(int i=correctBase.length()-1; i>=0; i--)         
    {
        integerNum=correctBase.charAt(i)-'0';
        board[row][col]=integerNum;
        col--;
        if(col < 0) {
            col = board[0].length - 1;
            row--;
        }
    }
    ...
}

答案 1 :(得分:0)

是,或者:

    int i = correctBase.length();
    for(int row=board.length-1; row>=0; row--)       
        for(int col=board[row].length-1; col>=0; col--)
            board[row][col] = i > 0 ? correctBase.get(--i)-'0' : 0;

答案 2 :(得分:0)

我首先检查字符串的大小是否与矩阵的大小相匹配。如果没有,则用零填充所述字符串。然后只需解析字符串的位置并将它们插入矩阵。

试试这样。

public static void main(String[] args) {
    //define size of matrix
    int n = 2;
    int m = 2;

    String input = "3";

    //if size of string is less than matrix size we append 0 to it
    if (input.length() < n * m) {
        int diff = n * m - input.length();

        for (int i = 0; i < diff; i++)
            input = "0" + input; //pad zeroes to the string
    }

    int board[][] = new int[n][m]; //declare matrix

    //populate matrix
    int stringPosition = 0; //position in the string starting from the left
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < m; j++) {
                board[i][j] =
                        Character.getNumericValue(input.charAt(stringPosition)); //transfrom char to int, then assign it to matrix
            stringPosition++; //increment position
        }
    }

    //display matrix
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < m; j++) {
            System.out.println("board[" + i + "][" + j + "] = " + board[i][j]);
        }
    }
}

它产生了预期的结果

input="3"

board[0][0] = 0
board[0][1] = 0
board[1][0] = 0
board[1][1] = 3


input="123"

board[0][0] = 0
board[0][1] = 1
board[1][0] = 2
board[1][1] = 3


input="2222"

board[0][0] = 2
board[0][1] = 2
board[1][0] = 2
board[1][1] = 2