Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Linq;
- using Laba1.Interfaces;
- namespace Laba1.Algorithms
- {
- public class RailFence : IAlgorithm
- {
- public string Decrypt(string text, string key)
- {
- int rkey = Convert.ToInt32(key);
- char[,] charMatrix = new char[rkey, text.Length];
- bool dir_down = false;
- int row = 0, col = 0;
- for (int i = 0; i < text.Length; i++)
- {
- if (row == 0 || row == rkey - 1)
- dir_down = !dir_down;
- charMatrix[row, col++] = '*';
- if (dir_down)
- row++;
- else
- row--;
- }
- int ind = 0;
- for (int i = 0; i < rkey; i++)
- {
- for (int j = 0; j < text.Length; j++)
- {
- if (charMatrix[i, j] == '*')
- charMatrix[i, j] = text[ind++];
- }
- }
- string resultText = "";
- row = 0;
- col = 0;
- for (int i = 0; i < text.Length; i++)
- {
- if (row == 0)
- dir_down = true;
- if (row == rkey - 1)
- dir_down = false;
- resultText += charMatrix[row, col++];
- if (dir_down)
- row++;
- else
- row--;
- }
- return resultText;
- }
- public string Encrypt(string text, string key)
- {
- var rkey = Convert.ToInt32(key);
- var matrix = new char[rkey, text.Length];
- int k = 0;
- int j = 0;
- int buf = 0;
- string resultString = "";
- while (k < text.Length)
- {
- for (int i = 0; (i < rkey) && (j < text.Length); i++)
- {
- matrix[i, buf] = text[buf];
- buf = ++j;
- k++;
- }
- for (int i = rkey - 2; (i > 0) && (j < text.Length); i--)
- {
- matrix[i, buf] = text[buf];
- buf = ++j;
- k++;
- }
- }
- k = 0;
- while (k < text.Length)
- {
- for (int i = 0; i < rkey; i++)
- {
- for (int y = 0; y < text.Length; y++)
- {
- if (matrix[i, y] != '\0')
- resultString += matrix[i, y];
- k++;
- }
- }
- }
- return resultString;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement