简体   繁体   中英

“Stretching” a 2D Array in Java

I need to "stretch" a 2D Array filled with chars of ' ', and '*'. The stretching is based on a "Int Factor" passed in through the method.

Current Image looks like this:

*****  
*      
*    * 
***    
*   *  
*     *
***** 

Need it to look like this: (Assuming its Factor 2)

**********  
**      
**    ** 
******    
**   **  
**     **
********** 

I started to write the loop for it but I have no idea if I'm on the right track or not, really struggling with this one.

EDIT: I've gotten the array col length to stretch, I need to get the image to stretch with it now.

 public void stretch ( int factor )
 {

factor = 2;
char[][] pixelStretch = new char[pixels.length][pixels[0].length * factor];
for (int row = 0; row < pixels.length; row++)
{
    for (int col = 0; col < pixels[0].length; col+= factor) {

        for(int i=0; i<factor; i++) {
            pixelStretch[row][col+i] = pixels[row][col];
        }

}
}

pixels = pixelStretch;



}

Image printed from this:

**** 

   **
** 


****

Ok, some problems with your loop:

for (int col = 0; col < pixels[0].length * factor; col--)

Here, you should use pixels[row].length to get the correction column. Furthermore, it should be col++ instead of col--

If you only need to print the result, you don't actually need to stretch the array.

public void stretch ( int factor )
    {
    for (int row = 0; row < pixels.length; row++)
    {
        for (int col = 0; col < pixels[row].length; col++) {
            char c = pixels[row][col];
            if (c == ' ')
                System.out.print(c);
            else
                for (int count = 0; count < factor; count++)
                    System.out.print(c);
        }
        System.out.println();
    }
}

This prints the star/asterisk 'factor' times, and the spaces only as often as they occur in the original.

You're almost there. All you have to do, is change the code so that you're copying pixels[row][column] to the new array factor times

// make sure factor is not 0 before you do this
for (int col = 0; col < pixels[0].length; col++) {
   for(int i=0; i<factor; i++) {
       pixelStretch[row][col*factor+i] = pixels[row][col];
   }
}

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