- Home /
Random String from list of string without repeated letters
List letters = new List(); //for exampe letters = e,n,d for (int i = 0; i < letters.Count; i++) { myString += letters[UnityEngine.Random.Range(0, letters.Count)]; if (myString.Length != letters.Count) { return; } if (!randomWords.Contains(myString)) { randomWords.Add(myString); rwords.text = rwords.text + " " + myString; } myString = ""; }
And i get a random words but the letters repeat for example: eed, enn.
I want to get words from list of letters for example: end, edn, ned, nde, den, dne.
Or if letters are more.
Answer by sacredgeometry · Jan 23, 2020 at 09:01 PM
You could do what logicandchaos said or you could randomise the order of the list/string and take the first n (obviously where n is smaller or equal to the size of the list) from the newly randomised list/string. Bear in mind this doesnt protect against duplicate sequences it just means that there arent duplicate characters.
var alphabet = "abcdefghijklmnopqrstuvwxyz";
var num = new Random();
var randomString = new string(
alphabet
.ToCharArray()
.OrderBy(s => (num.Next(2) % 2) == 0)
.Take(3)
.ToArray()
);
Answer by logicandchaos · Jan 23, 2020 at 08:45 PM
Sure, just when you select the letter myString += letters[UnityEngine.Random.Range(0, letters.Count)]; you just need to check if the last letter is the same, but then if it's not you have to generate a new value, so it will need to be put in a loop.
char newLetter = letters[UnityEngine.Random.Range(0, letters.Count)];
while(newLetter == myString[myString.Length])
newLetter = letters[UnityEngine.Random.Range(0, letters.Count)];
myString += newLetter;
Your answer
Follow this Question
Related Questions
How can I randomly create a number and then delete it to stop repeating 3 Answers
Random.Range is the same in each object with the script 0 Answers
pick a random int with the value of 1 from an array 2 Answers
Placing trees randomly across a large terrain 1 Answer
How good is Random.Range() for Uniform Distribution? 1 Answer