Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

C++ Programming Using the dictionary of four letter words write a program that w

ID: 3678535 • Letter: C

Question

C++ Programming

Using the dictionary of four letter words write a program that will check a sequence of 4 characters entered from the keyboard to determine if it is a word. Your program should have a function that employs a binary search to look for the word. All words must first be read from the file and stored into an array. There are 4030 words in the dictionary. Your output should indicate whether the word is valid or not. Count the number of comparisons and print that to the screen along with the validity of the word.

The txt file looks something like this :

Explanation / Answer

Code:

input.txt contains the dictionary

#include<iostream>
#include<fstream>
#include<vector>
#include<cstring>
using namespace std;
int comp_count=0;
vector<string> sttok(string str) //used to tokenize string separated by space
{
int i=0;
vector<string> res;
string temp="";
for(i=0;i<str.size();i++)
{

if(str[i]==' ')
{
res.push_back(temp);
temp="";
}
else
{
temp.push_back(str[i]);
}
}
res.push_back(temp);
return res;

}


bool binarySearch(vector<string> array,int size ,string key){
int start=1, end=size;
int mid=(start+end)/2;

while(start<=end && strcmp(array[mid].c_str(),key.c_str())!=0){
comp_count++;
if(strcmp(array[mid].c_str(),key.c_str()) < 0) //tmp.c_str())
{
start=mid+1;
}
else{
end=mid-1;
}
mid=(start+end)/2;
}// While Loop End

if(strcmp(array[mid].c_str(),key.c_str())==0)
return true; //Returnig to main
else
return false;//Returnig to main

cout<<" ";
}// binarySearch Function Ends Here

int main() {

ifstream is("input.txt");
string buffer="";
char c;
while (is.get(c))
buffer+=c;
is.close();
vector<string> words = sttok(buffer);
cout<<"Enter the input word:";
string word;
cin>>word;
for(int i=0;i<words.size();i++)
{
cout<<words[i]<<" ";
}
int size = words[words.size()-1].size();
words[words.size()-1].erase(size-1); //removing from last word
  
  
if(binarySearch(words,words.size() ,word))
{
cout<<"word is found";
cout<<comp_count;
}
else
{
cout<<"word is not found"<<endl;
cout<<"comparison count is: "<<comp_count;
  
}

return 0;
}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote