# Consider this data sequence: “fish bird reptile reptile bird bird bird mammal fish”.

1

### CHALLENGE:

Consider this data sequence: “fish bird reptile reptile bird bird bird mammal fish”.
Let’s define a SINGLETON to be a data element that is not repeated immediately before or after itself in the sequence.
So, here there are four SINGLETONs (the first appearance of “fish”, the first appearance of “bird”, “mammal”, and the second appearance of “fish”).
Write some code that uses a loop to read a sequence of words, terminated by the “xxxxx”.
The code assigns to the variable n the number of SINGLETONs that were read. (For example in the above data sequence it would assign 4 to n.) Assume that n has already been declared. but not initialized. Assume that there will be at least one word before the terminating “xxxxx”.

ASSUME the availability of a variable , stdin, that references a Scanner object associated with standard input.

### SOLUTION:

```char prev[MAX_SIZE] = "";
char curr[MAX_SIZE] = "";
char next[MAX_SIZE] = "";
int n; // declaration of n
int singletons = 0;

printf("Enter a sequence of words, terminated by the 'xxxxx'.\n");
printf("There will be at least one word before the terminating 'xxxxx'.\n");
printf("> ");

scanf("%s", curr);

do
{
scanf("%s", next);

if(strcmp(prev, curr) != 0 && strcmp(curr, next) != 0)
singletons++;

strcpy(prev, curr);
strcpy(curr, next);
}while(strcmp(next, SENTINAL) != 0);

n = singletons;

printf("\nNumber of SINGLETONs: %d\n", n);

```

#### One comment

• j p says:

Use this:

n = 0;
String word1, word2, word3;
word3 = stdin.next();
word2 = stdin.next();
word1 = stdin.next();
if (!(word3.equals(word2)))
n++;
if (!(word2.equals(word3)) && (!(word2.equals(word1))))
n++;
while (!(word1.equals(“xxxxx”)) && (stdin.hasNext()))
{
word3 = word2;
word2 = word1;
word1 = stdin.next();
if (!(word2.equals(word3)) && (!(word2.equals(word1))))
n++;
}