Advertisement
advictoriam

Untitled

Jan 25th, 2019
84
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.61 KB | None | 0 0
  1. import java.util.ArrayList;
  2.  
  3. /**
  4.    Encodes strings using the Railfence cipher.
  5. */
  6. public class Railfence
  7. {
  8.     /**
  9.        Arranges a message in a fence pattern
  10.        @param message any string
  11.        @return a two-dimensional array of strings that are either null (.) or strings
  12.        of length 1, arranged in a pattern like this
  13.        m . . . a . .
  14.        . e . s . g .
  15.        . . s . . . e
  16.     */
  17.     public String[][] makeFence(String message)
  18.     {
  19.        String[][] fence = new String[3][message.length()];
  20.        
  21.        for(int i = 0; i < message.length(); i++)
  22.        {
  23.           if(i % 4 == 0)
  24.           {
  25.              fence[0][i] = Character.toString(message.charAt(i));
  26.              fence[1][i] = null;
  27.              fence[2][i] = null;
  28.           }
  29.          
  30.           else if(i % 2 == 0)
  31.           {
  32.             fence[0][i] = null;
  33.             fence[1][i] = null;
  34.             fence[2][i] = Character.toString(message.charAt(i));
  35.           }
  36.          
  37.           else
  38.           {
  39.             fence[0][i] = null;
  40.             fence[1][i] = Character.toString(message.charAt(i));
  41.             fence[2][i] = null;
  42.           }
  43.        }
  44.        return fence;
  45.     }
  46.    
  47.    
  48.     // This message is used to check your work
  49.     public String encode(String message)
  50.     {
  51.        String[][] fence = makeFence(message);
  52.        String result = "";
  53.        for (int i = 0; i < fence.length; i++)
  54.           for (int j = 0; j < fence[i].length; j++)
  55.              if (fence[i][j] != null && fence[i][j].length() == 1)
  56.                 result = result + fence[i][j];
  57.        return result;
  58.     }
  59. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement