HiveBrain v1.2.0
Get Started
← Back to all entries
snippetcsharpMinor

Sort items in a list by grouping rules

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
groupingrulesitemssortlist

Problem

Problem Statement

Given a list of items each having a type associated with it, group them by the below mentioned rule

  • The list should not contain consecutive items that violate the Group setting. For example. An item of "Type1" can have a group setting of 3. This means that there cannot be more than 3 consecutive items of "Type1"



  • Any items that violate the group setting (mentioned above) should be moved down the collection. The position of insertion is determined by the Skip setting for that type. For example, an item of "Type 1" can have a group setting of 3 and a skip setting of 2. This means that when we encounter more than 3 consecutive items of "Type 1" then the next available point of insertion can only be after two items (Skip = 2) of type that is not of type "Type 1"



  • Each item also has a weight associated with it. While moving down items by the above rule, ensure that weighting is respected except in cases where you have to break items because of grouping rule.



Models

public class Setting
    {
        public string Id { get; set; }
        public int GroupSize { get; set; }
        public int Skip { get; set; }
    }

    public class Entity
    {
        public string Id { get; set; }
        public string Type { get; set; }
        public int Skip { get; set; }
        public double Weight { get; set; }
    }
    public class TimelineViewModel
    {
        public TimelineViewModel()
        {
            this.Items = new List();
        }

        public string SnapshotId { get; set; }
        public IList Items { get; set; }
        public IList UnmatchedItems { get; set; }
    }


Grouping Class

```
public class GroupingHelper
{
private static Dictionary GroupSizes;

private List settings;
private List input = new List();
private List temp = new List();
private List output = new List();

//Setting class. Contains group size for each type
public GroupingHelper(List systemSettings)
{
setting

Solution

Boolean overcomplication

Overcomplicating boolean expression is a very common beginner mistake, you can return boolean values directly without if statements:

private bool Validate(Entity entity, ref string previous) 
{ 
    return (entity.Type != previous) && (GroupSizes[entity.Type] > 0);
}


The code now has a better signal (information) / noise (sintactic / mechanical) ratio.

Duplication

GroupingHelper and Reset share an identical block of code, you should remove it from the former adding a call to the latter.

Code Snippets

private bool Validate(Entity entity, ref string previous) 
{ 
    return (entity.Type != previous) && (GroupSizes[entity.Type] > 0);
}

Context

StackExchange Code Review Q#138128, answer score: 2

Revisions (0)

No revisions yet.