@Quintis

Как оптимизировать код?

Доброго времени суток , решил небольшую задачку на codewars - https://www.codewars.com/kata/5aaae0f5fd8c069e8c00... но решение не верно потому что не все тесты успевают пройти за 12000 ms: " If you see this error multiple times you should try to optimize your code further."Как его оптимизировать ?

function compoundMatch(words, target) {
  let result = null
  let i,index,firstWord,secondWord
  let arrWordsLength = words.length

marck:for(i=0;i<arrWordsLength;i++) {
      index = words[i].length
      firstWord = target.slice(0,index)
      secondWord =target.slice(index) 
      let firstWordIndex = words.indexOf(firstWord)
      let secondWordIndex = words.indexOf(secondWord)
      if (words[i] === firstWord && firstWordIndex>=0 && secondWordIndex >=0 ){
      let firstWordInArr = Math.min(firstWordIndex,secondWordIndex)
      let secondWordInArr = Math.max(firstWordIndex,secondWordIndex)
      console.log(firstWordInArr,secondWordInArr)
      result=[words[firstWordInArr],words[secondWordInArr],[firstWordIndex,secondWordIndex]]
      break marck
      }

};
return result
}
  • Вопрос задан
  • 135 просмотров
Решения вопроса 1
0xD34F
@0xD34F Куратор тега JavaScript
function compoundMatch(words, target) {
  const pairs = [];

  for (let i = 1; i < target.length; i++) {
    pairs.push([ target.slice(0, i), target.slice(i) ]);
  }

  for (const [ a, b ] of pairs) {
    const ia = words.indexOf(a);
    const ib = words.indexOf(b);

    if (ia !== -1 && ib !== -1) {
      return ia < ib ? [ a, b, [ ia, ib ] ] : [ b, a, [ ia, ib ] ];
    }
  }

  return null;
}

или

function compoundMatch(words, target) {
  const indices = {};

  for (let i = 0; i < words.length; i++) {
    const a = words[i];
    if (!indices.hasOwnProperty(a)) {
      indices[a] = i;

      const b = target.replace(a, '');
      if (indices.hasOwnProperty(b)) {
        return [ b, a, a + b === target ? [ i, indices[b] ] : [ indices[b], i ] ];
      }
    }
  }

  return null;
}

или

function compoundMatch(words, target) {
  const indices = {};

  for (let i = 0; i < words.length; i++) {
    indices[words[i]] = i;
  }

  for (const a in indices) {
    for (const b in indices) {
      if (a + b === target) {
        return indices[a] < indices[b]
          ? [ a, b, [ indices[a], indices[b] ] ]
          : [ b, a, [ indices[a], indices[b] ] ];
      }
    }
  }

  return null;
}
Ответ написан
Комментировать
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы