Check for duplicates in cstring

Hello all. I am writing a hangman game and have run across a problem. Basically, I am keeping track of the letters the user has entered to prevent the repeating of a letter. In the code I have, I can only check adjacent letters but that's it. So if the letter array is "aba" the second 'a' wouldn't be caught. Here is the function.
1
2
3
4
5
6
7
bool checkLetter(char letter[])
{
	for(unsigned int index=0;index<strlen(letter)-1;index++) //loop only checks adjacent characters. Not sure how to check all 
		if(letter[index]==letter[index+1])
			return false;
	return true;
}



EDIT:
the array to store the letters is char letter[26];
Last edited on
Maybe this method is overkill, but I would personally use a "binary tree". Read up on it: Page 124-127 on K&R.

A binary tree basically counts how many occurrences of each word pops up while running through an input. If that count exceeds 1, retry the input.
Last edited on
A simple but slow solution:

Get an array of 26 characters. For each character read in, scan through the entire array and see if it's been recorded there. If it's not, record it. If it has, then it's a duplicate.


A more complex but faster solution:

Get an array of 26 bools (in C, chars). For each character read it, check a space in the array that records information for *only* that character (example: make [0] record info for A/a, [1] for B/b, and so on). If the boolean is false, set it to true, and if it was true, it's a duplicate.

-Albatross

Last edited on
Ok got it to work. Here is the updated function. I would post the entire hangman code I wrote but it exceeds the limit. (My hangman pictures take up too much lines).

1
2
3
4
5
6
7
8
9
bool checkLetter(char letter[], unsigned int i) //variable i is the index of letter
{
	for(unsigned int index=0;index<strlen(letter);index++)
		if(index==i) //avoid comparing the character itself
			continue;
		else if(letter[index]==letter[i])
			return false; //duplicate was found, so false is returned
	return true; //duplicate wasn't found
}


Albatross, I followed your first suggestion so I think this is what you meant..
Topic archived. No new replies allowed.