简体   繁体   中英

Creating weighted matrix with lettered edges

Is it at all possible to create an adjacency matrix that displays letters as the edges instead of numbers. For example, a weighted graph.

. a b c d e f  
a 0 1 0 0 0 0  
b 0 0 0 4 0 0  
c 0 0 1 0 0 0  
d 0 0 0 3 0 0  
e 0 2 0 0 0 0  
f 0 0 0 0 0 0  

I've tried everything as far as testing out my theories in accomplishing such task, such as

int let = 0;
String str = "a b c d e f";
char[] list = new char[str.length()];
for(int i = 0; i < list.length; i++)
{
    list[i] = str.charAt(i);
}
//To create the char array with letters used for the matrix
System.out.println();
for(int i = 0; i < list.length; i++)
{
    System.out.printf("%-3d", list[i]);
}
System.out.println();
for(int i = 0; i < list.length; i++)
{
    System.out.printf("%-3d", list[i]);
    for(int x = 0; x < list.length; x++)
    {
          System.out.printf("%-3d", let);
    }
    System.out.println();
 }

I just get a bunch of errors about printformat, and converting, and such. (Don't have eclipse open at the moment)

It works phenomenal if I replace (list[i]) with (i+1) to get numbers 1-6, but just nothing for letters. Is it even possible to accomplish this task? How would one go about creating a weighted matrix with letter edges if it's not possible.

This question may not be challenging for the majority of you, but as a beginner java programmer, I'm curious to learn, even if I have to suffer humility. No other way to learn.

You can print letters by casting the int values to char and adding the appropriate offset for the ASCII character you want. This example will print the letters af.

for (int i = 0; i < 6; i++) {
    System.out.printf("%-3c", (char) (i+97));
}

The ASCII value for 'a' is 97, 'b' is 98 and so on.

For reference: an ASCII table .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM