Answer the question
In order to leave comments, you need to log in
Why is the array out of bounds?
It turns out an extremely strange thing, why does an exception come out if it should not exist? wrote for clarity that it works, but at the same time it throws an exception
Here is the local data at the time the exception was thrown, that is, the array with which I work, as you can see, has a dimension much larger than at the first iteration
The essence of this loop is to swap the letters in the word according to the numbers written inj + 2
j + 1
j + 1
j = 0
key List
class Generator
{
public static string Text { get; set; } = "Hello how are you";
static List<int> GenerationKey()
{
var words = Text.Split(' ');
var key = new List<int>();
int counter = 0;
// Запись ключа
for (int i = 0; i < words.Length; i++)
{
for (int j = 0; j < words[i].Length; j++)
{
key.Add(++counter);
}
counter = 0;
}
// Перемешивание ключа
var rand = new Random();
int step = 0;
for (int i = 0; i < words.Length; i++)
{
for (int j = 0; j < words[i].Length; j++)
{
int a = rand.Next(step, words[i].Length + step);
int b = rand.Next(step, words[i].Length + step);
int temp = key[a];
key[a] = key[b];
key[b] = temp;
}
step += words[i].Length;
}
return key;
}
public static void EncryptionText()
{
var key = GenerationKey();
var words = Text.Split(' ');
char[] letters;
for (int i = 0; i < words.Length - 1; i++)
{
letters = words[i].ToCharArray();
for (int j = 0; j < letters.Length; j++)
{
var temp = letters[key[j]];
letters[key[j]] = letters[key[j + 1]];
letters[key[j + 1]] = temp;
}
}
}
}
Answer the question
In order to leave comments, you need to log in
Because you are accessing the element at index j = j + 2
When j is equal to the number of elements minus one, then the array is overflown.
Well, or on the last line, where you do the same, but + 1.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question