Home > front end >  Generate All Possible Combinations of A Password When Given the List of Integers
Generate All Possible Combinations of A Password When Given the List of Integers

Time:12-27

I have a list of integers:

List <int> allPossibleValues;

The length of the password:

int passwordLength = 2;

I should generate all possible combinations of the password with the integers from the list:

List <int> allPossibleValues = new List<int>() { 1, 2, 4};
int passwordLength = 2;

Expected result:

List<string> { 
  "11", "22", "44", "12", "21", "14", "41", "24", "42" 
};

How can I create a logic to implement this?

CodePudding user response:

You could just use two for cycles to iterate through your Input list twice, combine the values and add the combined value to a new list.

CodePudding user response:

Well, you can put it like this:

Code:

using System.Linq;

...

// Let's do it a bit more general - <T> - and enumerate any items of alphabet 
private static IEnumerable<string> Passwords<T>(List<T> alphabet, int size) {
  int[] current = new int[size];

  do {
    yield return string.Concat(current.Select(i => alphabet[i]));

    for (int i = 0; i < current.Length;   i)
      if ((current[i] = (current[i]   1) % alphabet.Count) != 0)
        break;
  }
  while (!current.All(i => i == 0));
}

Demo:

List <int> allPossibleValues = new List<int>() { 1, 2, 4};
int passwordLength = 2;

string[] passwords = Passwords(allPossibleValues, passwordLength).ToArray();

var report = string.Join(", ", passwords);
      
Console.Write(report);

Outcome:

11, 21, 41, 12, 22, 42, 14, 24, 44
  • Related