DEV Community

Discussion on: Daily Challenge #232 - Regex Pattern

Collapse
 
craigmc08 profile image
Craig McIlwrath

I'm not sure why you would want to implement this as a regular expression. There's no compact way (that I could think of) to represent those rules as a regular language. Here's my solution, in javascript.

function permutations(list) {
  if (list.length === 1) return [list];
  const xs = [];
  for (let i = 0; i < list.length; i++) {
    const tails  = permutations(list.filter((y, j) => j !== i));
    xs.push(...tails.map(ys => [list[i], ...ys]));
  }
  return xs;
}

function regexContainsAll(chars) {
  const regex = permutations(chars.split(''))
    .map(pattern => `^.*${pattern.join('.*')}.*$`)
    .join('|');
  return regex;
}

For example, input 'abc' produces the string 'a.*b.*c|a.*c.*b|b.*a.*c|b.*c.*a|c.*a.*b|c.*b.*a'.

As a side note, why do all of these challenges have "tests" that don't include expected results? It doesn't help me understand the question if they don't tell me what the function is supposed to do...