Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
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