Skip to content

Instantly share code, notes, and snippets.

@JohnMGant
Created November 17, 2020 21:47
Show Gist options
  • Select an option

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

Select an option

Save JohnMGant/39989f8627e48f439c18e1428275c751 to your computer and use it in GitHub Desktop.
internal class LinqHeadTailAdder : IIntegerAdder
{
private const int maxSupportedLength = 10000;
public int Add(int[] values)
{
if (values.Length > maxSupportedLength)
{
throw new NotSupportedException($"Max supported length is {maxSupportedLength}");
}
var (head, tail) = GetHeadAndTail(values);
return AddImplentation(head, tail);
}
private static int AddImplentation(int head, IEnumerable<int> tail)
{
if (!tail.Any())
{
return head;
}
var (nextHead, nextTail) = GetHeadAndTail(tail);
return AddImplentation(head + nextHead, nextTail);
}
private static (int head, IEnumerable<int> tail) GetHeadAndTail(IEnumerable<int> values)
=> (values.First(), values.Skip(1));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment