Vikalp Patel
Vikalp Patel

Reputation: 10877

Box type pattern in java

I want to create a pattern something look likes a box.

I tried every reflection and mirror but unable to achieve the exact loop.

It's the box look like loop for String s="ROHIT";

enter image description here

Upvotes: 0

Views: 2486

Answers (3)

Joop Eggen
Joop Eggen

Reputation: 109547

int n = 2 * word.length();
for (int i = 0; i < n; ++i) {
    int iWord = i < word.length()? i : 2 * word.length() - 1 - i;
    for (int j = 0; j < n; ++j) {
        int jWord = j < word.length()? j : 2 * word.length() - 1 - j;
        int diagonal = Math.min(iWord, jWord);
        System.out.print(word.charAt(diagonal));
    }
    System.out.println();
}

Upvotes: 3

assylias
assylias

Reputation: 328598

This does what you asked for (the idea is to check on wich inside level you are):

public static void main(String[] args) {
    String s = "ROHIT";
    int size = s.length() * 2;
    for (int i = 0; i < size; i++) {
        for (int j = 0; j < size; j++) {
            if ((j > i && size - j > i) || (size - j > size - i && j >= size - i)) {
                print(s, i);
            } else {
                print(s, j);
            }
        }
        System.out.println("");
    }
}

private static void print(String s, int i) {
    if (i < s.length()) {
        System.out.print(s.charAt(i));
    } else {
        System.out.print(s.charAt(s.length() - i % s.length() - 1));
    }
}

Actually, this is more intuitive:

public static void main(String[] args) {
    String s = "ROHIT";
    int size = s.length() * 2;
    int max = s.length();
    for (int i = 0; i < size; i++) {
        for (int j = 0; j < size; j++) {
            int level = Math.min(normalize(i, max), normalize(j, max));
            System.out.print(s.charAt(level));
        }
        System.out.println("");
    }
}

private static int normalize(int i, int max) {
    return (i >= max) ? 2 * max - i - 1: i;
}

Upvotes: 3

TheWhiteRabbit
TheWhiteRabbit

Reputation: 15758

This is the algortithm /pseuodo code

for(each row)
{
 if(firstrow) print total row;

else if(lastrow) print total row;
else {
  for (each column)
{
 if(firstcol) print col;
 if(lastcol) print col;
}
}
}

Upvotes: 1

Related Questions