Last active
October 9, 2023 15:43
-
-
Save aloisdg/fefd11636494637c56307367d690aa89 to your computer and use it in GitHub Desktop.
Try it online: https://dotnetfiddle.net/Q32WcF
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
using System; | |
using System.Linq; | |
using System.Collections.Generic; | |
public class Program | |
{ | |
// https://bowlingguidance.com/all-about-strikes-and-spares-in-bowling/ | |
static int Score(IList<int> pins) | |
{ | |
bool startsWithStrike(IList<int> list) => list[0] == 10; | |
bool startsWithSpare(IList<int> list) => list[0] + list[1] == 10; | |
int Loop(int accumulator, int turn, IList<int> list) | |
{ | |
//Console.WriteLine($"{turn}: {accumulator}"); | |
if (turn == 0) | |
{ | |
return accumulator; | |
} | |
if (startsWithStrike(list)) | |
{ | |
return Loop(10 + list[1] + list[2] + accumulator, turn - 1, list.SkipList(1)); | |
} | |
if (startsWithSpare(list)) | |
{ | |
return Loop(10 + list[2] + accumulator, turn - 1, list.SkipList(2)); | |
} | |
return Loop(list[0] + list[1] + accumulator, turn - 1, list.SkipList(2)); | |
} | |
return Loop(0, 10, pins); | |
} | |
public static void Main() | |
{ | |
var zeros = Enumerable.Repeat(0, 20).ToList(); | |
Console.WriteLine(Score(zeros) == 0); | |
var zerosAndOne = Enumerable.Repeat(0, 19).Prepend(1).ToList(); | |
Console.WriteLine(Score(zerosAndOne) == 1); | |
var zerosAndStrike = Enumerable.Repeat(0, 19).Prepend(10).ToList(); | |
Console.WriteLine(Score(zerosAndStrike) == 10); | |
var strikes = Enumerable.Repeat(10, 12).ToList(); | |
Console.WriteLine(Score(strikes) == 300); | |
var zerosAndSpare = Enumerable.Repeat(0, 18).Prepend(9).Prepend(1).ToList(); | |
Console.WriteLine(Score(zerosAndSpare) == 10); | |
var spares = Enumerable.Repeat(new []{9, 1}, 10).SelectMany(x => x).Append(9).ToList(); | |
Console.WriteLine(Score(spares) == 190); | |
} | |
} | |
public static class Extensions | |
{ | |
public static IList<T> SkipList<T>(this IList<T> list, int n) => list.Skip(n).ToList(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
True. Smaller problem is easier to reason with