Найдите пропущенную букву в массиве
Я пытаюсь создать функцию, которая принимает массив ввода последовательных символов в алфавите и возвращает пропущенную букву, если она есть (будет только 1 пропущенная буква, и каждый элемент в массиве будет перечислен в алфавитном порядке).
Пример входных данных:
['a', 'b', 'c', 'e'] -> 'd'
['l', 'n', 'o', 'p'] -> 'm'
['s', 't', 'u', 'w', 'x'] -> 'v'
const findMissingLetter = () => {
const stepOne = (array) => {
for (let i = 0; i < array.length; i++) {
let x = array.charCodeAt(i + 1);
let y = array.charCodeAt(i);
if ((x - y) != 1) {
return (array.charCodeAt[i] + 1);
}
}
}
}
return findMissingLetter(stepOne.fromCharCode(array));
Я пытаюсь выполнить цикл по каждому индексу массива и преобразовать каждый символ в юникод. Если элементы [i + 1] - [i] в массиве равны 1, то пропущенные буквы отсутствуют. Однако, если он не равен 1, то я хочу вернуть юникод [i] + 1, а затем через функцию более высокого порядка преобразовать выходные данные юникода обратно в соответствующий символ в алфавите.
Может кто-нибудь объяснить, пожалуйста, что я делаю не так? Я знаю, что неправильно вызываю функции.
Спасибо!
4 ответа
Строковый метод .charCodeAt()
не работает на массивах. Вам нужно использовать его для каждого символа и получить код в позиции 0 (по умолчанию):
const findMissingLetter = (array) => {
// we can skip the 1st letter
for (let i = 1; i < array.length; i++) {
// get the char code of the previous letter
const prev = array[i - 1].charCodeAt();
// get the char code of the current letter
const current = array[i].charCodeAt();
if (current - prev !== 1) { // if the difference between current and previous is not 1
// get the character after the previous
return String.fromCharCode(prev + 1);
}
}
return null; // if nothing is found
}
console.log(findMissingLetter(['a', 'b', 'c', 'e'])); // d
console.log(findMissingLetter(['l', 'n', 'o', 'p'])); // m
console.log(findMissingLetter(['s', 't', 'u', 'w', 'x'])); // v
console.log(findMissingLetter(['a', 'b', 'c'])); // null
И еще одно решение, которое использует Array.findIndex()
найти пропавшего персонажа:
const findMissingLetter = (array) => {
const index = array
.slice(1) // create an array with 1st letter removed
.findIndex((c, i) => c.charCodeAt() - array[i].charCodeAt() > 1); // compare current letter and the same index in the original array 'till you find a missing letter
return index > -1 ? // if we found an index
String.fromCharCode(array[index].charCodeAt() + 1) // if index was found return next letter after the last letter in a sequence
:
null; // if index wasn't found
};
console.log(findMissingLetter(['a', 'b', 'c', 'e'])); // d
console.log(findMissingLetter(['l', 'n', 'o', 'p'])); // m
console.log(findMissingLetter(['s', 't', 'u', 'w', 'x'])); // v
console.log(findMissingLetter(['a', 'b', 'c'])); // null
Я пришел с таким решением:
const alphabet = 'abcdefghijklmnopqrstuvwxyz'.split('');
const findMissing = (arr) => {
const start = alphabet.indexOf(arr[0]);
const end = alphabet.indexOf(arr[arr.length-1]);
const sliced = alphabet.slice(start, end + 1);
return sliced.filter((letter) => !arr.includes(letter));
};
console.log(findMissing(['a','b','c','e','h']));
console.log(findMissing(['h','j','l','p']));
console.log(findMissing(['s','t','v','z']));
Это вернет массив отсутствующих букв между начальной и конечной буквой алфавита.
Вы можете использовать
charCodeAt
, но для (односимвольных) строк в массиве:
Используя английские буквы, вы можете использовать массив с буквами и проверять каждую букву в переданном массиве.
let findMissing = (arr) => {
let alpha = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'];
let j = alpha.indexOf(arr[0]);
for (let i = 0; i < arr.length; i++) {
if (arr[i].toUpperCase() !== alpha[j].toUpperCase()) return alpha[j];
j++;
}
return "";
}
console.log(findMissing(['a', 'b', 'c', 'e']));
console.log(findMissing(['l', 'n', 'o', 'p']));
console.log(findMissing(['s', 't', 'u', 'w', 'x']));
console.log(findMissing(['s', 't', 'u', 'v', 'w']));