English 中文(简体)
从矩阵中提取按特定方向的所有对数线列表
原标题:Extracting a list of all diagonals from a matrix in a specific direction
  • 时间:2012-05-23 04:11:37
  •  标签:
  • java
  • matrix

我试图从一个矩阵中提取 所有的对角体 在某个方向,例如右下角。

下列矩阵:

A   B   C   D
E   F   G   H
I   L   M   N

预期成果

[ [A F M], [B G N], [C H], [D], [E L], [I] ]

普遍的做法值得欢迎。

我使用的语言是爪哇语。

谢谢!

<强 > EDIT

String[] grid = {"SUGAR", 
                 "GLASS", 
                 "MOUSE"};

for( int k = 0; k < grid.length; k++ )
{   
    StringBuffer buffer = new StringBuffer( );

    for( int i = 0; i < grid.length
                && i+k < grid[0].length( ); i++ )
    {
        buffer.append( grid[i].charAt(i+k) );
    }

    trie.addWord( buffer.toString() );
}

添加到三角体的输出单词

[ "SLU" "UAS" "GSE" ]

存储在三角中的预期字符串( 顺序无关紧要 )

[ "SLU" "UAS" "GSE" "GO" "M" "AS" "R"]
最佳回答

这是一个需要解决的有趣问题。

很容易被嵌入的环圈缠住

我注意到,如果我把单词放在一个字符串中, 出现了一个模式。

以《任择议定书》为例,三个词“SUGAR”、“GLASS”、“MOUSE”被混为SUGARASSONESE。

这是基于零字符的字符性位置, 我需要从连接字符串中获取这些字符。 我把它们排成一行, 这样您就可以更容易地看到模式 。

          10     M
     5    11     GO
0    6    12     SLU
1    7    13     UAS
2    8    14     GSE
3    9           AS
4                R

看到图案了吗?我有3个指数,由5个迭代组成。我有三个字,由5个字母组成。

对角单词数为 letters + words - 1 。 我们减去 1, 因为字符位置 0 的第一个字母只使用过一次 。

这是我测试的结果

[ "SUGAR" "GLASS" "MOUSE" "STATE" "PUPIL" "TESTS" ]
[ "T" "PE" "SUS" "MTPT" "GOAIS" "SLUTL" "UASE" "GSE" "AS" "R" ]

[ "SUGAR" "GLASS" "MOUSE" ]
[ "M" "GO" "SLU" "UAS" "GSE" "AS" "R" ]

这里的代码是:

import java.util.ArrayList;
import java.util.List;

public class Matrix {

    public static final int DOWN_RIGHT = 1;
    public static final int DOWN_LEFT = 2;
    public static final int UP_RIGHT = 4;
    public static final int UP_LEFT = 8;

    public String[] getMatrixDiagonal(String[] grid, int direction) {
        StringBuilder builder = new StringBuilder();
        for (String s : grid) {
            builder.append(s);
        }
        String matrixString = builder.toString();

        int wordLength = grid[0].length();
        int numberOfWords = grid.length;
        List<String> list = new ArrayList<String>();


        if (wordLength > 0) {
            int[] indexes = new int[numberOfWords];

            if (direction == DOWN_RIGHT) {
                indexes[0] = matrixString.length() - wordLength;
                for (int i = 1; i < numberOfWords; i++) {
                    indexes[i] = indexes[i - 1] - wordLength;
                }

                int wordCount = numberOfWords + wordLength - 1;

                for (int i = 0; i < wordCount; i++) {
                    builder.delete(0, builder.length());
                    for (int j = 0; (j <= i) && (j < numberOfWords); j++) {
                        if (indexes[j] < wordLength * (wordCount - i)) {
                            char c = matrixString.charAt(indexes[j]);
                            builder.append(c);
                            indexes[j]++;
                        }
                    }
                    String s = builder.reverse().toString();
                    list.add(s);
                }
            }

            if (direction == DOWN_LEFT) {
                // Exercise for original poster
            }

            if (direction == UP_RIGHT) {
                // Exercise for original poster
            }

            if (direction == UP_LEFT) {
                // Exercise for original poster
                // Same as DOWN_RIGHT with the reverse() removed
            }
        }

        return list.toArray(new String[list.size()]);
    }

    public static void main(String[] args) {
        String[] grid1 = { "SUGAR", "GLASS", "MOUSE", "STATE", "PUPIL", "TESTS" };
        String[] grid2 = { "SUGAR", "GLASS", "MOUSE" };

        Matrix matrix = new Matrix();
        String[] output = matrix.getMatrixDiagonal(grid1, DOWN_RIGHT);
        System.out.println(createStringLine(grid1));
        System.out.println(createStringLine(output));

        output = matrix.getMatrixDiagonal(grid2, DOWN_RIGHT);
        System.out.println(createStringLine(grid2));
        System.out.println(createStringLine(output));
    }

