Splitting the list considering all sections and section numbers
Suppose I am given a list of items:
[A, B, C, D, E, F, G, H, I, J]
I am asked to split them into 3 lists and take the second list:
[A, B, C, D] [E, F, G] [H, I, J]
How should I do it?
I think the function would look like
public List<Item> SplitItems(
List<Item> items,
int totalPartitions,
int partitionNumber) { }
I can get a list if it partitionNumber
is 1 (first set) using the calculations associated with the modulo totalPartitions
and operation partitionNumber
, but I am having problems getting list partitionNumber
2 and above.
@Blorgbeard: Here is the code I have so far. Again, I can only handle the first section:
int itemsCount = items.Count;
int setCount = itemsCount/totalPartitions + ((itemsCount%totalPartitions >= partitionNumber) ? 1 : 0);
return webItems.Take(setCount).ToList();
source to share
int smallPartitionSize = list.Count / totalPartitions;
int remainder = list.Count % totalPartitions;
int selectedPartitionSize = smallPartitionSize + (partitionNumber <= remainder) ? 1 : 0;
var start = (partitionNumber - 1) * smallPartitionSize + Math.Min(remainder, partitionNumber - 1);
return list.Skip(start).Take(selectedPartitionSize);
source to share
Another approach is to create a set of evenly spaced numbers 0-2 and Zip
with your positions:
var items = new[] { "A", "B", "C", "D", "E", "F", "G", "H", "I", "J" };
var n = items.Length;
var partitioner = Enumerable.Range(0, n).Select (e => (e * 3) / n );
// Values: { 0, 0, 0, 0, 1, 1, 1, 2, 2, 2 }
var result = partitioner.Zip(items, (i,s) => new {i,s})
.Where(z => z.i == 1).Select(z => z.s).ToList();
source to share
public static List<T> SplitItems<T>(
List<T> items,
int totalPartitions,
int partitionNumber)
{
var result = new List<T>();
int partitionIndex = partitionNumber - 1;
int size = (int)Math.Ceiling((double)items.Count / totalPartitions);
result.AddRange(items.Skip(size * partitionIndex).Take(size));
return result;
}
source to share