2017-10-13 56 views
1

我嘗試創建一個矩陣來存儲信息。例如,如果A和Q相遇,它將返回-1。我的問題是,在二維數組中,沒有辦法存儲字符和整數,有沒有辦法在java中初始化下面的矩陣?創建一個在java中同時具有char和int的矩陣

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 
+0

Java中的數組只接受整數作爲數組的索引,因此,索引必須分兩步完成:一個將char轉換爲相應的數字索引,另一個將實際訪問矩陣。 –

+0

@Haroldo_OK在這種情況下,矩陣的順序會改變,也就是說,在修改過的矩陣中,A和R會彼此相鄰? – vkosyj

回答

3

在您的示例 「A」, 「R」, 「N」, 「d」, 「C」,和 「Q」 不屬於矩陣的成員,它們是其索引的軸標籤。您不需要將它們與整數存儲在相同的矩陣中。

用標籤創建一個單獨的數組,並使用它將索引名稱('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 
} 
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結果。

3

您可以創建自己的類,你可以在其中存儲必要的信息,這樣的事情:

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)); 
... 

和搜索方法:

public int search(String comunnId, String rowId) { 
    ... 
} 

希望它可以幫助你實現你想要的。

+0

令人耳目一新的是看到實際提升類的答案,而不是使用數組或Map <>。 –

+0

陣列數據類型不適合這個問題。 – zappee

+0

最簡單的解決方案是Map map;然後將其添加到地圖:(「AQ」,-1)。然後返回值非常簡單:map.get(「AQ」)。但這不是一個面向對象的解決方案,Java是一種強大的OO語言。 – zappee

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);