    private static String createStringLine(String[] values) {
        StringBuilder builder = new StringBuilder();
        builder.append("[ ");

        for (String s : values) {
            builder.append(""");
            builder.append(s);
            builder.append("" ");
        }

        builder.append("]");

        return builder.toString();
    }

}
问题回答

如果您的数据以表格形式出现,您可以将矩阵扫描到第一列上,然后左过第一行。

final String[M][N] mtx = { ... };

public List<List<String>> diagonalize() {
    final List<List<String>> diags = new ArrayList<>();
    for (int row = M - 1; row > 1; --row) {
        diags.add(getDiagonal(row, 0));
    }
    for (int col = 0; col < N; ++col) {
        diags.add(getDiagonal(0, col));
    }
    return diags;
}

private List<String> getDiagonal(int x, int y) {
    final List<String> diag = new ArrayList<>();
    while (x < M && y < N) {
        diag.add(mtx[x++][y++]);
    }
    return diag;
}
    String[] grid = {"SUGAR", 
             "GLASS", 
             "MOUSE"};
    System.out.println("Result: " + Arrays.toString(diagonals(grid)));

public static String[] diagonals(String[] grid) {
    int nrows = grid.length;
    int ncols = grid[0].length();
    int nwords = ncols + nrows - 1;
    String[] words = new String[nwords];
    int iword = 0;
    for (int col = 0; col < ncols; ++col) {
        int n = Math.min(nrows, ncols - col);
        char[] word = new char[n];
        for (int i = 0; i < n; ++i) {
            word[i] = grid[i].charAt(col + i);
        }
        words[iword] = new String(word);
        ++iword;
    }
    for (int row = 1; row < nrows; ++row) {
        int n = Math.min(ncols, nrows - row);
        char[] word = new char[n];
        for (int i = 0; i < n; ++i) {
            word[i] = grid[row + i].charAt(i);
        }
        words[iword] = new String(word);
        ++iword;
    }
    assert iword == nwords;
    return words;
}

Result: [SLU, UAS, GSE, AS, R, GO, M]

First a loop with the first element on the column. Then a loop on the rows, skipping row 0. The code in both loops is very symmetric. Nothing too difficult. Assumed is that all strings have the same length.

一个循环 :

public static String[] diagonals(String[] grid) {
    int nrows = grid.length;
    int ncols = grid[0].length();
    int nwords = ncols + nrows - 1;
    String[] words = new String[nwords];

    // Position of first letter in word:
    int row = 0;
    int col = ncols - 1;

    for (int iword = 0; iword < nwords; ++iword) {
        int n = Math.min(nrows - row, ncols - col);
        char[] word = new char[n];
        for (int i = 0; i < n; ++i) {
            word[i] = grid[row + i].charAt(col + i);
        }
        words[iword] = new String(word);

        if (col > 0) {
            --col;
        } else {
            ++row;
        }
    }
    return words;
}

word 的宣告可以带出环圈外。只需用左侧和上边缘(行、行、行)走。

您可以使用二维阵列代表您的矩阵,

字符 [ [] 矩阵 =字符 [ ]

然后,你就可以用循环循环来进行循环, 并提取您想要的输出, 输入您的算法将会是您想要的对角方向 。

对于Ex; 一个可能的输入将右下

根据可能的投入,您必须决定如何通过循环初始条件和终止条件进行循环。

以上列第一行字符开始

r = 0, c = colm_count - 1;

终止条件将是Ist_clum last行索引中的字符。

r = 行数 - 计数 - 1, c = 0;

在最后一行或最后一列最后一行或最后一列的读取字符是子循环的终止时的每次迭代





相关问题
Spring Properties File

Hi have this j2ee web application developed using spring framework. I have a problem with rendering mnessages in nihongo characters from the properties file. I tried converting the file to ascii using ...

Logging a global ID in multiple components

I have a system which contains multiple applications connected together using JMS and Spring Integration. Messages get sent along a chain of applications. [App A] -> [App B] -> [App C] We set a ...

Java Library Size

If I m given two Java Libraries in Jar format, 1 having no bells and whistles, and the other having lots of them that will mostly go unused.... my question is: How will the larger, mostly unused ...

How to get the Array Class for a given Class in Java?

I have a Class variable that holds a certain type and I need to get a variable that holds the corresponding array class. The best I could come up with is this: Class arrayOfFooClass = java.lang....

SQLite , Derby vs file system

I m working on a Java desktop application that reads and writes from/to different files. I think a better solution would be to replace the file system by a SQLite database. How hard is it to migrate ...

热门标签