write a program that lets the user enter a word and then output all the words co
ID: 3683812 • Letter: W
Question
write a program that lets the user enter a word and then output all the words contained in the file words.txt that can be formed from the letters of the entered word. one algorithm o do this is to compare the letter histograms for each word.create and array that counts up the number of each letter in the entered word (e.g., one S, one W, two I, two M, etc.) and then creates a similar array for the current word read from the file. the two arrays can be compared to see if the word from the file could be created out of the letters from the entered word. ( i have been trying to figure this out for a while now. i am using c++ if anybody could show me so i can see how its done that would be great. the words.txt document is just a list of words and its to large to put in this.)
Explanation / Answer
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int main()
{
//variable declarations
ifstream infile;
string data[100000], master, word;
int master_array[26], temp_array[26];
bool can_be_formed;
int total_count = 0, i = 0, j;
/*
master_array and temp_array will store count of letters.
they have only 26 because there are 26 alphabets in english
for eg. master_array[0] will store no. of 'a' occuring in
user given word and temp_array[0] will store no. of 'a'
occuring in a particular word of "words.txt" file. Now
if it has to be formed from the user given word then
all the count of letters in temp_array should be less than
all of the count in master_array
*/
//input from file
infile.open("words.txt");
while(infile>>word)
{
data[i++] = word;
total_count += 1;
}
//asking user for the word
cout<<"Enter a word (in lowercase) : ";
cin>>master;
//counts up the number of each letter in the entered word
for(i=0;i<26;i++)
master_array[i] = 0;
for(i=0;i<master[i]!='';i++)
{
if(master[i]>='A'&&master[i]<='Z')
master[i] = master[i] + 32;
if(master[i]>='a'&&master[i]<='z')
master_array[master[i]-'a'] += 1;
}
//creating a similar array for the current word read from the file.
for(i=0; i<total_count; i++)
{
for(j=0;j<26;j++)
temp_array[j] = 0;
for(j=0;data[i][j]!='';j++)
temp_array[data[i][j]-'a'] += 1;
can_be_formed = true;
for(j=0;j<26;j++)
if(master_array[j]<temp_array[j])
{
can_be_formed = false;
break;
}
if(can_be_formed)
cout<<data[i]<<endl;
}
infile.close();
return 1;
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.