Created
July 28, 2016 19:34
-
-
Save khyperia/f34c17e69948319426feb0623336d1f0 to your computer and use it in GitHub Desktop.
Any and All Puzzle Solution (over-complicated mode)
This file contains 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.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