Problem - I have a statement string so i have to print the longest string in the centre then second long in right of the centre then third on left and so on.
Approach - Split the string, sort string based on the size.
- Take 2d array rows will be the longest string size and columns will be the size of sorted list.
- Take one column parameter and set it to centre for first time so center = length/2 of list.
- Take 2 more for left move and right move.
- Now iterate the sorted list when i = 0 so it need to be set on centre so, column = centre, and increase left, right with 1.
- When i%2 = 0 means its even so it will go to left -> column = centre - left, left++.
- When i%2 != 0 so its odd so it will go to right -> column = centre+right, right++ and row will be the length of the word.
- Now will iterate the word in reverse order and set the char from last to start (bottom up), so column will be same and row--.
Exp abc ab a => a
b a
a c b
public class PrintZigZagString {
public static void main(String[] args) {
String str = "this statment is for testringg purpose onlly";
printString(str);
}
private static void printString(String str) {
String[] st = str.split(" ");
List<String> descendingSorted = Arrays.asList(st);
Collections.sort(descendingSorted, new java.util.Comparator<String>() {
public int compare(String s1, String s2) {
return s2.length() - s1.length();
}});
//System.out.println("String reversed \n"+descendingSorted);
char[][] prnt = new char[descendingSorted.get(0).length()][descendingSorted.size()];
for(char[] c:prnt){
Arrays.fill(c, ' ');
}
int center = descendingSorted.size()/2;
int left = 0;
int right = 0 ;
for(int i=0;i<descendingSorted.size();i++){
String tmp = descendingSorted.get(i);
int column = 0;
int row = descendingSorted.get(0).length()-1;
if(i == 0){
column = center;
left++;
right++;
}else if(i%2 == 1) {
column = center+right;
right++;
}else{
column = center - left;
left++;
}
for(int x = tmp.length()-1;x>=0;x--){
//System.out.println(row+" "+column);
prnt[row][column] = tmp.charAt(x);
row--;
}
}
for(char[] ch:prnt){
System.out.println(Arrays.toString(ch));
}
}
}
Output :
[ , , , t, , , ]
[ , , , e, s, , ]
[ , , p, s, t, , ]
[ , , u, t, a, , ]
[ , , r, r, t, o, ]
[ , t, p, i, m, n, ]
[ , h, o, n, e, l, f]
[i, i, s, g, n, l, o]
[s, s, e, g, t, y, r]