Skip to content

Instantly share code, notes, and snippets.

@leosabbir
Last active April 10, 2019 21:53
Show Gist options
  • Save leosabbir/d410df80cd0ca3b6a53d697715ff3b44 to your computer and use it in GitHub Desktop.
Save leosabbir/d410df80cd0ca3b6a53d697715ff3b44 to your computer and use it in GitHub Desktop.
program to print in zig zag fashion
import java.util.Scanner;
public class ZigZag {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String input = "I am Lord Voldemort. Lord Voldemort is my past, my present and my future!!!"; //sc.next();
System.out.print("Enter value of K: ");
int K = sc.nextInt();
System.out.println();
for (int i = 0; i < K; i++) {
StringBuilder sb = new StringBuilder();
sb.append(new String(new char[i]).replace('\0', ' ')); // logic may be changed to create string of spaces
int index = i;
boolean up = i == K - 1; // for all lines except last, we start by moving down
while(index < input.length()) {
sb.append(input.charAt(index)); // append char
int gapSize; // compute and append spaces
if (up) {
gapSize = 2 * i - 1;
} else {
int j = K - i - 1;
gapSize = 2 * j - 1;
}
sb.append(new String(new char[gapSize]).replace('\0', ' ')); // logic may be changed to create string of spaces
index += gapSize + 1; // index of next char for current line
// set direction for next character
if (i == 0) { // for top line always consider we are moving down
up = false;
} else if (i == K - 1) { // for last line always consider we are moving up
up = true;
} else { // for middle lines we alaternatively move down and up
up = !up;
}
}
System.out.println(sb.toString());
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment