I am trying to write a program to identify the occurrences of 3 consecutive integers in a given array of N numbers and replace them with the middle value by deleting the other two.
For example Input->55 99 99 100 101 101 34 35 36 5 28 7 50 50 51 52 52 24 13 14 15 5 6 7 37 31 37 38 39 36 40
Output->55 100 35 5 28 7 51 24 14 6 37 31 38 36 40
To achieve this i wrote this method which accepts array as an input and it returns the modified array.
//input
int[] original = new int[] { 1, 3, 4, 5, 5, 6, 8} ;
List<int> lstoriginal = new List<int>(original);
List<int> modified = Test(lstoriginal);
//method
public static List<int> Test(List<int> arrayInput)
{
for (i = 0; i < arrayInput.Count; i++)
{
if (i + 2 < arrayInput.Count)
{
if (arrayInput[i + 2] == arrayInput[i + 1] + 1
&& arrayInput[i + 2] == arrayInput[i] + 2)
{
arrayInput.RemoveAt(i + 2);
arrayInput.RemoveAt(i);
List<int> temp = arrayInput;
Test(temp);
}
}
}
return arrayInput;
}
Follwoing are the execution steps/result which i analyzed-
1-Initially if the test input is 1, 3, 4, 5, 5, 6, 8
2-When i=1 and it finds that 3,4,5 is in sequence it removes 3 and 5 and list becomes 1,4,5,6,8
3-Next time when i=1 then it finds 4,5,6 and it removes 4 and 6 and the new list is 1,5,8
4-i am expecting to exit from loop when i + 2 < arrayInput.Count returns false and trying to retrun the modified array immediately here the return statement gets executed but instead of return the result it again calls the Test(temp); statement few more times and then get exit. Please suggest
You actually don’t need recursion at all. You can perform the task significantly faster by just moving
iafter you’re removed your sequence. Here’s a function that is much simpler and does the exact same thing. I tested it on tens of thousands of randomly generated unordered sequences.That said, to answer your specific question, the best way to exit a recursive loop like your original is to change the signature of your recursive function to return a
boolindicating whether or not it actually made any changes. When the first one returns with no changes, they all can exist, so your call toTestcan be wrapped inif (!Test(...)) { return; }.Here’s the complete test and test data comparing your original to my modified version: