Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.Arrays;
- import java.util.Scanner;
- public class RailFence {
- public static void main(String[] args) {
- Scanner read=new Scanner(System.in);
- String plainText=read.next();
- int key=read.nextInt();
- char railFence[][]=new char[plainText.length()][key ];
- int currentCol = 0;
- boolean atBottom = false;
- /*
- * We maintain track of current column while traversing rows
- * and whether it has touched bottom column or not,
- * in case current column has touched bottom we have to decrement
- * current column else increment.
- *
- * Every time the current column is 0, atBottom is marked as false,
- * we will increment the column index. when it reaches Last Column
- * we will mark it true, then decrement the column index
- */
- for (int i = 0; i < plainText.length(); i++) {
- //update flag - either it has touched bottom or top
- if(currentCol == (key - 1))
- atBottom = true;
- else if(currentCol == 0)
- atBottom = false;
- //update value
- railFence[i][currentCol] = plainText.charAt(i);
- //update current column, in case it hasn't touched the
- //bottom then increment otherwise ( the currenCol has reached
- // bottom) decrement it.
- if(atBottom == false){
- currentCol ++;
- } else {
- currentCol --;
- }
- }
- // Store the result
- StringBuilder result = new StringBuilder();
- // simply pick up all the non-empty values, while traversing each row.
- // this would be the required CipherText
- for (int i = 0; i < key; i++) {
- for (int j = 0; j < plainText.length(); j++) {
- char res = railFence[j][i];
- if((int)res != 0){
- result.append(res);
- }
- }
- }
- System.out.println(result.toString());
- // prints the RailFence
- for (int i = 0; i < plainText.length(); i++) {
- for (int j = 0; j < key; j++) {
- System.out.print(railFence[i][j] + " ");
- }
- System.out.println("");
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement