using System; using System.Text; namespace AniNIX.Crypto { public class CharGrid { protected char[][] theGrid; /// ///Use this to even out grids so that columnar transpositions can be regular. /// ///The String to pad ///How wide the grid should be ///A paddded string public static String RandPad(String input, int width) { Random sRand = new Random(); int mod = input.Length%width; if (mod == 0) return input; char[] pad = new char[width-mod]; for (int i=0; i /// Create a grid from the input and row length /// /// The string to make the grid from /// The width of a row /// a grid private char[][] MakeGrid(String input, int width) { int k=0; int y=(input.Length%width == 0) ? input.Length/width : input.Length/width+1; int remainingLength=input.Length; char[][] newGrid = new char[y][]; for (int i=0; i < y; i++) { newGrid[i] = new char[(remainingLength > width) ? width : remainingLength]; remainingLength -= width; for (int j=0; j < newGrid[i].Length; j++) { newGrid[i][j] = input[k++]; } } return newGrid; } /// /// Create a grid from a width and length /// /// The length of a column /// The width of a row /// a grid private char[][] MakeVGrid(int length, int width) { int y = (length%width == 0) ? length/width : length/width+1; char[][] newGrid = new char[y][]; for (int i = 0; i < y; i++) { newGrid[i] = new char[(length > width) ? width : length]; length -= width; } return newGrid; } /// /// Make a horizontal grid from the input of certain width. Make regular if wanted. /// /// String to make from /// How wide a grid to make /// Should random padding be added to make this not a jagged array public CharGrid(String input,int width,bool isRegular=false) { if (isRegular) input = RandPad(input,width); theGrid = MakeGrid(input,width); } /// /// Make a vertical grid from the input of certain width. Make regular if wanted. /// /// String to make from /// How wide a grid to make /// What order should the columns be populated in? public CharGrid(String input,int width,int[] order) { // Make a grid first. theGrid = MakeVGrid(input.Length,width); //Populate int k = 0; for (int j = 0; j < theGrid[0].Length; j++) { for (int i = 0; i < theGrid.Length; i++) { if (i != theGrid.Length-1 || order[j] < theGrid[i].Length) { theGrid[i][order[j]] = input[k]; k++; } } } } /// /// Create a string representation /// /// representation public override String ToString() { StringBuilder sb = new StringBuilder(); // Include a line to indicate height vs. width sb.Append(String.Format("{0} {1} ------------->\n",theGrid.Length,theGrid[0].Length)); // Iterate through the arrays for (int j=0; j /// Return the array for manipulation /// /// the array public char[][] ToArray() { return theGrid; } // This is leftover in case you want to debug chargrid /*public static void Main(String[] args) { CharGrid cg = new CharGrid("helloiamanewcipher",5); Console.Write(cg.ToString()); cg = new CharGrid("four",5,false); Console.Write(cg.ToString()); return; }*/ } }