创建一个在java

时间:2017-10-13 17:01:32

标签: java matrix

我尝试创建一个矩阵来存储信息。例如,如果A和Q相遇,则返回-1。我的问题是在2D数组中,没有办法存储字符和int,有没有办法在java中初始化下面的矩阵?

   A  R  N  D  C  Q    
A  4 -1 -2 -2  0 -1  
R -1  5  0 -2 -3  1   
N -2  0  6  1 -3  0   
D -2 -2  1  6 -3  0  
C  0 -3 -3 -3  9 -3   
Q -1  1  0  0 -3  5 

4 个答案:

答案 0 :(得分:4)

地图地图怎么样?

Map<Character, Map<Character, Integer>> matrix = TreeMap<>();

除了TreeMap之外,您可以使用Map的其他实现,但我想您希望按字母顺序对键进行排序(注意大小写)。

您可以像填充任何地图一样填充地图。例如,对于字母A ......

Map<Character, Integer> mapA = new TreeMap<>();
mapA.put('A', 4);
mapA.put('R', -1);
mapA.put('N', -2);
mapA.put('D', -2);
mapA.put('C', 0);
mapA.put('Q', -1);

matrix.put('A', mapA);

要引用AQ,您可以调用matrix.get('A').get('Q')并获得所需的-1

答案 1 :(得分:3)

在您的示例中&#34; A&#34;,&#34; R&#34;,&#34; N&#34;,&#34; D&#34;,&#34; C&#34;和&#34; Q&#34;不是矩阵的成员,它们是其索引的轴标签。您不需要将它们存储在与整数相同的矩阵中。

使用标签创建一个单独的数组,并将其用于&#34;翻译&#34;索引名称('A''R''N'等)到矩阵维度的数字索引。

一种方法是使用String dimLabels = "ARNDCQ",并对其应用indexOf以将索引输入矩阵:

static final String dimLabels = "ARNDCQ";

char dimChar = 'R';
int dimIndex = dimLabels.indexOf(dimChar);
if (dimIndex >= 0) {
    ... // The index is valid
} else {
    ... // The index name is invalid
}

答案 2 :(得分:3)

您可以创建一个自己的类,您可以在其中存储必要的信息,如下所示:

the cached

然后,您可以创建class Dot { private int value; private String rowId; private String columnId; public Dot(String rowId, String columnId, int value) { this.rowId = rowId; this.columnId = columnId; this.value = value; } // getter / setters } ,将点添加到列表中,并为List创建方法。

search(comunnId, rowId)

和搜索方法:

List martix = new ArrayList<Dot>();
matrix.add(new Dot("A", "Q", -1));
...

希望它可以帮助您实现您想要的效果。

答案 3 :(得分:2)

您可以将整数数组和顺序与每个字符相关联,从而有效地将矩阵构建为地图。

    Map<Character, int[]> dataMap = new HashMap<>();
    dataMap.put('A', new int[] { 4, -1, -2, -2,  0, -1});
    dataMap.put('R', new int[] {-1,  5,  0, -2, -3,  1});
    dataMap.put('N', new int[] {-2,  0,  6,  1, -3,  0});
    dataMap.put('D', new int[] {-2, -2,  1,  6, -3,  0});
    dataMap.put('C', new int[] { 0, -3, -3, -3,  9, -3});
    dataMap.put('Q', new int[] {-1,  1,  0,  0, -3,  5});

    Map<Character, Integer> orderMap = new HashMap<>();
    orderMap.put('A', 0);
    orderMap.put('R', 1);
    orderMap.put('N', 2);
    orderMap.put('D', 3);
    orderMap.put('C', 4);
    orderMap.put('Q', 5);

    int val = dataMap.get('A')[orderMap.get('Q')];
    System.out.println(val);