Garrett Openshaw had an okay answer to Codingbat maxMirror challenge
But there were a couple of issues with the code he gave, so I decided to review it and make it a little bit better.
I don't have access to Java here at work so I instead changed the code in C# which wasn't too much trouble.
I added a List<int[]>
to keep track of all the test cases and added an extra loop to the outside of the the rest of the code.
I moved some variables as I mentioned in my comment to Garret's answer, and also moved some variables to the correct scope. It seems like there should be more I can do to simplify this answer.
There was indentation and bracketing issues that made it difficult to read that I also changed.
List<int[]> sequences = new List<int[]> {
new int[] {1, 2, 1, 2, 1},
new int[] {1, 2, 3, 8, 9, 3, 2, 1},
new int[] {1, 2, 1, 4},
new int[] {7, 1, 2, 9, 7, 2, 1}
};
foreach (var sequence in sequences)
{
int maxLength = 1;
int endIndex = sequence.Length - 1;
for (int frontIndex = 0; frontIndex < endIndex; frontIndex++)
{
for (int i = endIndex; i > frontIndex; i--)
{
if (sequence[frontIndex] == sequence[i])
{
var currentLength = 0;
while (frontIndex + currentLength < sequence.Length && i - currentLength >= 0)
{
if (sequence[frontIndex + currentLength] == sequence[i - currentLength])
{
currentLength++;
}
else break;
}
if (currentLength > maxLength)
{
maxLength = currentLength;
}
}
}
}
Console.WriteLine("Max length is " + maxLength);
Console.ReadLine();
}