My function returns an int array with 2 values Let's say, res[0] and res[1]
When I'm calling the array in a for loop for multiple times, and when I'm storing the results in another array, in each iteration the results are over-written with the new results.
If the first call returns [0,1] the array will store [0,1] at index [0] and [1], which is fine, but when I'm calling the function again, the new results are stored at the same indexes [0] and [1] How can I avoid that?
The code is:
class Hill_Cipher
{
string AtoZ="ABCDEFGHIJKLMNOPQRSTUVWXYZ";
public string Hill_Cipher_Enc(string input, int[,] key)
{
int[] encChars = new int[input.Length];
string res = "";
input = input.ToUpper();
input = input.Replace(" ", String.Empty);
StringBuilder sb = new StringBuilder(input);
while (sb.Length % key.GetLength(0) != 0)
{
sb = sb.Append('X');
}
input = sb.ToString();
IEnumerable<string> chunks = Enumerable.Range(0, input.Length / key.GetLength(0))
.Select(x => input.Substring(x * key.GetLength(0), key.GetLength(0)));
string[] outPut = chunks.ToArray();
for (int i = 0; i < outPut.Length; i++)
{
if (i == 0)
{
MatrixMul(outPut[i], key, encChars);
}
else
MatrixMul(outPut[i], key,encChars);
}
for (int i = 0; i < encChars.Length; i++)
{
encChars[i] = encChars[i] % 26;
}
return res;
}
private void MatrixMul(string subInput, int[,] key, int [] result)
{
for (int row = 0; row < key.GetLength(0); row++)
{
for (int col = 0; col < key.GetLength(0); col++)
{
result[row]+= key[row, col] * AtoZ.IndexOf(subInput[col]);
}
}
}
}
For example, my outPut contains the following: "TH","IS","AT" when I'm calling the function with the first element of array "TH", it converts "T" to its equivalent number and apply some calculations and same with "H". Let's say the final answer is 20 for "T" and 30 for "H". The problem is that every time, encChars will store the values at index 0 and 1: encChars[0]=20 encChars[1]=30 When I call the function again it will store the new values at 0 and 1.... That's because I'm not changing the index value for encChars on each call, so how do I do that?