简体   繁体   中英

1D array printed as 2D Java

I'm trying to print a sparse matrix from an array list where each object in the list comprises of a pair. The pair (object) holds two integers- position and value. [pos,val].

The position is the amount of zeros into the sparse matrix the whole numbers are located. So, represented as a 2d matrix you may have for example the following:

[000 0023 100] (sorry about the formatting, imagine a 3x3 matrix). Anyway, the array list for this would be

aList = {[5,23], [6,1]}

Now, I have the following code which I'm using to try and loop through them all to create a 6x6 matrix.

public void printFullMatrix() {

    int count = 0;
    int temp = 0;
    for (int i = 0; i < aList.size(); i++) {
        for (int j = 0; j < aList.get(i).pos - temp; j++) {
            count+=1;
            if (count % size == 0){
                System.out.println("");

            } else {
                System.out.print(0 + " ");
            }

        }
        System.out.print(aList.get(i).val + " ");
        temp = aList.get(i).pos;
    }

}

The problem is that I'm getting the following print back (The | sign represents a line break):

[0 0 35 0 0 99 0 | 0 0 0 0 0 0 | 0 0 0 0 0 0 55| 0 0 20 0 0 0 0 | 0 0 0 3 0 0 0 | 0 0 0 0 0 2 ]

As you can see the first line has 7 elements and I've found that with each line that a whole number is printed on, an extra 0 is added. This is shown on the second line where it has no whole numbers. Sorry for the essay but I've been on this all day!

Thanks for any replies!

OK theres a few problems with your code, I'm assuming your input is:

[2, 35] [3, 99] [17, 55] [19, 20] [26, 3] [34, 2]

Firstly you aren't incrementing the count when you add a non-zero number, and so that's why your getting extra zero's on lines with other numbers.

Then you need a few more checks for new lines (ie for the situations when you've added a non-zero number at either the start or the end of a row).

And after all this is done you need to add in any zeros remaining at the end of the matrix.

The following code should work for you:

public void printFullMatrix() {

    int count = 0;
    int temp = 0;
    int rows = 0;

    for (int i = 0; i < aList.size(); i++) {
        if (count % size == 0) {
            System.out.println("");
            rows++;
        }
        for (int j = 0; j < aList.get(i).pos - temp; j++) {
            count += 1;
            if (count % size == 0) {
                System.out.println("");
                rows++;
            } else {
                System.out.print(0 + " ");
            }

        }
        System.out.print(aList.get(i).val + " ");
        temp = aList.get(i).pos;
        count++;
        if (count % size == 0) {
            System.out.println("");
            rows++;
        }
    }

    while (rows < size) {
        count++;
        if (count % size == 0) {
            System.out.println("");
            rows++;
        } else {
            System.out.print(0 + " ");
        }
    }

}

I think you would be better off to sort your two-dimensional array (I've called them your pairs ), and then iterate through the length of your matrix. Since the pairs don't contain any information about matrix length, you'll need to pass that into your printFullMatrix as well.

One additional caveat: since you will never have two pairs with the same amount of zero indices (eg. {{5,3}, {5,4}} will never happen), then you only need to iterate at most one time through your pair list for every matrix entry.

Here is the way that I would do it:

import java.util.Arrays;
import java.util.Comparator;

public class q15413815 {

    public static void main(String[] args) {
        Integer[][] pairs = { { 6, 1 }, { 5, 23 } };
        printFullMatrix(pairs, 3);
    }

    public static void printFullMatrix(Integer[][] pairs, int length) {
        // Sort the pairs so we can simply iterate through them.
        Arrays.sort(pairs, new Comparator<Integer[]>() {

            @Override
            public int compare(Integer[] a1, Integer[] a2) {
                return a1[0] - a2[0];
            }

        });

        // Walk through the matrix and populate it with values.
        for (int i = 0; i < length * length; i++) {
            if (i % length == 0 && i != 0) {
                System.out.println();
            }

            int value = 0;
            for (int j = 0; j < pairs.length; j++) {
                if (pairs[j][0] == i) {
                    value = pairs[j][1];
                }
                if (pairs[j][0] > i) {
                    break;
                }
            }

            System.out.print(value + " ");
        }

    }
}

Something like this, I think...

    int[][] lll = new int[][] { {5, 23}, {6, 1}, {14, 6}};

    int count = 0;
    final int MATRIX_SIZE = 6;
    int index = 0;
    for (int pos = 0; pos < lll.length; pos++) {
        count = lll[pos][0];
        for (int i = 0; i < MATRIX_SIZE; i++) {
            index++;

            if (count == index - 1) {
                System.out.print(lll[pos][1] + " ");
            }
            else {
                System.out.print(0 + " ");
            }
        }
        System.out.print("|");
    }
}

I tried to figure out how to fix what you currently have, but since the for loops will not print out any 0's coming after the last object's value, I just started over with a while loop that will always print out every position in the matrix. This assumes that your list will always be sorted by position.

Using an input list of {[2,35], [4,99], [17,55], [19,20], [26,3], [34,2]}

int count = 0;
int currentObj = 0; // the object whose value is going to be printed
int numObjs = 6; // the number of objects to print
int size1 = 6; // number of rows
int size2 = 6; // number of positions in a row

// make sure you loop through every possible position
// the way you have it now stops after "2" is printed, leaving out the last "0"
while (count < size1 * size2) {
    count++; // increment the position every loop

    // if there are still objects to print out,
    // and if count is at the position of the current object
    //  pos of the objects is actually the number of positions before that value
    //  so pos is technically (position to print number - 1)
    if (currentObj < numObjs && (count - 1) == aList.get(currentObj).pos) {
        System.out.print(aList.get(currentObj).val + " ");
        currentObj++; // remember to increment to the next object

    // not at the position of an object's value, so print 0
    } else {
        System.out.print("0 ");
    }

    // go to the next line if size2 positions have been printed
    if (count % size2 == 0) {
        System.out.println("");
    }
}

Output:

0 0 35 0 99 0 
0 0 0 0 0 0 
0 0 0 0 0 55 
0 20 0 0 0 0 
0 0 3 0 0 0 
0 0 0 0 2 0 

I always feel the cleanest way to print a 2d structure is nested loops:

public void printFullMatrix() {
    int mi = 0; // matrix index
    int li = 0; // list index
    for (int row = 0; row < size; row++) {
        for (int col = 0; col < size; col++) {
            System.out.printf(" %3d", 
               (li < aList.size() && mi++ == aList.get(li).pos)
               ? aList.get(li++).val : 0);
        }
        System.out.println();
    }
}

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