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

Add item after every nth step

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

Problem

The purpose of the method is to add a list of items after every nth step (5 for example) where the input items are repeated if needed. I'm looking for an overall review and possible how to remove the use of the while and replace it with a for.

public static List AddEveryNthStep(List items, List itemsToAdd, int nthStep)
{
    List output = new List();

    int itemIndex = 0;
    int itemsToAddIndex = 0;
    int index = 1;

    while (itemsToAddIndex < itemsToAdd.Count)
    {
        output.Add(items[itemIndex++]);

        if (itemIndex == items.Count)
        {
            itemIndex = 0;
        }

        // We are at at point where we want to add a item
        if (index % nthStep == 0)
        {
            output.Add(itemsToAdd[itemsToAddIndex++]);
        }

        index++;
    }

    return output;
}


Usage:

List items = new List { "Item 1", "Item 2", "Item 3", "Item 4" };
List itemsToAdd = new List { "Item to add 1", "Item to add 2", "Item to add 3" };

Console.WriteLine(String.Join(Environment.NewLine, AddEveryNthStep(items, itemsToAdd, 5)));


Output:

Solution

Loops and Indexes

Why are you using a while loop? A for loop keeps track of indexes for you. Admittedly you do still need to track one index yourself, but you can eliminate one to loop processing:

int addIndex = 0;
for (int i = 0; i < items.Count; i++) {
    output.Add(items[i]);

    if (i % nthStep == 0) {
        output.Add(itemsToAdd[addIndex++]);
    }

    if (i == (items.Count - 1) && addIndex < (itemsToAdd.Count - 1)) {
        i = 0;
    }
}


In words:

  • define an index for the items you're adding



  • loop through the items list, on every pass:



  • add the current item to the output list



  • if the current step is the nth step, add the next item to add and increase the index



  • if we've run out of items but have more left to add, reset the items index so we loop back through



Now you're only tracking and handling one index yourself, instead of the three that your while loop requires.

Code Snippets

int addIndex = 0;
for (int i = 0; i < items.Count; i++) {
    output.Add(items[i]);

    if (i % nthStep == 0) {
        output.Add(itemsToAdd[addIndex++]);
    }

    if (i == (items.Count - 1) && addIndex < (itemsToAdd.Count - 1)) {
        i = 0;
    }
}

Context

StackExchange Code Review Q#126299, answer score: 3

Revisions (0)

No revisions yet.