Все возможные комбинации символов из 2 разных строк в C# - PullRequest
0 голосов
/ 21 апреля 2020

Может кто-нибудь помочь мне с этим?

Это должно быть ConsoleApp, которое запрашивает имя и фамилию. Из всего названия должно генерироваться 4 символа. Я должен предоставить различные возможные комбинации строк (например, 1. и 3. char из fn и 2. 3. char из ln ...) Алгоритм должен быть способен обеспечить все возможные комбинации из 4 символов, где 2 из имя и фамилия 2.

До сих пор я делал только комбинации 2 для имени и фамилии.

static void Main(string[] args) 
{ 
   Console.WriteLine("Enter your first name");
   string firstName = Console.ReadLine(); 

   Console.WriteLine("Enter your last name"); 
   string lastName = Console.ReadLine();

        string[] result = GetAllCombinations(firstName);
        string[] code = GetAllCombinations(lastName);

        PrintTheCombinations(result);
        PrintTheCombinations(code);


    }
    private static void PrintTheCombinations(string[] list)
    {
        foreach (var results in list)
        {
            Console.WriteLine(results);
        }
    }
    private static string[] GetAllCombinations(string word)
    {
        int arraylength = word.Length * word.Length;
        var ret = new string[arraylength];

        for (int i = 0; i < word.Length; i++)
        {
            for (int j = 0; j < word.Length; j++)
            {
                ret[i * word.Length + j] = string.Concat(word[i], word[j]);
            }
        }
             return ret;
    }

Теперь мне нужно напечатать 4 символа , 2 из fn и 2 из ln, но я застрял. Надеюсь, вы, ребята, понимаете, что я имею в виду

Ответы [ 2 ]

0 голосов
/ 21 апреля 2020

Следующий код напечатает все существующие комбинации двух букв из firstName и firstName. Предполагается, что порядок букв имеет значение, и буквы могут повторяться, только если они используются несколько раз в имени и / или фамилии.

using System;

public class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine("Enter your first name");
        string firstName = Console.ReadLine();

        Console.WriteLine("Enter your last name");
        string lastName = Console.ReadLine();
        Console.WriteLine("All combinations:");
        PrintAllCombinations(firstName, lastName);

        Console.ReadLine();
    }

    private static void PrintAllCombinations(string word1, string word2)
    {
        for (int i = 0; i < word1.Length; i++)
        {
            for (int j = i + 1; j < word1.Length; j++)
            {
                for (int k = 0; k < word2.Length; k++)
                {
                    for (int l = k + 1; l < word2.Length; l++)
                    {
                        char[] chars = new char[] { word1[i], word1[j], word2[k], word2[l] };
                        //create all permutations of this collection
                        for (int ii = 0; ii < 4; ii++)
                        {
                            for (int jj = 0; jj < 4; jj++)
                            {
                                if (ii == jj) continue;
                                for (int kk = 0; kk < 4; kk++)
                                {
                                    if (ii == kk || jj == kk) continue;
                                    for (int ll = 0; ll < 4; ll++)
                                    {
                                        if (ii == ll || jj == ll || kk == ll) continue;
                                        Console.Write(chars[ii]);
                                        Console.Write(chars[jj]);
                                        Console.Write(chars[kk]);
                                        Console.Write(chars[ll]);
                                        Console.WriteLine("");
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }

}
0 голосов
/ 21 апреля 2020

это можно сделать таким образом

static void Main(string[] args)
{
    //Console.WriteLine("Enter your first name");
    //string firstName = Console.ReadLine().ToUpper();

    //Console.WriteLine("Enter your last name");
    //string lastName = Console.ReadLine().ToUpper();
    string firstName = "abc".ToUpper();
    string lastName = "123".ToUpper();
    var first = new HashSet<string>();
    var second = new HashSet<string>();
    foreach (var permutation in Permutations(firstName))
    {
        var value = $"{permutation[0]}{permutation[1]}";
        if (!first.Contains(value))
        {
            first.Add(value);
        }
    }
    foreach (var permutation in Permutations(lastName))
    {
        var value = $"{permutation[0]}{permutation[1]}";
        if (!second.Contains(value))
        {
            second.Add(value);
        }
    }
    var result = new HashSet<string>();

    foreach (var begin in first)
    {
        foreach (var end in second)
        {
            var value = $"{begin}{end}";
            if (!result.Contains(value))
            {
                result.Add(value);
                Console.WriteLine(value);
            }
        }
    }
}
static IEnumerable<string> Permutations(string word)
{
    if (word == null || word.Length <= 1)
    {
        yield return word;
        yield break;
    }

    char firstChar = word[0];
    foreach (string subPermute in Permutations(word.Substring(1)))
    {
        int indexOfFirstChar = subPermute.IndexOf(firstChar);
        if (indexOfFirstChar == -1) indexOfFirstChar = subPermute.Length;

        for (int index = 0; index <= indexOfFirstChar; index++)
            yield return subPermute.Insert(index, new string(firstChar, 1));
    }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...