Advertisement
Guest User

Untitled

a guest
Sep 19th, 2019
138
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.26 KB | None | 0 0
  1. import java.util.Arrays;
  2. import java.util.Scanner;
  3.  
  4.  
  5. public class RailFence {
  6.  
  7. public static void main(String[] args) {
  8. Scanner read=new Scanner(System.in);
  9.  
  10. String plainText=read.next();
  11. int key=read.nextInt();
  12.  
  13. char railFence[][]=new char[plainText.length()][key ];
  14. int currentCol = 0;
  15. boolean atBottom = false;
  16. /*
  17. * We maintain track of current column while traversing rows
  18. * and whether it has touched bottom column or not,
  19. * in case current column has touched bottom we have to decrement
  20. * current column else increment.
  21. *
  22. * Every time the current column is 0, atBottom is marked as false,
  23. * we will increment the column index. when it reaches Last Column
  24. * we will mark it true, then decrement the column index
  25. */
  26. for (int i = 0; i < plainText.length(); i++) {
  27. //update flag - either it has touched bottom or top
  28. if(currentCol == (key - 1))
  29. atBottom = true;
  30. else if(currentCol == 0)
  31. atBottom = false;
  32.  
  33. //update value
  34. railFence[i][currentCol] = plainText.charAt(i);
  35.  
  36. //update current column, in case it hasn't touched the
  37. //bottom then increment otherwise ( the currenCol has reached
  38. // bottom) decrement it.
  39. if(atBottom == false){
  40. currentCol ++;
  41. } else {
  42. currentCol --;
  43. }
  44. }
  45.  
  46. // Store the result
  47. StringBuilder result = new StringBuilder();
  48.  
  49. // simply pick up all the non-empty values, while traversing each row.
  50. // this would be the required CipherText
  51. for (int i = 0; i < key; i++) {
  52. for (int j = 0; j < plainText.length(); j++) {
  53. char res = railFence[j][i];
  54. if((int)res != 0){
  55. result.append(res);
  56. }
  57. }
  58. }
  59.  
  60. System.out.println(result.toString());
  61.  
  62.  
  63. // prints the RailFence
  64. for (int i = 0; i < plainText.length(); i++) {
  65. for (int j = 0; j < key; j++) {
  66. System.out.print(railFence[i][j] + " ");
  67. }
  68. System.out.println("");
  69. }
  70.  
  71. }
  72. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement