Заставить консольную программу угадывания случайных строк циклически угадывать один символ за раз вместо всех сразу - PullRequest
0 голосов
/ 05 января 2019

Код разработан, чтобы начать с создания рандомизированной строки символов, которая имеет выбранное пользователем количество символов. Затем он будет циклически перебирать символы до тех пор, пока символ не совпадет со строкой, в этом случае он блокирует ее и окрашивает в голубой цвет. Любые символы, уже опробованные для строки, игнорируются.

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

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

namespace ConsoleApp3
{
    class Program
    {
        private static Random random = new Random();
        public static string RandomString(int length)
        {
            const string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
            return new string(Enumerable.Repeat(chars, length)
              .Select(s => s[random.Next(s.Length)]).ToArray());
        }


        static void Main(string[] args)
        {


            Console.WriteLine("How many characters in the password?");
            string delta = Console.ReadLine();

            try
            {
                int passwordlength = Convert.ToInt32(delta);

                // BARRIER

                string password = RandomString(passwordlength);

                Random r = new Random();
                string letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
                List<string> dictionary = new List<string>(new string[] { password });

                string word = dictionary[r.Next(dictionary.Count)];
                List<int> indexes = new List<int>();
                Console.ForegroundColor = ConsoleColor.Red;
                StringBuilder sb = new StringBuilder();
                for (int i = 0; i < word.Length; i++)
                {
                    sb.Append(letters[r.Next(letters.Length)]);
                    if (sb[i] != word[i])
                    {
                        indexes.Add(i);

                    }
                }
                Console.WriteLine(sb.ToString());

                var charsToGuessByIndex = indexes.ToDictionary(k => k, v => letters);

                while (indexes.Count > 0)
                {
                    int index;

                    Thread.Sleep(50);
                    Console.Clear();

                    for (int i = indexes.Count - 1; i >= 0; i--)
                    {
                        index = indexes[i];

                        var charsToGuess = charsToGuessByIndex[index];
                        sb[index] = charsToGuess[r.Next(charsToGuess.Length)];
                        charsToGuessByIndex[index] = charsToGuess.Remove(charsToGuess.IndexOf(sb[index]), 1);
                        if (sb[index] == word[index])
                        {
                            indexes.RemoveAt(i);
                        }
                    }
                    var output = sb.ToString();

                    for (int i = 0; i < output.Length; i++)
                    {
                        if (indexes.Contains(i))
                        {
                            Console.ForegroundColor = ConsoleColor.Red;
                        }
                        else
                        {
                            Console.ForegroundColor = ConsoleColor.Cyan;
                        }

                        Console.Write(output[i]);
                    }

                    Console.WriteLine();
                }

                Console.ForegroundColor = ConsoleColor.Green;

                Console.WriteLine("Password successfully breached. Have a nice day.");                    
                Console.WriteLine("");

                Console.ReadLine();
            }
            catch
            {
                if (delta is string)
                {
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.Clear();
                    Console.WriteLine("FATAL ERROR PRESS ENTER TO EXIT");


                    Console.ReadLine();
                }
                else
                {
                    Console.WriteLine("welp, it was worth a try.");
                    Console.ReadLine();
                }
            }
        }




    }
}

1 Ответ

0 голосов
/ 06 января 2019
using System;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading;

namespace ConsoleApp3
{
    class Program
    {
        private static Random random = new Random();
        static string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";

        public static string generatePassword(int length)
        {
            var sb = new StringBuilder();
            for (int i = 0; i < length; i++)
            {
                sb.Append(chars.OrderBy(o => Guid.NewGuid()).First());
            }
            return sb.ToString();
        }

        public static StringBuilder generateNotPassword(int length, string password)
        {
            var sb = new StringBuilder();
            for (int i = 0; i < length; i++)
            {
                sb.Append(chars.Where(w => password[i] != w).OrderBy(o => Guid.NewGuid()).First());
            }
            return sb;
        }

        static void Main(string[] args)
        {
            Console.WriteLine("How many characters in the password?");
            var passwordlength = int.Parse(Console.ReadLine());
            var password = generatePassword(passwordlength);
            var notPassword = generateNotPassword(passwordlength, password);

            Stopwatch stopWatch = new Stopwatch();
            stopWatch.Start();
            for (int i = 0; i < passwordlength; i++)
            {
                var notfound = true;
                while (notfound)
                {

                    foreach (var c in chars)
                    {
                        if (password[i] == c)
                        {
                            notPassword[i] = c;
                            notfound = false;
                        }
                        Thread.Sleep(50);
                        Console.Clear();
                        var output = notPassword.ToString();
                        for (int ii = 0; ii < output.Length; ii++)
                        {
                            var iii = (!notfound && i == ii) ? ii - 1 : ii;
                            Console.ForegroundColor = i > iii ? ConsoleColor.Red : ConsoleColor.Cyan;
                            var o = i <= iii ? '█' : output[ii];
                            Console.Write(o);
                        }
                        Console.WriteLine();
                        TimeSpan ts = stopWatch.Elapsed;
                        Console.WriteLine
                            (String.Format(
                           "RunTime {0:00}:{1:00}:{2:00}.{3:00}",
                           ts.Hours, ts.Minutes, ts.Seconds, ts.Milliseconds / 10));
                        if (!notfound) break;
                    }


                }
            }
            Console.ForegroundColor = ConsoleColor.Green;

            Console.WriteLine($"Guessed  Password = {notPassword}");
            Console.WriteLine($"Original Password = {password}");
            //https://www.asciiart.eu/electronics/electronics
            Console.WriteLine(@"
                                  ____
                             ____|    \
                            (____|     `._____
                             ____|       _|___
                            (____|     .'
                                 |____/

                            ");
            Console.ReadLine();
        }
    }
}
...