Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.ArrayList;
- /**
- Encodes strings using the Railfence cipher.
- */
- public class Railfence
- {
- /**
- Arranges a message in a fence pattern
- @param message any string
- @return a two-dimensional array of strings that are either null (.) or strings
- of length 1, arranged in a pattern like this
- m . . . a . .
- . e . s . g .
- . . s . . . e
- */
- public String[][] makeFence(String message)
- {
- String[][] fence = new String[3][message.length()];
- for(int i = 0; i < message.length(); i++)
- {
- if(i % 4 == 0)
- {
- fence[0][i] = Character.toString(message.charAt(i));
- fence[1][i] = null;
- fence[2][i] = null;
- }
- else if(i % 2 == 0)
- {
- fence[0][i] = null;
- fence[1][i] = null;
- fence[2][i] = Character.toString(message.charAt(i));
- }
- else
- {
- fence[0][i] = null;
- fence[1][i] = Character.toString(message.charAt(i));
- fence[2][i] = null;
- }
- }
- return fence;
- }
- // This message is used to check your work
- public String encode(String message)
- {
- String[][] fence = makeFence(message);
- String result = "";
- for (int i = 0; i < fence.length; i++)
- for (int j = 0; j < fence[i].length; j++)
- if (fence[i][j] != null && fence[i][j].length() == 1)
- result = result + fence[i][j];
- return result;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement