Skip to content

Instantly share code, notes, and snippets.

@MinChanSike
Last active December 15, 2020 02:08
Show Gist options
  • Save MinChanSike/de6a0ac10f1ebf9a215e29ae92039f10 to your computer and use it in GitHub Desktop.
Save MinChanSike/de6a0ac10f1ebf9a215e29ae92039f10 to your computer and use it in GitHub Desktop.
Partition Elements By C#
public static class Extensions {
public static Dictionary<int, IEnumerable<T>> AdjustablePartition<T>(this IEnumerable<T> source, int count) {
var map = new Dictionary<int, IEnumerable<T>>();
var average = (int)Math.Round(source.Count() / (double)count);
for (int i = 0; i < count; i++) {
if (i == count - 1) {
var skipCount = (i) * average;
var takeCount = source.Count() - skipCount;
map.Add((i + 1), source.Skip(skipCount).Take(takeCount).ToArray());
} else {
map.Add((i + 1), source.Skip(i * average).Take(average).ToArray());
}
}
return map;
}
public static Dictionary<int, IEnumerable<T>> JustPartition<T>(this IEnumerable<T> source, int count) {
var sourceCount = source.Count();
return source.Select((x, i) => new { value = x, index = i })
.GroupBy(x => x.index / (int)Math.Ceiling(sourceCount / (double)count))
.Select(x => x.Select(z => z.value))
.Select((v, i) => new Tuple<int, IEnumerable<T>>(i, v))
.ToDictionary(v => (v.Item1 + 1), v => v.Item2);
}
}
void Main() {
var sources = Enumerable.Range(1, 10).Select(i => $"Item-{i}").ToArray();
Console.WriteLine("JustPartition Results");
foreach (var elm in sources.JustPartition(3)) {
Console.WriteLine($"Group ({elm.Key})");
Console.WriteLine($"\t\t\t{string.Join("\n\t\t\t", elm.Value)}");
}
Console.WriteLine("------------------------------------------");
Console.WriteLine("AdjustablePartition Results");
foreach (var elm in sources.AdjustablePartition(3)) {
Console.WriteLine($"Group ({elm.Key})");
Console.WriteLine($"\t\t\t{string.Join("\n\t\t\t", elm.Value)}");
}
}
/*
JustPartition Results
Group (1)
Item-1
Item-2
Item-3
Item-4
Group (2)
Item-5
Item-6
Item-7
Item-8
Group (3)
Item-9
Item-10
------------------------------------------
AdjustablePartition Results
Group (1)
Item-1
Item-2
Item-3
Group (2)
Item-4
Item-5
Item-6
Group (3)
Item-7
Item-8
Item-9
Item-10
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment