Skip to content

Instantly share code, notes, and snippets.

@aloisdg
Last active October 9, 2023 15:43
Show Gist options
  • Save aloisdg/fefd11636494637c56307367d690aa89 to your computer and use it in GitHub Desktop.
Save aloisdg/fefd11636494637c56307367d690aa89 to your computer and use it in GitHub Desktop.
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();
}
@aloisdg
Copy link
Author

aloisdg commented May 6, 2022

At the end this is more a way to show off three kind of loops...

@torendil
Copy link

torendil commented May 9, 2022

Still interesting ;) I believe it all comes down to the fact that a kata is a weird stuff designed to let you achieve something else that simply writing the answer :)

@aloisdg
Copy link
Author

aloisdg commented May 9, 2022

True. Smaller problem is easier to reason with

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment