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?
To simplify, I splitted the function to add up and add down separately (it's always better to have simple and understandable code at all times)
static void Main()
{
int n = 20;
int interval = 5;
List<int> list = new List<int>();
AddDown(list, n, 0, interval);
AddUp(list, 0, n, interval);
int[] arrInt = list.ToArray();
}
static void AddDown(List<int> list, int currentNumber, int targetNumber, int interval)
{
if(currentNumber > targetNumber)
{
list.Add(currentNumber);
AddDown(list, currentNumber - interval, targetNumber, interval);
}
}
static void AddUp(List<int> list, int currentNumber, int targetNumber, int interval)
{
if (currentNumber <= targetNumber)
{
list.Add(currentNumber);
AddUp(list, currentNumber + interval, targetNumber, interval);
}
}