0

Yes I have searched a lot for a solution and yes I am a beginner and this is the first time that I asked a question through this website. I usually ask it to my teacher but I have a holiday and I am spending my free time on learning C#.

I have a task which I made up by myself and the task is a game where you have to put a word into a console application and the console has to randomize every single letter of the word so that the other player has to guess what the word is.

example : the word is "programming" and after that the console will mix up the letters of the word, so it could be "ginamrmgorp" and the player has to guess what the word is.

        string woord = Console.ReadLine();
        Random random = new Random();
        char[] woorden = woord.ToCharArray();

        for (int i = 0; i < woorden.Length; i++)
        {

            kiesgetal = random.Next(0, woorden.Length);
            char letter = woorden[kiesgetal];

            Console.Write("letter: ");
            Console.WriteLine(letter);
        }
        Console.ReadKey();

The problem is that the console isn't using every letter of the word but the console is using some letters (not all) of the word and it puts it in the length of the word so it isn't "ginamrmgorp" but "gimmmmoopra".

Sakirma
  • 31
  • 1
  • 6

2 Answers2

4

Basically you wanna shuffle the character array. You can do that easily using Fisher-Yates shuffle algorithm, as implemented in this answer. Here is the modified version for arrays:

public static void Shuffle<T>(this T[] list)  
{  
    Random rng = new Random();  
    int n = list.Length;  
    while (n > 1) {  
        n--;  
        int k = rng.Next(n + 1);  
        T value = list[k];  
        list[k] = list[n];  
        list[n] = value;  
    }  
}

Then just use it like this:

char[] woorden = woord.ToCharArray();
woorden.Shuffle();
string shuffledWord = new string(woorden);
Community
  • 1
  • 1
Selman Genç
  • 100,147
  • 13
  • 119
  • 184
1

Random.Next will not necessarily return a different number each time. It's entirely likely that you will get the same number muptiple times.

What you want to do is shuffle the letters, which can be done by ordering by a random number:

    char[] woorden = woord.ToCharArray();

    var woordenShuffled = woorden.OrderBy(c => random.Next()).ToArray();

    for (int i = 0; i < woordenShuffled.Length; i++)
    {
        char letter = woordenShuffled[i];
        Console.Write("letter: ");
        Console.WriteLine(letter);
    }

or if you just want to create the whole string:

string woordShuffled = new string(woord.OrderBy(c => random.Next()).ToArray());
D Stanley
  • 149,601
  • 11
  • 178
  • 240