Skip to content

Instantly share code, notes, and snippets.

@khyperia
Created July 28, 2016 19:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save khyperia/f34c17e69948319426feb0623336d1f0 to your computer and use it in GitHub Desktop.
Save khyperia/f34c17e69948319426feb0623336d1f0 to your computer and use it in GitHub Desktop.
Any and All Puzzle Solution (over-complicated mode)
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using static System.Console;
namespace AnyAndAll
{
public class Program
{
public static void Main(string[] args)
{
var sequence = GetSpecialSequence();
// Prints "True"
WriteLine(sequence.All(b => b == true));
// Prints "False"
WriteLine(sequence.Any(b => b == true));
ShowBehavior();
}
private static IEnumerable<bool> GetSpecialSequence()
{
// because implementing this with `yield break;` is boring.
return new TrueBreakFalseBreak();
}
private class TrueBreakFalseBreak : IEnumerable<bool>, IEnumerator<bool>
{
private int state = 0;
public bool Current => state % 4 < 2;
public bool MoveNext() => state++ % 2 == 0;
public IEnumerator<bool> GetEnumerator() => this;
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
object IEnumerator.Current => Current;
public void Reset() { }
public void Dispose() { }
}
private static void ShowBehavior()
{
// Note that the solution relies on that the original
// test code re-uses the same `sequence` variable.
// .Any and .All call .Dispose, but we ignore it.
var sequence = new TrueBreakFalseBreak().GetEnumerator();
for (int i = 0; i < 16; i++)
{
WriteLine($"MoveNext: {sequence.MoveNext()}");
WriteLine($"Current: {sequence.Current}");
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment