Hello im currently stuck at the final step of Anagram Finder lesson.
If anyone can help that would be amazing!
This are the prompts to follow:
- Copy and paste the following starting code into your workspace:
#include<stdio.h>#include<string.h>int main() { }
-
Create two integer arrays called
counter1
andcounter2
. Initialize both arrays with four zeros each. -
We will check if the following two strings are anagrams:
- String 1: “dbb cccccaacb cdbababdcdcdab dcdad”
- String 2: “bbbcc bdddccccad cdbbaaacaccdabdd”
Right under your counters, create two char
arrays called s1
and s2
containing String 1 and String 2 respectively.
Counting the characters in String 1.
-
First, create a
for
loop to loop through the string. Usestrlen()
to find the length of the string. -
We will now write the logic to determine the number of each character in String 1.
We will update counter1
in the following way:
- If we encounter an ‘a’ we will increment
counter1[0]
by one. - If we encounter a ‘b’ we will increment
counter1[1]
by one. - If we encounter a ‘c’ we will increment
counter1[2]
by one. - If we encounter a ‘d’ we will increment
counter1[3]
by one. - If we encounter a space, we ignore it.
Implement this logic in the loop body.
Counting the characters in String 2.
- Loop through String 2 and update its counter (
counter2
) accordingly.
Comparing the counts of both strings.
- We need a flag that we can use to determine if there is a mismatch in the two counters.
First, create an integer variable called flag
and set it to 0
.
The flag variable maintains one of these states:
- The flag will be set to zero if there is no mismatch in the counters.
- The flag will be set to one if there is a mismatch in the counters.
-
Create an empty
for
loop that you will use to loop through both counters. We will place logic in it in the next task. -
In the loop, change the
flag
variable’s value to 1 if a mismatch is encountered.
Well, are they anagrams?
- If the two strings are anagrams, print “Anagram!”. If they are not, print “Not Anagram!”
This is my code:
#include <stdio.h>
#include <string.h>
int main (){
//counters a, b, c, d
int counter1 [] = {0,0,0,0};
int counter2 [] = {0,0,0,0};
//strings to compare and verify
char s1 [] = "dcba";
char s2 [] = "aacd";
//flag for verification
int flag = 0;
//verification process s1
for (int i = 0; i < strlen(s1); i++){
if (s1[i] == 'a'){
counter1[0]++;
}
if (s1[i] == 'b'){
counter1[1]++;
}
if (s1[i] == 'c'){
counter1[2]++;
}
if (s1[i] == 'd'){
counter1[3]++;
}
if (s1[i] == ' '){
continue;
}
}
//verification process s2
for (int i = 0; i < strlen(s2); i++){
if (s2[i] == 'a'){
counter2[0]++;
}
if (s2[i] == 'b'){
counter2[1]++;
}
if (s2[i] == 'c'){
counter2[2]++;
}
if (s2[i] == 'd'){
counter2[3]++;
}
if (s2[i] == ' '){
continue;
}
}
//check if they are anagrams
for(int i = 0; i < 4; i++){
if (counter1[i-1] == counter2[i-1]){
flag == 0;
}
else {
flag == 1;
}
}
if (flag == 0){
printf("Anagram!\n");
}
else {
printf("Not Anagram!\n");
}
}