Skip to content

Instantly share code, notes, and snippets.

@juanfal
Created January 8, 2024 17:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save juanfal/9d0976768a7044460b5b65b6198f3b69 to your computer and use it in GitHub Desktop.
Save juanfal/9d0976768a7044460b5b65b6198f3b69 to your computer and use it in GitHub Desktop.
distance between repeated words
// x2.maxdistrepwords.cpp
// juanfc 2024-01-08
//
// The \textbf{distance between two words} in a text is the number of words in
// between them. Build an algorithm that reads from keyboard a sequence of words
// and then print on the screen the maximum distance between repeated words.
// Words that are no repeated will not appear in the output.
#include <iostream>
#include <array>
using namespace std;
const int MAX_PAL_DIST=100;
struct TWordPos {
string word;
int lastPos, maxDist;
};
typedef array<TWordPos,MAX_PAL_DIST> TWordPosList;
void addWord(TWordPosList& wl, string w, int pos);
void printWordList(TWordPosList wl);
int main()
{
TWordPosList wl;
int pos = 0;
string word;
// can you can a can as a canner can can a can end
while ( cin >> word and word != "end" ) {
++pos;
addWord(wl, word, pos);
}
printWordList(wl);
return 0;
}
int posInList(TWordPosList wl, string word);
void addNewWord(TWordPosList& wl, string w, int pos);
void addWord(TWordPosList& wl, string w, int pos)
{
int i=0;
while ( wl[i].word.length() > 0 and wl[i].word != w )
++i;
if (wl[i].word.length() > 0) {
int disTemp = pos - wl[i].lastPos;
if (wl[i].maxDist < disTemp)
wl[i].maxDist = disTemp;
wl[i].lastPos = pos;
} else {
wl[i].word = w;
wl[i].lastPos = pos;
wl[i].maxDist = 0;
}
}
void printWordList(TWordPosList wl)
{
int i = 0;
while ( wl[i].word.length() > 0 ) {
if (wl[i].maxDist > 0) {
cout << wl[i].word << ": ";
cout << wl[i].maxDist << endl;
}
++i;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment