swang / markovchain

generates a markov chain of words based on input files
50 stars 8 forks source link

Sentence generation able to be put in infinite loop #7

Open dootbar opened 5 years ago

dootbar commented 5 years ago

In the main file, index.js, the process() function's while loop is able to hang there infinitely if two chain words can only step forward to each other. Example if foo is only able to go to bar, and if bar is only able to go to foo foo->bar bar->foo having this will result in infinite sentence with alternating of the two words

I've currently not tested if this can happen in larger chains, for example if foo can only go to bar can only go to biz can only go to foo (or if it's even possible) NOT tested: foo->bar bar->biz biz->foo

my current fix was to simply make a variable that was the previous word, then check if there was only one key for the current word, and if it was equal to the previous word. if it was, then break and return the sentence, if not then continue.

here is the loop with my fix, so far it has worked fine for me and fixed the infinite looping, although I have not extensively tested it:

key: 'process',
    value: function process() {
      var curWord = this.startFn(this.wordBank);
      var prevWord = "";
      this.sentence = curWord;
      while (this.wordBank[curWord] && !this.endFn()) {

        curWord = pickOneByWeight(this.wordBank[curWord]);

        if (this.wordBank[curWord] && Object.keys(this.wordBank[curWord]).length == 1 && Object.keys(this.wordBank[curWord])[0] == prevWord) {
          console.log(true); //infinite loop detected
          return this.sentence;
        }
        this.sentence += ' ' + curWord;
        prevWord = curWord;
      }
      return this.sentence;
    }