I am trying to do a simple coding challenge that requires me to do the following:
You are given n, return an array ans, composed in such way:
`ans = [n, n - 5, n - 10, ... , m, m + 5, ... , n - 5, n]`, where m stands for the first non-positive integer obtained by subtractions.
Try to solve it without any loop.
Example
For n = 25
, the output should be
listWithoutLoop(n) = [25, 20, 15, 10, 5, 0, 5, 10, 15, 20, 25].
I have done this code:
int[] listWithoutLoop(int n)
{
List<int> test = new List<int>();
if (test.Count > 2 && test[test.Count - 1] == n)
return test.ToArray();
if (n <= 0)
{
test.Add(n + 5);
return listWithoutLoop(n + 5);
}
else
{
test.Add(n - 5);
return listWithoutLoop(n - 5);
}
}
But I keep getting a stack overflow when running it. Is recursion supported by c#? If so, how to prevent getting a stackoverflow exception when running it?
test
in every recursive call sotest.Count > 2
is always false so you never reach the base case. – Lee Dec 14 '17 at 12:53List<int> test = new List<int>();
aboveint[] listWithoutLoop(int n)
? – mjwills Dec 14 '17 at 12:54