There is a file, words are written in it. From the keyboard, enter the word with non-repeating letters. Find and display a word from a file in which you will find the most letters from a word entered from the keyboard. I just can’t figure out how to implement this in the program ... Someone, please tell me the possible algorithm, preferably without using sophisticated procedures and little-known libraries. What is better to use: thong or enchantment?

    4 answers 4

    An example of a function that returns the number of matching characters in string s from the string sub :

     size_t overlap(const string& s, const string& sub) { size_t k = 0, sz = sub.size(); for (size_t n = 0; n < sz; ++n){ k += std::count(s.begin(), s.end(), sub[n]); } return k; } 

    Try to write the program yourself.

      Enter the word, add characters from the word to std::set

      For each word in the file, calculate how many characters from it are in the set.

      • Why is std :: string not a sequence of characters? - AR Hovsepyan
      • @AR Hovsepyan This question to me or is it rhetorical? - MBo
      • The question is - what is set for? - AR Hovsepyan
      • @AR Hovsepyan For a simple comparison, good for the time (not the best). Solution options are many. This will take only a few lines, uses STL, and not "little-known libraries", which the author does not want, does not require a lot of memory, and is fast enough. - MBo
      • @AR Hovsepyan do not tell me how to calculate how many characters in a word are in a string? - ubuntu beginner

      Enter the sample word. In the loop, until you get a rejection, read the file word for word, using fscanf (). Then for each letter of the word check if it is contained in the sample? using strchr (). If contained, add to the counter. If the word contains more characters from the pattern than the previous one, save it. When all the words in the file are read, the one you need will be saved. Sample code that works in both C and C ++. It was too lazy to enter the sample word, and I scored it in the array — for debugging and demonstration of an example, it’s enough.

       #include <stdio.h> #include <stdlib.h> #include <errno.h> #include <ctype.h> #include <string.h> int main(int argc, char *argv[]) { FILE *ifile; if (NULL == (ifile = fopen(argv[1], "r"))) { perror(argv[1]); exit(errno); } int n = 0; int nmax = 0; char *ss; char smpl_word[] = "sample_word"; char next_word[1024]; char most_word[1024]; // читаем файл словами while (1 == fscanf(ifile, "%1023s", next_word)) { // сканируем для каждой буквы полученного слова факт // вхождения в smpl_word ss = next_word; n = 0; do { // scanf никогда не возвращает пустых строк if (strchr(smpl_word, *ss++)) { n++; // и отмечаем если входит } } while (*ss); // проверка на превышение количеств вхождений if (n > nmax) { nmax = n; strcpy(most_word, next_word); } } // собственно, и все на этом fprintf(stdout, "%s\n", most_word); return 0; argc++; } 
         #include <iostream> #include <string> #include <algorithm> #include <fstream> using namespace std; int getRateWordByPattern(const string& word, const string& pattern) { int rate = 0; for (int i = 0; i < pattern.size(); ++i) rate += std::count(word.begin(), word.end(), pattern[i]); return rate; } void main() { string pattern = "ght"; ifstream f; f.open("D://1.txt"); if (!f.is_open()) return; int max_rate = 0; string res_word = "not found"; string word; while (f >> word) { int rate = getRateWordByPattern(word, pattern); if (rate > max_rate) { max_rate = rate; res_word = word; } } cout << max_rate << endl; cout << res_word << endl; char ch; cin >> ch; } 

        Threw here on the knee. No error handling, the data is all scored hardcore. Word with letters to search in the pattern variable.

        In the file I have a line of the form: one two three four five six seven eight nine ten.

        Data entry, validation and error handling embed himself and everything.

        PS As far as optimization is concerned, I see two ways, either to analyze the file in advance and build metadata based on it, or more intelligently calculate the rating. As for the latter, you need to think more.

        • Could you explain how the string "for each (char pattern_ch in pattern)" works? - ubuntu beginner
        • I used the Visual C ++ 17 compiler, it supports this design. In general, the CLR construct itself, read C #. Checked on gcc and clang compilers - do not understand. - Tananndart
        • C ++ 11 standard introduced range-based loops, the canonical syntax: for (auto& val : container) {...} The difference from the standard form is that this construction works through iterators. Updated example, so as not to confuse. To paint the differences in one comment - the characters are not enough. It is better for you to read separately. - Tananndart 6:51 pm
        • OMG, how badly I know C ++ and all kinds of IDEs ...) Thanks for the edit, now it's much clearer! - ubuntu beginner