Sha256: 9b8711eb9c134445a5deecb553d2540ee96ed46a52f66992f738634f38f6fcb3

Contents?: true

Size: 1.23 KB

Versions: 396

Compression:

Stored size: 1.23 KB

Contents

using System;
using System.Collections.Generic;
using System.Linq;

public static class Dominoes
{
    public static bool CanChain(IEnumerable<Tuple<int, int>> dominoes)
    {
        if (!dominoes.Any())
        {
            return true;
        }

        var domino = dominoes.First();

        if (dominoes.Count() == 1)
        {
            return domino.Item1 == domino.Item2;
        }

        return dominoes.Skip(1).Rotate().Any(sublist => PossibleChains(domino, sublist).Any(CanChain));
    }

    public static IEnumerable<Tuple<int, int>[]> PossibleChains(Tuple<int, int> domino, IEnumerable<Tuple<int, int>> remainder)
    {
        var head = remainder.First();

        if (domino.Item2 == head.Item1)
        {
            yield return new[] { Tuple.Create(domino.Item1, head.Item2) }.Concat(remainder.Skip(1)).ToArray();
        }
        else if (domino.Item2 == head.Item2)
        {
            yield return new[] { Tuple.Create(domino.Item1, head.Item1) }.Concat(remainder.Skip(1)).ToArray();
        }
    }

    private static IEnumerable<IEnumerable<T>> Rotate<T>(this IEnumerable<T> input)
    {
        return Enumerable.Range(0, input.Count()).Select(i => input.Skip(i).Take(input.Count() - i).Concat(input.Take(i)));
    }
}

Version data entries

396 entries across 396 versions & 1 rubygems

Version Path
trackler-2.2.1.180 tracks/csharp/exercises/dominoes/Example.cs
trackler-2.2.1.179 tracks/csharp/exercises/dominoes/Example.cs
trackler-2.2.1.178 tracks/csharp/exercises/dominoes/Example.cs
trackler-2.2.1.177 tracks/csharp/exercises/dominoes/Example.cs
trackler-2.2.1.176 tracks/csharp/exercises/dominoes/Example.cs
trackler-2.2.1.175 tracks/csharp/exercises/dominoes/Example.cs
trackler-2.2.1.174 tracks/csharp/exercises/dominoes/Example.cs
trackler-2.2.1.173 tracks/csharp/exercises/dominoes/Example.cs
trackler-2.2.1.172 tracks/csharp/exercises/dominoes/Example.cs
trackler-2.2.1.171 tracks/csharp/exercises/dominoes/Example.cs
trackler-2.2.1.170 tracks/csharp/exercises/dominoes/Example.cs
trackler-2.2.1.169 tracks/csharp/exercises/dominoes/Example.cs
trackler-2.2.1.167 tracks/csharp/exercises/dominoes/Example.cs
trackler-2.2.1.166 tracks/csharp/exercises/dominoes/Example.cs
trackler-2.2.1.165 tracks/csharp/exercises/dominoes/Example.cs
trackler-2.2.1.164 tracks/csharp/exercises/dominoes/Example.cs
trackler-2.2.1.163 tracks/csharp/exercises/dominoes/Example.cs
trackler-2.2.1.162 tracks/csharp/exercises/dominoes/Example.cs
trackler-2.2.1.161 tracks/csharp/exercises/dominoes/Example.cs
trackler-2.2.1.160 tracks/csharp/exercises/dominoes/Example.cs