Поиск совпадений в двух массивах с индексом
Я прохожу через испытание мутаций FreeCodeCamp. Вот что я должен сделать:
Возвращает true, если строка в первом элементе массива содержит
все буквы строки во втором элементе массива.
Например, ["hello", "Hello"], должно возвращать true, потому что все
буквы во второй строке присутствуют в первой, игнорируя регистр.
Аргументы ["hello", "hey"] должны возвращать false, так как строка
"привет "не содержит буквы"у".
Наконец, ["чужой", "линия"], должен вернуть true, потому что все
Буквы в " строке "присутствуют в"чужой".
Это мое решение. К сожалению, это не работает, хотя я думаю, что можно решить проблему таким образом. Где же моя ошибка?
Вот код с моими подробными комментариями:
function mutation(arr) {
//indexOf is case sensitive, so first we make all the elements in the array lowerCase. After that we use the lowerCaseArray instead of our original array
var y = arr.join(" ");
var x = y.toLowerCase();
var lowerCaseArray = x.split(" ")
// This variable will contain the number of matches
var matchCounter = 0;
//The for loop picks a letter from the second element
//(lowerCaseArray[1][i]) of an array and then we look
//if a match in the first element of an array(lowerCaseArray[0] is found).
//If there is a match, then the indexOf would return a number >=0.
//In this case we add 1 to our matchCounter.
for (i = 0; i < lowerCaseArray[1].length; i++) {
if(lowerCaseArray[0].indexOf(lowerCaseArray[1][i]) > 0) {
matchCounter+= 1;
}
//Finally we compare the matchCounter length with the second
//element of our array. If matchCounter >= the length of our
//array, it means every letter in the second element was found
//within the first element
}
return matchCounter >= arr[1].length;
}
mutation(["floor", "for"]);
По какой-то причине return lowerCaseArray[1][i]; возвращает 'o', хотя последняя буква второго элемента - "r". И в данном случае Пример matchCount равен 2, но это должно быть 3, потому что есть 3 совпадения. Может быть, это часть с ошибкой.
5 ответов:
Строка, в результате которой ваш код возвращает неверный результат, выглядит следующим образом:
if (lowerCaseArray[0].indexOf(lowerCaseArray[1][i]) > 0) {Он игнорирует возможность того, что искомый символ может находиться в позиции 0.
Изменение
Есть еще несколько мест, где код можно было бы сделать немного менее запутанным. Смотрите ниже:>на>=приводит его к работе. Ваши комментарии фактически указывают, что это должно быть>=, но ваш код использует>.
function mutation(arr) { //indexOf is case sensitive, so first we make all the elements in the array lowerCase. After that we use the lowerCaseArray instead of our original array var lowerCaseArray = arr.map(function (str) { return str.toLowerCase(); }); // the for loop checks each letter in the second string // if any of its letters is not present in the first one, // return false immediately for (i = 0; i < lowerCaseArray[1].length; i++) { if (lowerCaseArray[0].indexOf(lowerCaseArray[1][i]) === -1) { return false; } } // if the for loop completed without returning, then the strings pass the test. return true; } console.log(mutation(["floor", "for"]));
Необходимо проверить на неравенство
-1, так как ноль0является допустимым индексом строки.if (lowerCaseArray[0].indexOf(lowerCaseArray[1][i]) !== -1) { // ^^^^^^
function mutation(arr) { var y = arr.join(" "), x = y.toLowerCase(), lowerCaseArray = x.split(" "), matchCounter = 0, i; for (i = 0; i < lowerCaseArray[1].length; i++) { if (lowerCaseArray[0].indexOf(lowerCaseArray[1][i]) !== -1) { matchCounter += 1; } } return matchCounter >= arr[1].length; } console.log(mutation(["floor", "for"]));
В качестве альтернативы можно также использовать
regex. Это также избавит вас от необходимости подбирать подходящий случай.Пример
function validate(arr){ var regex_str = arr[0].replace(/[^a-z0-9 ]/gi, function(m){ return "\\" + m }) var regex = new RegExp("^[" + regex_str + "]*$", "i"); var valid = regex.test(arr[1]); console.log(regex, "|", arr[1], "|", valid) return valid } validate(["floor", "for"]) validate(["floor", "fora"]) validate(["heworld", "hello World "]) validate(["heworld", "hello World "]) validate(["heworldts(*) ", "hello World (test *)"])
Попробуйте этот один раз матч ("пой", "певец").
var match=function(a,b) { var nomatch=0; var w1=a.toLowerCase(); var word1=w1.split(''); var string2=b.toLowerCase(); console.log('word1 len : '+word1.length+' '+string2+' length : '+string2.length); for(var i=0;i<word1.length;i++) { if(string2.indexOf(word1[i])==-1) { console.log('no match : '+b+' .indexOf('+word1[i]+')'); nomatch +=1; } else { console.log('match : '+b+'.indexOf('+word1[i]+')'); } } if(nomatch>0) { console.log(b+' does not have all characters of '+a); } else { console.log(b+' do have all characters of '+a); } } match('hello','Hell');
Comments