Skip to content

Instantly share code, notes, and snippets.

@JohnMGant
Created October 2, 2020 18:48
Show Gist options
  • Select an option

  • Save JohnMGant/bb1c2ec78483f5bc08667212a13634e6 to your computer and use it in GitHub Desktop.

Select an option

Save JohnMGant/bb1c2ec78483f5bc08667212a13634e6 to your computer and use it in GitHub Desktop.
Add an array of integers in C# using recursion and arrays
internal class ArrayHeadTailAdder : IIntegerAdder
{
//This will fail with large arrays
public int Add(int[] values)
{
var (head, tail) = GetHeadAndTail(values);
return AddImplentation(head, tail);
}
private static int AddImplentation(int head, int[] tail)
{
if (tail.Length == 0)
{
return head;
}
var (nextHead, nextTail) = GetHeadAndTail(tail);
return AddImplentation(head + nextHead, nextTail);
}
private static (int head, int[] tail) GetHeadAndTail(int[] values)
{
var head = values[0];
var tail = new int[values.Length - 1];
Array.Copy(values, 1, tail, 0, values.Length - 1);
return (head, tail);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment