public static T FirstOrDefault <T>(this IExtremaEnumerable <T> source) { if (source == null) { throw new ArgumentNullException(nameof(source)); } return(source.Take(1).AsEnumerable().FirstOrDefault()); }
/// <summary> /// Returns the only element of a sequence, and throws an exception if /// there is not exactly one element in the sequence. /// </summary> /// <typeparam name="T"> /// The type of the elements of <paramref name="source"/>.</typeparam> /// <param name="source">The input sequence.</param> /// <exception cref="InvalidOperationException"> /// The input sequence contains more than one element.</exception> /// <returns> /// The single element of the input sequence. /// </returns> public static T Single <T>(this IExtremaEnumerable <T> source) { if (source == null) { throw new ArgumentNullException(nameof(source)); } return(source.Take(2).AsEnumerable().Single()); }
public Group FindClosestGroup(Vector2 point, float size) { float Selector(Group group) { var groupCenter = group.Center; float distance = Vector3.SqrMagnitude(point - groupCenter); return(distance); } IExtremaEnumerable <Group> mins = _groups.MinBy(Selector); var closestGroup = mins.First(); return(closestGroup); }
public string SolvePart1() { var currentLocation = new Location(0, 0); while (currentLocation.X <= XBoundary && currentLocation.Y <= YBoundary) { Dictionary <Location, int> distances = AllLocations.ToDictionary(location => location, location => CalculateManhattanDistance(currentLocation, location)); IExtremaEnumerable <KeyValuePair <Location, int> >?sortedDistances = distances.MinBy(d => d.Value); KeyValuePair <Location, int> shortestDistance = sortedDistances.First(); if (sortedDistances.Count() == 1 || sortedDistances.Count(s => s.Value == shortestDistance.Value) == 1) { // Only add if the current location is closest to a single point. var newLocation = new Location(currentLocation.X, currentLocation.Y) { IsInfinite = currentLocation.X == 0 || currentLocation.Y == 0 || currentLocation.X == XBoundary || currentLocation.Y == YBoundary }; AllLocations.SingleOrDefault(l => l == shortestDistance.Key)?.ClosestLocations.Add(newLocation); } // Move to the next location if (currentLocation.Y == YBoundary) { currentLocation.X++; currentLocation.Y = 0; } else { currentLocation.Y++; } } List <Location> nonInfiniteLocations = AllLocations.Where(l => l.ClosestLocations.All(c => !c.IsInfinite)).ToList(); Location? largestNonInfinite = nonInfiniteLocations.MaxBy(l => l.ClosestLocations.Count).First(); return($"Part 1: {largestNonInfinite.ClosestLocations.Count}"); }