I'm trying to count how many times an byte occurs in my byte array to write it to an uint[] so my input is. an byte[] arrayToConvert = {97, 98, 99, 97, 98, 99, 97, 98, 100};
which writes abcabcabd.
And what I'm trying to achieve using an uint[]
is this:
97 = 3 times
98 = 3 times
99 = 2 times
100 = 1 time
So I'm trying to do this in my Class:
public static uint[] mCount(byte[] aCount)
{
for (int i = 0; i < aCount.Length; i++)
{
for (int j = i; j < aCount.Length; j++)
{
if (aCount[i] == aCount[j])
{
// somewhere around here I think I must create the uint[] to return.
// but for this I would need to know how many different bytes there are.
// not to forget I need to get my counter working to safe how many of which byte there are.
uint[] returncount = new uint[ !! number of different bytes !! ];
// foreach to fill the ^ array.
count = count + 1;
}
}
}
return returncount;
}
So at this point I'm completely stuck. So it would be nice if someone can push me in the right direction for this. Or tell me where I can read about this to learn it better. Because I cant really seem to find an explanation I understand.
Thanks in advance and happy coding!
First, you should notice that a byte ranges from 0 to 255.
I think one of the best approach would be to declare an int (type doesn't really matter much here) array of size 256 and initialize each element to 0.
Then, just iterate over each element in your input array using it as the index of the newly created array and incrementing its value. At the end, every element of the int array will contain the occurences of its index on the input.
For example:
var aCount = new[] {97, 98, 99, 97, 98, 99, 97, 98, 100};
var occurrences = new int[256];
for (int i = 0; i < aCount.Length; i++)
{
var byteElement = aCount[i];
occurrences[byteElement]++;
}
for (int i = 0; i < occurrences.Length; i++)
if (occurrences[i] != 0)
Console.WriteLine($"{i} = {occurrences[i]} times");