In permutation ciphers, the order of the characters changes. In a simple permutation cipher, a permutation of numbers from 0 to n is selected as the key. For example, for n = 7, you can use a permutation of 3, 2, 5, 7, 4, 6, 1. Next, the text is written into n columns, which are then rearranged in accordance with the order specified by the permutation. Below is an example:

как вид

но, сов

Result:

даквки

вонс,о

That is, in the key 3, 2, 5, 7, 4, 6, 1 it is indicated in which place the letter will stand. The first letter "k", it corresponds to the number 3, etc.

Help, please implement.

 public string Encrypt(string msg, char[] key) { string result = string.Empty; string[] msgInArray = new string[(msg.Length / key.Length) + 1]; for (int i = 0; i < (msg.Length / key.Length) + 1; i++) { if (msg.Length <= key.Length) { msgInArray[i] = msg; break; } else { msgInArray[i] = msg.Substring(i * key.Length, key.Length); } } int[] a = new int[key.Length]; for (int i = 0; i < a.Length; i++) { a[i] = key[i]-48; } List<char> msgl = new List<char>(); for (int i = 0; i < msgInArray.Length; i++) { if (msgInArray[i] != null) { msgl = msgInArray[i].ToList<char>(); for (int j = 0; j < key.Length; j++) { result += msgl[a[j]]; } msgl.Clear(); } else { break; } } return result; } private void button1_Click(object sender, EventArgs e) { MessageBox.Show(Encrypt(textBox1.Text, textBox2.Text.ToCharArray())); } 

Gives an error message

Индекс и длина должны указывать на позицию в строке. Имя параметра: length

in line

 msgInArray[i] = msg.Substring(i * key.Length, key.Length); 
  • @ Elena1234, According to the rules of the forum, questions should not be reduced to the decision or the completion of student assignments. Please clarify what you have done yourself and what did not work out. - Nicolas Chabanovsky
  • > Index and length should indicate the position in the string for the hike msg.Substring (i * key.Length, key.Length); out of line, if the troc is not a multiple of key.Length - Specter

3 answers 3

The season "help make the laboratory work" is declared open.

I will show how to convert a single line, further on:

 var source = "как вид"; var shift = new int[]{3, 2, 5, 7, 4, 6, 1}; shift .Zip(source, (idx, ch)=>new {idx, ch}) .OrderBy(x=>x.idx) .Aggregate(string.Empty, (acc, el)=>acc+ el.ch ); // даквки 
  • I inserted my code - Elena1234
  • one
    Angry you, lambda students scare. )) - Olter

Look at the already existing code for the permutation encoder, so it will be easier to understand and understand: Classical Encryption Techniques (see Transposition / Permutation).

     msgInArray[i] = msg.Substring(i * key.Length, key.Length); 

    i * key.Length is the starting index

    key.Length is the length at which msg you take out a string