Home > Back-end >  RegEx via Javascript
RegEx via Javascript

Time:02-17

I do not know how to solve this coding puzzle with Javascript. I've never been working with Regular Expressions but I feel they are the best approach to solve it.

Let's say, I have this code:

let str = "abcdefabc";
let pattern = "abc";

What I need is to write the algorithm, that returns the array of arrays (two-dimensional) of indexes like this:

[ 
[1, 2, 3], 
[4, 5, 6], 
[7, 8, 9] 
] 

where indexes are the positions of pattern letters in str. For example, with str = 'abcdefabc' and pattern pattern = 'abc' algo must return such arrays:

  1. [0, 1, 2] (first 'abc' inside str that matches pattern: "abcdefabc");
  2. [6, 7, 8] (last 'abc' inside str that matches pattern: "abcdefabc"); these are obvious examples, but it must return those as well:
  3. [0, 1, 8] because "abcdefabc"
  4. [0, 7, 8] because "abcdefabc"

I hope you got the logic. The order of pattern is important: str = 'fox1423423man_united_x' with pattern ='fox' must return [[0, 1, 2], [0, 1, 21]];

str = 'google with pattern ='fox' must return null because there is no 'fox' somewhere in between;

str = 'xof' with pattern ='fox' must return null because the way the letters go is important;

All strings will be lower-case

CodePudding user response:

Here's a solution that solves it via recursion.
It uses the old indexOf to find the positions of the characters.

function findTokenPositions(str, tokens) {
  let arr = [];
  function recurse (strpos=0, tok=0, accum=[]) {
    if (tok >= tokens.length) { arr.push(accum); return; }
    strpos = str.indexOf(tokens[tok], strpos);
    if (strpos < 0) { return; }
    accum[tok] = strpos;
    recurse(strpos 1, tok 1, [...accum])
    recurse(strpos 1, tok,   [...accum]);
  }
  recurse(0, 0);
  return arr;
}

let tests = [ 
  ["abcdefabc", "abc"], 
  ["fox1423423man_united_x", "fox"], 
  ["hound", "fox"] 
];

tests.forEach(x => {console.log(x[0] ':' x[1] '-->'   JSON.stringify(findTokenPositions(x[0], x[1])))});

  • Related