Printing string in rows and column pattern Java

you could try to make the spiral algorithm first and try to find the value of its each index in the matrix so that later you could map every index of your string into the specific index in the spiral array matrix.

for example:

Input: n = 5
Output:   1   2   3   4   5
          16  17  18  19  6
          15  24  25  20  7
          14  23  22  21  8
          13  12  11  10  9
Aligned Output:  1 2 3 4 5 16 17 18 19 6 15 24 25 20 7 14 23 22 21 8 13 12 11 10 9

the algorithm can be found here or here.

now you know all the index of each position to make the letters aligned in a spiral way, what you have to do is map each letter of your string to be print according to the number of the spiral matrix sequentially.

print string 1.
print string 2.
print string 3.   
print string 4.
print string 5.
print string 16.
print string 17.
print string 18.
print string 19.
print string 6.
print string 15.
cont...

Basically, you move through the string from start to end, but treat the stringbuffer as an array. You#ll also need to to keep track of your direction (dx,dy) and where your bounds are.

The following code will produce:

hello
beau 
 l.tw
sufio
i dlr

given the input "hello world is beautiful"

public class Main {

    public static void main(String[] args) {
        String text ="hello world is beautiful";
        int len = text.length();
        double sideLength = Math.sqrt( len );
        int width = 0;
        int height = 0;

        // check if it's a square
        if ( sideLength > (int) sideLength) {
            // nope... it#s a rectangle
            width = (int) sideLength +1;
            height = (int) Math.ceil((double)len / (double)width);
        } else {
            // square
            width = (int) sideLength;
            height = (int) sideLength;
        }

        // create a buffer for the spiral
        StringBuffer buf = new StringBuffer( width * height );
        buf.setLength( width * height );
        // clear it.
        for (int a=0; a < buf.length(); a++ ) {
            buf.setCharAt(a, '.');
        }
        

        int dstX = 0;
        int dstY = 0;
        int curWidth =  width;
        int curHeight = height;
        int startX = 0;
        int startY = 0;
        int dx = 1;
        int dy = 0;
        // go through the string, char by char
        for (int srcPos =0; srcPos < len; srcPos++) {
            buf.setCharAt( dstX + dstY * width, text.charAt( srcPos ));

            // move cursor
            dstX += dx;
            dstY += dy;

            // check for bounds
            if ( dstX == curWidth-1 && dx > 0) {
                // end of line while going right, need to go down
                dx = 0;
                dy = 1;
                // also, reduce width
                curWidth--;
                startY++;
            } else if (dstY == curHeight-1 && dy > 0) {
                // end of column while going down, need to go left
                dx = -1;
                dy = 0;

                // also, reduce height
                curHeight--;
            } else if (dstX == startX && dx < 0) {
                // hit left border while going left, need to go up
                dx = 0;
                dy = -1;
                // also, increase startX
                startX++;
            } else if (dstY == startY && dy < 0) {
                // hit top border, while going up, need to go right
                dx = 1;
                dy = 0;
                // also, increase startY
                startY++;
            }
            
        }


        // display string
        for (int line = 0; line < height; line++) {
            System.out.println( buf.substring( line* width, line*width +width) );
        }
    }
}


spiralMatrix(int s) returns s x s spiral matrix.

static int[][] spiralMatrix(int s) {
    int[][] a = new int[s][s];
    int n = 0;
    for (int b = s - 1, c = 0, x = 0, y = 0, dx = 0, dy = 1; b > 0; b -= 2, x = y = ++c)
        for (int j = 0, t = 0; j < 4; ++j, t = dx, dx = dy, dy = -t)
            for (int i = 0; i < b; ++i, x += dx, y += dy, ++n)
                a[x][y] = n;
    if (s % 2 == 1)
        a[s / 2][s / 2] = n;
    return a;
}

test

for (int s = 0; s < 6; ++s) {
    int[][] a = spiralMatrix(s);
    System.out.println("s=" + s);
    for (int[] row : a)
        System.out.println(Arrays.toString(row));
    System.out.println();
}

result

s=0

s=1
[0]

s=2
[0, 1]
[3, 2]

s=3
[0, 1, 2]
[7, 8, 3]
[6, 5, 4]

s=4
[0, 1, 2, 3]
[11, 12, 13, 4]
[10, 15, 14, 5]
[9, 8, 7, 6]

s=5
[0, 1, 2, 3, 4]
[15, 16, 17, 18, 5]
[14, 23, 24, 19, 6]
[13, 22, 21, 20, 7]
[12, 11, 10, 9, 8]

And you can do it with this method.

String str = "hello world its beautiful";
int[][] spiral = spiralMatrix(5);
int length = str.length();
for (int x = 0, h = spiral.length, w = spiral[0].length; x < h; ++x) {
    for (int y = 0; y < w; ++y) {
        int p = spiral[x][y];
        System.out.print((p < length ? str.charAt(p) : " ") + " " );
    }
    System.out.println();
}

result

h e l l o 
  b e a   
s u l u w 
t f i t o 
i   d l r 

Tags:

Java