I came up with a recursive function that I think is clear:
private static byte[] JoinByteValues(byte[] message, byte valueToJoin, int start)
{
int joinIndex = Array.IndexOf<byte>(message, valueToJoin, start);
if (joinIndex > -1 && joinIndex < message.Length)
{
// copy to here, minus one byte
byte[] shorten = new byte[message.Length - 1];
// lets put the values back together at the index of joinIndex
message[joinIndex] = (byte)(message[joinIndex] + message[joinIndex + 1]);
// copy message to shorten, skipping the index [joinIndex + 1]
Array.Copy(message, 0, shorten, 0, joinIndex + 1);
Array.Copy(message, joinIndex + 2, shorten, joinIndex + 1, message.Length - joinIndex - 2);
// recall this method with the shorten copy, to find any more joinIndex values
return JoinBytesValue(shorten, valueToJoin, joinIndex + 1);
}
else
{
// no more bytes need joined
return message;
}
}
Today I also came up with this function without recursion, but I don't think it's any clearer:
private static void JoinByteValues(ref byte[] message, byte valueToJoin, int start)
{
int joinCount = 0;
for (int joinIndex = Array.IndexOf<byte>(message, valueToJoin, start);
joinIndex > -1 && joinIndex < message.Length;
joinIndex = Array.IndexOf<byte>(message, valueToJoin, start))
{
// add values back to together and store it at joinIndex
message[joinIndex] = (byte)(message[joinIndex] + message[joinIndex + 1]);
// start is the value we are 'dropping' out of the array
start = joinIndex + 1;
// move everything to the right of start left one index
Array.Copy(message, start + 1, message, start, message.Length - start - ++joinCount);
}
if (joinCount > 0)
{
// Drop the empty indexes do the the movement of data
Array.Resize<byte>(ref message, message.Length - joinCount);
}
}
So I'm curious as to which way you would rather see it? Both functions pass my tests. (Also, speed is not a concern, I am working with a small data set, never more than 90 bytes. I am only interested to know which you prefer readability wise.)

New Topic/Question
Reply


MultiQuote






|