1

I want to ask if how can I randomize a word that I've get from the textfile data I made.

I already have the word actually from the textfile and stored into an array of character.

Here's what I have so far

I created a method called Shuffle

void Shuffle(string[] chArr)
    {
        //Shuffle
        for (int i = 0; i < chArr.Length; i++)
        {
            string tmp = chArr[i].ToString();
            int r = Random.Range(i, chArr.Length);
            chArr[i] = chArr[r];
            chArr[r] = tmp;

        }
        Debug.Log(chArr);
    }

and use it like this

string temp = textArray[rowsToReadFrom[0]];
        temp = System.Text.RegularExpressions.Regex.Replace(temp, @"\s", "");
        char[] chArr = temp.ToCharArray();

        string s = chArr.ToString();
        string[] ss = new string[] { s };
        Shuffle(ss);

        foreach (char c in chArr)
        {
            testObject clone = Instantiate(prefab.gameObject).GetComponent<testObject>();
            clone.transform.SetParent(container);

            charObjects.Add(clone.Init(c));

            //Debug.Log(c);
        }

It still doesn't randomize that word I get from the textfile data.

EDITTED

So far here's what I did

string temp = textArray[rowsToReadFrom[0]];
        temp = System.Text.RegularExpressions.Regex.Replace(temp, @"\s", "");
        char[] chArr = temp.ToCharArray();

        string charResult = "";
        for(int i = 0; i < chArr.Length; i++)
        {
            int ran = Random.Range(0, chArr.Length);
            charResult += chArr[ran];
        }

        Debug.Log(charResult);

        foreach (char c in charResult)
        {

            testObject clone = Instantiate(prefab.gameObject).GetComponent<testObject>();
            clone.transform.SetParent(container);

            charObjects.Add(clone.Init(c));

            //Debug.Log(c);
        }


But instead of giving me for example the word "Abandon" it would give me sometimes a randomize word "aaaabn" could someone help me out why?

  • Possible duplicate of [C# (sharp) reading random line from txt file](https://stackoverflow.com/questions/5796224/c-sharp-sharp-reading-random-line-from-txt-file) – styx Apr 14 '19 at 08:14
  • @styx it's a different thing sir . You see I have already pick a word and store it to the chararray and that chararray is what I want to be randomized –  Apr 14 '19 at 08:16
  • Do you want to get a random character from a given string? – styx Apr 14 '19 at 08:18
  • @styx No I want to randomize the words that I get from the textile for example I already have an "Abandon" word and has been stored on the ```chArr``` variable. –  Apr 14 '19 at 08:19
  • you want to get a random word from a text file and store it at `chArr`? – styx Apr 14 '19 at 08:32
  • @styx I already have a random word that I got from the text file and it was stored already on the ```char[] chArr``` now I want to randomize that variable –  Apr 14 '19 at 08:33
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/191806/discussion-between-styx-and-boonmingprog). – styx Apr 14 '19 at 08:39
  • 1
    Possible duplicate of [Best way to randomize an array with .NET](https://stackoverflow.com/questions/108819/best-way-to-randomize-an-array-with-net) – derHugo Apr 14 '19 at 09:02
  • @derHugo can I have a c# in unity sir?? –  Apr 14 '19 at 09:04
  • 1
    In the up to date version of Unity you can **only** have c# ... What do you think your given code is written in? – derHugo Apr 14 '19 at 09:07

3 Answers3

1

Your code is just getting random letters from that word but does not exclude duplicate. What you want instead is randomize the array of chars and convert it back to a string

System.Random rnd = new System.Random();
Char[] randomCharArray = chArr.OrderBy(x => rnd.Next()).ToArray();
string charResult = randomCharArray.ToString();

Unity has its own implementation of Random so be sure you use System.Random

derHugo
  • 83,094
  • 9
  • 75
  • 115
  • Apparently Unity has its own implementation of `Random` make sure you use the one from `System` – derHugo Apr 14 '19 at 09:15
  • Sorry sir for being a beginner but how can I display that on the log? –  Apr 14 '19 at 09:19
  • Your way is by far simpler than mine :) – Hassan Faghihi Apr 14 '19 at 09:23
  • `Debug.Log(charResult, this);` the `this` just makes that additionally you can click it in the console and it will show you where that log entry came from ;) – derHugo Apr 14 '19 at 09:25
  • @derHugo This will not yield a good random result. According to [MSDB](https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.orderby?redirectedfrom=MSDN&view=netframework-4.7.2#System_Linq_Enumerable_OrderBy__2_System_Collections_Generic_IEnumerable___0__System_Func___0___1__) OrderBy will use a stable sort and preserve the order for those characters that are given the same value. For the 'h' in "hello" to be put last, 'h' needs to roll 'false' and the rest 'true'. However the result will be "elloh", which is not very exciting. – styx Apr 14 '19 at 09:26
  • @derHugo it only gives me a ``` System.Char[] ```log –  Apr 14 '19 at 09:27
  • @BoonMingProg replace the last line with `string charResult = String.Join("", randomCharArray);` – styx Apr 14 '19 at 09:29
1

I will be using Fisher–Yates_shuffle

 public static string Shuffle(string str)
    {
        System.Random random = new System.Random();         
        var array = str.ToCharArray();
        for (int i = 0; i < array.Length; i++)
        {
            int j = random.Next(i, array.Length); 
            char temp = array[i]; 
            array[i] = array[j];
            array[j] = temp;
        }
        return String.Join("", array);
    }

and to use it simply do

var f = "hello";

Console.WriteLine(Shuffle(f));
styx
  • 1,852
  • 1
  • 11
  • 22
0

it's most easier if you use a list (let call it initial list), (it may have some performance overheat do to shifts on remove, but i'm wonder if using a linked list would solve that...

Here what you can do if you do as i said:

  1. Fill the list, with your words, or char, or any data which you want to randomize
  2. Create another list or array to store randomized data in (result)
  3. create a while loop, and check while, your initial list Has Item (count > 0)
  4. use Random, and performe rand.Next(0, initialList.Count)
  5. take the item within the index of random number and append it to the result list, (or replace free slot if you are using array)

    List<string> initial = new List<string>();
    initial.AddRange(data);
    Random rand = new Random();
    List<string> result = new List<string>();
    while (initial.Count > 0) // LINQ: initial.Any() 
    {
        int index = rand.Next(0, initial.Count);
        result.Add(initial[index]);
        initial.RemoveAt(index);
    }
    return result;
    
Hassan Faghihi
  • 1,888
  • 1
  • 37
  • 55