Skip to content

Instantly share code, notes, and snippets.

@tcshao
Created March 3, 2018 05:38
Show Gist options
  • Save tcshao/048980eb78332c4977e8bf1022079d02 to your computer and use it in GitHub Desktop.
Save tcshao/048980eb78332c4977e8bf1022079d02 to your computer and use it in GitHub Desktop.
using System;
using System.Collections.Generic;
using System.Linq;
public static class Program
{
public static void Main()
{
Enumerable.Range(0, 9)
.Squeeze(2)
.GenerateSuccessivePairs()
.ToList()
.ForEach(Console.WriteLine);
Console.WriteLine();
}
}
public static class ExtensionMethods
{
// this method given an enumerable list, will try to truncate the left and right sides equally
// ie given [4, 5, 6, 7] with a Squeeze of 1, it will return [5, 6], obviously this can not handle
// large arrays because it scans to the end first
public static IEnumerable<T> Squeeze<T>(this IEnumerable<T> source, int count)
{
return source.TruncateLeft(count).TruncateRight(count);
}
public static IEnumerable<T> TruncateLeft<T>(this IEnumerable<T> source, int count)
{
return source.Skip(count);
}
public static IEnumerable<T> TruncateRight<T>(this IEnumerable<T> source, int count)
{
var totalToTake = source.Count() - count;
return totalToTake <= 0
? Enumerable.Empty<T>()
: source.Take(totalToTake);
}
// given an enumerable, it will return a tuple representing the current item
// and the one after
public static IEnumerable<Tuple<T,T>> GenerateSuccessivePairs<T>(this IEnumerable<T> source)
{
return
source.Zip(source.Skip(1), (a, b) => Tuple.Create(a, b));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment