Given a sequence and key, create a function to find out if the characters in the sequence appear in the order of the key

Viewed 72

Given two strings a sequence string and a key string. create a function determine if characters of key appear in order in the sequence string. "arcata" & "cat" or "c1a2t3" & "cat" will return true while "cta" will return false

created a nested loop to create a new str and then compared the new str to the key.

function sequenceSearch(sequence, key) {
  var str = "";
  for (var i = 0; i < key.length; i++) {
    var keyChar = key[i]
    for (var j = 0; j < sequence.length; j++) {
      var char = sequence[j];
      if (char === keyChar) {
        if (str.indexOf(char) === -1) {
          str += char;
        }
      } 
    }
  }
  return str === key;
}

"c1a2t3" & "cat" should be true but i get false; "cta", "cat" should be false but i get true

3 Answers

This can be done pretty easily by converting your key to a regular expression, then checking if your sequence matches it:

var key = "cat"; // or whatever
var sequence = "c1a2t3"; // or whatever
var r = ".*" + key.split("").join(".*") + ".*"; // makes string representation of regex of .*c.*a.*t.*
var valid = sequence.match(r);

Without regex or foreach use reduce

function reduceKey(acc, letter, i) {
  const {sequence = ''} = acc;
  const [, ...rest] = sequence.split(letter);
  const remainingSequence = rest.join(letter);
  const isLetterFound = remainingSequence !== undefined;
  console.log(`${i} - ${letter}: ${sequence} split to => ${remainingSequence}`)
  return {
    result: isLetterFound,
    sequence: remainingSequence
  }
}

function sequenceSearch(sequence, key) { 
  const init = {
   sequence
  };
  const {result } = key.split('').reduce(reduceKey, init);
  return result;
}

console.log('c1a2', sequenceSearch('c1a2', 'cat'))
console.log('c1a2t', sequenceSearch('c1a2t', 'cat'))
console.log('cat2', sequenceSearch('cat2', 'cat'))
console.log('caxat2', sequenceSearch('caxat2', 'cat'))

for each letter in key, split the sequence.

Strip away the sequence letters before key letter.

Continue reduce with remaining Sequence

If final key letter can split the sequence, we have a match and return result: true;

Related