Rosetta Code - Execute a Markov algorithm

Tell us what’s happening:
Is the test set correct?

For one of the examples/tests the input is markov(["A -> apple","B -> bag","S -> .shop","T -> the","the shop -> my brother","a never used -> .terminating rule"],"I bought a B of As from T S."). Following the markov algorithm my code produces '‘I bought a bag of apples from the .shop.’, but the test expects ‘I bought a bag of apples from T shop.’. Why is the ‘T’ not getting replaced?

Your code so far

function markov(rules,data) {
  let ruleTuples = rules.map(ruleString => ruleString.split(' -> '));
  let processing = true;
  while(processing){
    let matched = false;
    for(let i = 0; i < ruleTuples.length; i++){
      let ruleMatchString = ruleTuples[i][0];
      let ruleIndex = data.indexOf(ruleMatchString);
      if(ruleIndex != -1){
        matched = i < ruleTuples.length - 1;
        data = data.substring(0, ruleIndex) +
          ruleTuples[i][1] +
          data.substring(ruleIndex + ruleTuples[i][0].length);
        break;
      }
    }
    if(!matched){
      processing = false;
    }
  }
  return data;
}
markov([
  "A -> apple",
  "B -> bag",
  "S -> .shop",
  "T -> the",
  "the shop -> my brother",
  "a never used -> .terminating rule"
],
"I bought a B of As from T S.")

Your browser information:

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/113.0.0.0 Safari/537.36

Challenge: Rosetta Code - Execute a Markov algorithm

Link to the challenge:

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.