K
K
kill942015-09-09 20:07:08
Algorithms
kill94, 2015-09-09 20:07:08

How to generate all words from letters of given length?

Help need to generate words from a given alphabet
for example:
alphabet: a, b, c, d word
length: 4
then the number of words: 4 ^ 2
aa
ab
ag ba bb bc bg va wb cc ....
y

Answer the question

In order to leave comments, you need to log in

3 answer(s)
A
ar4ebaldello, 2015-09-09
@kill94

This is not the best, but probably the easiest option.
If you want, I can write in detail.

class Program
{
  static void Main(string[] args)
    {
        Console.InputEncoding = Console.OutputEncoding = Encoding.GetEncoding(@"Cyrillic");

        var letters = Console.ReadLine().ToCharArray(); // Введи весь алфавит в одну строчку
        var wordLength = int.Parse(Console.ReadLine()); // Введи размер слова

        var word = new char[wordLength];
        var totalWordsCount = 1;

        for (var i = 0; i < wordLength; i++)
            totalWordsCount *= letters.Length;

        for (var i = 0; i < totalWordsCount; i++)
        {
            var accum = i;
            for (var j = word.Length - 1; j >= 0; j--)
            {
                word[j] = letters[accum % letters.Length];
                accum /= letters.Length;
            }

            Console.WriteLine(new string(word));
        }

        Console.ReadKey();
    }
}

S
Sergey, 2015-09-09
Protko @Fesor

for the future:
- you need all possible permutations of letters, not all words
- permutations in english will be "permutations"
- google
https://en.wikipedia.org/wiki/Heap%27s_algorithm

M
Mrrl, 2015-09-10
@Mrl

void PrintAllWords(string alphabet,int length){
  PrintAllWords(alphabet,length,"");
}
void PrintAllWords(string alphabet,int length,string prefix){
  if(length==0) Console.WriteLine(prefix);
  else foreach(char c in alphabet) PrintAllWords(alphabet,length-1,prefix+c);
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question