Created
October 2, 2020 18:48
-
-
Save JohnMGant/bb1c2ec78483f5bc08667212a13634e6 to your computer and use it in GitHub Desktop.
Add an array of integers in C# using recursion and arrays
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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