Domanda

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.

È stato utile?

Soluzione

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.

Altri suggerimenti

If you are given an integer n and you are iterating over the integers from 0 to n^2. In the loop you can use mod to determine if you are an the end of a line.

       if((i mod n) == 0){
           //print a new line here
       }

So simply write a loop that goes from 0 to n^2 and use that if statement to know when to break to the next line.

public static void main(String[] args) {

        Map<Integer, Integer> hashmap = new HashMap<Integer, Integer>();
        hashmap.put(1, 10);
        hashmap.put(2, 90);
        hashmap.put(4, 9);
        hashmap.put(7, 2);
        hashmap.put(11, 4);
        hashmap.put(14, 45);

        printSquare(4, hashmap);
    }

    public static void printSquare(int dimension, Map<Integer,Integer> map){
        int grid = dimension * dimension;

        for(int x = 0; x < grid; x++){

            Integer value = map.get(x);
            value = (value == null) ? 0:value;

            if(x != 0 && x % 4 == 0){
                System.out.println("\n");
                System.out.print(value);
                System.out.print("\t");
            }else{
                System.out.print(value);
                System.out.print("\t");
            }
        }
    }
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top