-2

I want to write a method which returns a string. So far so good. The creation of the string however is quite complicated. I have 3 string lists - the first one has 155 entries, the second one - 9, the third one 21. I want my method if called enough times(155*9*21) to return all the possible combinations of values from the 3 lists (basically this method should keep count on how many times it was called and return only one combination each time). Any ideas how to accomplish that?

I have 155*9*22 possible combinations. The first time the method is called it should take List1(0), List2(0), List3(0). After that in the next 21 iterations, the index of the third list is only changed. Once all the elements from the third list have been used increment the index of the second list and so on.

Once the method has produced all the possible combinations (155*9*22) I want it to start from the beginning.

2
  • may be you should try yield return : example
    – Guru Stron
    Jun 26, 2013 at 15:52
  • as simple as three for loops; for each word in each loop print out results
    – user2140173
    Jun 26, 2013 at 15:52

5 Answers 5

3

You can just enumerate all possible combinations, like this:

    public IEnumerable<String> generator() {
      foreach (String item1 in List1)
        foreach (String item2 in List2)
          foreach (String item3 in List3)
            yield return item1 + item2 + item3;
    }

   ...

   foreach (String item in generator()) {
     // Do something with generated strings
   }
5
  • yes but the generation of the string should happen only when the method is called, and I am aiming to keep how far I got in the same method using some indexes.
    – Andrey
    Jun 26, 2013 at 15:57
  • @Andrey read the link which I posted in comments to your question
    – Guru Stron
    Jun 26, 2013 at 15:58
  • yes this would return all the possible combinations. However I want my method to do the computations only when it is invoked and to keep count on how far it went. A possible way is to get all the combinations and just index them but if I decide to extend the method(to add one more list) then this will result in a lot of results which is unwanted memory usage.
    – Andrey
    Jun 26, 2013 at 16:12
  • @Andrey: This does not generate a separate list. It returns items one at a time, as needed. That's sort of the point of deferred execution (among other things). And you can keep track of the count by using the technique I posted in my answer. Jun 26, 2013 at 16:21
  • @Dmitry: If you like, you can combine my answer with yours, and I'll delete my answer. Jun 26, 2013 at 16:21
1

Used good old modulo operator. Can probably be optimized a lot more.

public class Generator
{
    private int index = 0;
    private List<string> list1 = new List<string> { "a", "b" };
    private List<string> list2 = new List<string> { "c", "d" };
    private List<string> list3 = new List<string> { "e", "f", "g" };

    public string Next()
    {
        int indexList3 = index % list3.Count;
        int indexList2 = (index / list3.Count) % list2.Count;
        int indexList1 = (index / (list2.Count * list3.Count)) % list1.Count;

        IncrementIndex();

        return list1[indexList1] + list2[indexList2] + list3[indexList3];
    }

    private void IncrementIndex()
    {
        index++;
        if (index > list1.Count*list2.Count*list3.Count)
        {
            index = 0;
        }
    }
}

so the first 13 results (on 12 possible combinations), obtained with

string result = string.Empty;
Generator generator = new Generator();

for (int i = 0; i < 13; i++)
{
    result += generator.Next() + "\n";
}

outputs :

ace
acf
acg
ade
adf
adg
bce
bcf
bcg
bde
bdf
bdg
ace
1

You can keep an index for each list:

public IEnumerable<string> Permutations(string[][] lists, int start = 0) {
    int[] position = new int[lists.Length];

    for(int i = lists.Length - 1; start > 0; i--) {
        position[i] = start % lists[i].Length;
        start /= lists[i].Length;
    }

    while(true) {
        int i;
        string current = string.Empty;

        for(i = lists.Length - 1; i >= 0; i--) {
            if(++position[i] == lists[i].Length) {
                position[i] = 0;
                current = lists[i][0] + current;
            } else {
                break;
            }
        }

        if(i == -1) break;

        while(i > -1) {
            current = lists[i][position[i]] + current;
            i--;
        }

        yield return current;
    }
}

It takes a place to start, optionally, so you can keep just one integer and generate the next item.

I haven’t tested this, though. Be warned! :)

1

Using the method shown by Dmitry Bychenko, you can keep track of how far you are in the lists:

// use his generator method
public IEnumerable<String> generator()
{
    ...
}

....

int counter = 0;
foreach (String item in generator())
{
    // compute indexes
    int ix_list3 = counter % List3.Count;
    int ix_list2 = (counter / List3.Count) % List2.Count;
    int ix_list1 = (counter / (List3.Count * List2.Count));

    // do something with item and indexes
    ++counter;
}
1
public IEnumerable<string> List1 = new [] { "A", "B", "C" };
public IEnumerable<string> List2 = new [] { "1", "2", "3" };
public IEnumerable<string> List3 = new [] { "Z", "Y" };

public IEnumerator<string> StringEnumerator;

public void InitializeEnumerator()
{
    var stringEnumerable = List1.SelectMany(x => List2.SelectMany(y => List3.Select(z => x + y + z)));

    StringEnumerator = stringEnumerable.GetEnumerator();
}

public string GetNextString()
{
    return StringEnumerator.MoveNext() ? StringEnumerator.Current : null;
}

Just call InitializeEnumerator(), then you will get a new string out of each call to GetNextString()

InitializeEnumerator();
GetNextString(); //-> A1Z
GetNextString(); //-> A1Y
GetNextString(); //-> A2Z
GetNextString(); //-> A2Y
GetNextString(); //-> A3Z
GetNextString(); //-> A3Y
GetNextString(); //-> B1Z

To have it auto initialize and re-initialize after it runs out, modify GetNextString like this.

public string GetNextString()
{
    if(StringEnumerator == null || !StringEnumerator.MoveNext())
    {
        InitializeEnumerator();
        StringEnumerator.MoveNext();
    }

    return StringEnumerator.Current;
}
3
  • And once it has covered all the combinations how to make it to start iterating from the first one again?
    – Andrey
    Jun 26, 2013 at 16:14
  • Just call InitializeEnumerator() again. Jun 26, 2013 at 16:20
  • I modified my answer to include a looping version of GetNextString Jun 26, 2013 at 16:27

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.