Katie
Katie

Reputation: 377

Partitioning a list given total partitions and partition number

Suppose I'm given a list of items:

[ A, B, C, D, E, F, G, H, I, J ]

I'm asked to split these into 3 lists, and take the second list:

[ A, B, C, D ] [ E, F, G ] [ H, I, J ]

How would I do this?

I'm thinking the function would look like

public List<Item> SplitItems(
    List<Item> items, 
    int totalPartitions, 
    int partitionNumber) { }

I'm able to get the list if the partitionNumber is 1 (the first set) using calculations involving the modulo operation of the totalPartitions and the partitionNumber, but I'm having issues getting the list of partitionNumber 2 and above.


@Blorgbeard: Here's the code that I have so far. Again, I'm only able to handle the first partition:

int itemsCount = items.Count;
int setCount = itemsCount/totalPartitions + ((itemsCount%totalPartitions >= partitionNumber) ? 1 : 0);
return webItems.Take(setCount).ToList();

Upvotes: 3

Views: 754

Answers (3)

Gert Arnold
Gert Arnold

Reputation: 109165

Another approach is to create a collection of evenly distributed numbers 0-2 and Zip it with your items:

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();

Upvotes: 2

Dave Mackersie
Dave Mackersie

Reputation: 1061

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);

Upvotes: 3

Jaap Elgersma
Jaap Elgersma

Reputation: 169

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;
}

Upvotes: -1

Related Questions