Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

Hey I have a LinkedHashMap containing several values but I'm struggling to print it in the format I want. It will be passed a size integer, and I want it to print out the values in a square format, and if there's not a value for a certain key up to the size value to place a 0 there instead.

Say these are the values in the hashmap, first is location, 2nd is value

hashmap.put(1, 10); 
hashmap.put(2, 90); 
hashmap.put(4, 9); 
hashmap.put(7, 2); 
hashmap.put(11, 4); 
hashmap.put(14, 45); 

I'd like it to print as follows after being passed the value 4 (the height/width).

0 10 90 0
9 0  0  2
0 0  0  4
0 0  45 0

Sorry this is really badly described, not sure how to say it any better! Cheers for any help.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
245 views
Welcome To Ask or Share your Answers For Others

1 Answer

public static void printMapAsMatrix(Map<Integer, Integer> map, int size) {
    for (int i = 0; i < size; i++) {
        for (int j = 0; j < size; j++) {
            Integer v = map.get(size * i + j);
            if (v == null)
                v = 0;
            System.out.printf("%1$-5s", v);
        }
        System.out.println();   
    }
}

This solution pads every cell so that it occupied 5 chars. You may change this if needed. The idea is to create the full matrix by scanning all cells (0..size-1)x(0..size-1), and fetching the value of that cell from the map. Line i and column j should be transformed to key=size * i + j, because we have to skip i lines and j items in the current line. Non existent items are converted to 0.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...