Last active
December 13, 2020 02:20
-
-
Save cameronpresley/1a51ad36d9ca825176da9dec89957456 to your computer and use it in GitHub Desktop.
C# Advent 2020
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
// Generate numbers from -10 .. 100 | |
var numbers = Enumerable.Range(-10, 111); | |
// Determines all positive numbers that are divisible by 6 | |
var positiveDivisbleBySix = numbers | |
.Where(x=>x > 0) // iterates through the whole list (111 comparisons, returning 100 results) | |
.Where(x=>x % 2 == 0) // iterates through the new list (100 comparisons, returning 50 results) | |
.Where(x=>x % 3 == 0); // iterates through the new list (50 comparisons, returning 16 results) | |
// Overall metrics: 261 comparisons over 111 total elements) | |
// Generate numbers from -10 .. 100 | |
var numbers = Enumerable.Range(-10, 111); | |
var positiveDivisibleBySix = numbers.Where(x => x > 0 && x % 2 == 0 && x % 3 == 0); | |
Func<T, bool> CombinePredicateWithAnd<T>(Func<T, bool> a, Func<T, bool> b) | |
{ | |
return x => a(x) && b(x); | |
} | |
Func<int, bool> isPositive = x => x > 0; | |
Func<int, bool> isEven = x => x % 2 == 0; | |
Func<int, bool> isDivisibleByThree = x => x % 3 == 0; | |
var predicates = new List<Func<int, bool>> {isPositive, isEven, isDivisibleByThree}; | |
var combinedPredicate = predicates.Aggregate(...., ....); | |
Func<int, bool> combinedPredicateWithAnd(Func<int, bool> a, Func<int, bool> b) | |
{ | |
return x => ...; | |
} | |
Func<int, bool> combinedPredicateWithAnd(Func<int, bool> a, Func<int, bool> b) | |
{ | |
return x => ... && ...; | |
} | |
Func<int, bool> combinedPredicateWithAnd(Func<int, bool> a, Func<int, bool> b) | |
{ | |
return x => a(x) && b(x); | |
} | |
Func<int, bool> andIdentity = _ => true; | |
var combinedPredicate = predicates.Aggregate(andIdentity, CombinePredicateWithAnd); | |
// Define the predicates | |
Func<int, bool> isPositive = x => x > 0; | |
Func<int, bool> isEven = x => x % 2 == 0; | |
Func<int, bool> isDivisibleByThree = x => x % 3 == 0; | |
var predicates = new List<Func<int, bool>> {isPositive, isEven, isDivisibleByThree}; | |
// Defining the Aggregate functions | |
Func<int, bool> andIdentity = _ => true; | |
Func<int, bool> combinedPredicateWithAnd(Func<int, bool> a, Func<int, bool> b) | |
{ | |
return x => a(x) && b(x); | |
} | |
// Combining the predicates | |
Func<int, bool> combinedAndPredicate = predicates.Aggregate(andIdentity, combinedPredicateWithAnd); | |
// The new solution | |
// Generate numbers from -10 .. 100 | |
var numbers = Enumerable.Range(-10, 111); | |
var positiveDivisbleBySix = numbers.Where(combinedAndPredicate); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment