Dawn17
Dawn17

Reputation: 8297

Getting combinations of strings in C#

Data

When I run my code, it asks for an input string and gets the list of similar words with probability for each word token (beautiful and queen).

What I would like to do is get a mixture of the output so that I can get a list of wonderful queen, wounderful princess, lovely queen, lovely empress, etc...

My current code in the main looks like this:

    while (true)
    {
        Console.Write("Input 1 > ");

        String word1 = Console.ReadLine();
        String[] splitted = word1.Split(' ');

        for(int i = 0; i < splitted.Length; i++)
        {
            foreach (var item in model.NearestWords(splitted[i], 10))
                Console.WriteLine("{0:0.000} {1}", item.Value, item.Key);
        }

        Console.WriteLine();
    }

What is a good way to get all possibilities of similar strings of beautiful + similar strings of queen?

Upvotes: 1

Views: 479

Answers (1)

Tommaso Belluzzo
Tommaso Belluzzo

Reputation: 23675

Actually, I don't know the structure of your framework, but I can point you out to a solution to get all the possible combinations of adjectives and nouns:

List<String> adjectives = new List<String> { "Beautiful", "Wonderful", "Lovely" };
List<String> nouns = new List<String> { "Queen", "Princess", "Empress" };       

List<String> combinations = adjectives.SelectMany(a => nouns.Select(n => String.Concat(a, " ", n))).ToList();

for (Int32 i = 0; i < combinations.Count; ++i)
    Console.WriteLine(combinations[i]);

Output:

Beautiful Queen
Beautiful Princess
Beautiful Empress
Wonderful Queen
Wonderful Princess
Wonderful Empress
Lovely Queen
Lovely Princess
Lovely Empress

In order to obtain the combinations together with the average probability:

public sealed class Word
{
    public Single Probability { get; private set; }
    public String Text { get; private set; }

    public Word(Single probability, String text)
    {
        Probability = probability;
        Text = text;
    }
}

List<Word> adjectives = new List<Word>
{
    new Word(1.000f, "Beautiful"),
    new Word(0.748f, "Wonderful"),
    new Word(0.732f, "Lovely")
};

List<Word> nouns = new List<Word>
{
    new Word(1.000f, "Queen"),
    new Word(0.767f, "Princess"),
    new Word(0.702f, "Empress")
};      

List<Word> words = adjectives
    .SelectMany(
        a => 
        nouns.Select(
            n => 
            new Word(((a.Probability + n.Probability) / 2.0f), String.Concat(a.Text, " ", n.Text))
        )
    )
    .ToList();

for (Int32 i = 0; i < words.Count; ++i)
{
    Word word = words[i];

    Console.WriteLine(word.Probability.ToString("N4") + " - " + word.Text);
}

Output:

1,0000 - Beautiful Queen
0,8835 - Beautiful Princess
0,8510 - Beautiful Empress
0,8740 - Wonderful Queen
0,7575 - Wonderful Princess
0,7250 - Wonderful Empress
0,8660 - Lovely Queen
0,7495 - Lovely Princess
0,7170 - Lovely Empress

Upvotes: 2

Related Questions