Count and store instances of each letter in a string

Hi everyone,
I’m trying to make an anagram game similar to the one they have on a television program here in the UK called ‘Countdown’. The way it works is a generator outputs a random string containing 9 letters (certain number of vowels and consonants - but just assume random for now). The contestants then have to try and form words using the letters. The longer the word, the more points awarded.

They can only use the letters in the random string as many times as they appear. So for example, if there’s one ‘A’, then once it’s used in a word, its no longer available.

The ‘accepted’ words are stored in a text file which contains every word in the English language.

Now, I’ve used a Hashset to parse the text file to begin with and generated the random string of length 9 in the following way (any suggestions to improve are always appreciated);

    string returnString = "";

    for (int i = 0; i < length; i++)
        returnString += alphabet[UnityEngine.Random.Range(0, alphabet.Length)];

What I’m having a little trouble with is how to go about checking that each letter in the string is only used once. How would I count the instances of each character in the random string and store that information for when the user submits their word?

For example, if the random string is: “AXSRAETOB”, how would I count the number of 'A’s, 'X’s, etc. and store that to check that no letters have been used more than they should?

Also, for large text files (this one is around 200K lines) is it still best to parse the entire file at the beginning, or is there a way to ‘look up’ the word in the file, or just parse the word to be checked??

Any help would be great.

You can create a container for available letters and used letters… like this.

List<char> availableLetters = new List<char>();
List<char> usedLetters = new List<char>();

To check if a letter is still available, just use…

if( availableLetters.Contains(sampleChar) )

Is it still best to parse the entire file at the beginning? Try it first, if you think you have enough memory to store everything, then go. I think you do. If not, comment, and we’ll look for solutions :wink:

On the same note, for reference reasons:

function occurencesOfChar(st:String, ch : String):int
{//occurences of a character in a string
	var cnt = 0;
	for (c in st) 
		if (c == ch) cnt++;
	}return cnt;