Специалисты по JavaScript
238
58
peryevd сказал(а):↑Я бы сделал так
кодlet str = "Woof-woof-woof-woof-woof-woof!Woof-woof-woof-woof-woof! Woof-woof-woof-woof-woof! Woof-woof-woof-woof! Woof-woof-woof-woof-woof-woof-woof-woof-woof-woof-woof-woof-woof! Woof-woof-woof-woof-woof"
//алфавит
let alph = 'abcdefghijklmnopqrstuvwxyz'
//преобразуем строку в массив, состоящий из строк до знака "!"
let arr = str.toLowerCase().split("!"), res = ''
//проходимся по массиву строк, подсчитываем количество совпадений с woof, передаем это количество в массив с алфавитомfor (let i = 0; i < arr.length; i++){ res += alph&arr&i].match(/woof/g).length-1]}
console.log(res)
Нажмите, чтобы раскрыть...Ты рассмотрел только один проверочный способ?
Ник пользователя сказал(а):↑Ты рассмотрел только один проверочный способ?
Нажмите, чтобы раскрыть...
Не совсем понял о чем ты, если ты имеешь ввиду проверки на неправильные строки то да, я этим не занимался. Но это не составит труда - проверить что строка пустая, или что woof больше чем букв в алфавите, или что в строке вообще нет woof
peryevd сказал(а):↑
Не совсем понял о чем ты, если ты имеешь ввиду проверки на неправильные строки то да, я этим не занимался. Но это не составит труда - проверить что строка пустая, или что woof больше чем букв в алфавите, или что в строке вообще нет woof
Нажмите, чтобы раскрыть...Чел прости, а где твой код?
Ник пользователя сказал(а):↑Ды ты смеёшься, он же не работает!
Нажмите, чтобы раскрыть...
слева код, справа вывод
https://imgbb.com/dGF4gN6
peryevd сказал(а):↑
слева код, справа вывод
https://imgbb.com/dGF4gN6Нажмите, чтобы раскрыть...Ты проверил всего одно выражение а их там 10
YoshkinKot сказал(а):↑а мне вот интересно что авторы полагают должна вывести программа, если на вход дали нечто вроде: "woof-!woof!"
aa?
b?
Это "b"
Нажмите, чтобы раскрыть...
Ник пользователя сказал(а):↑Нажмите, чтобы раскрыть...Это "a"
Ник пользователя сказал(а):↑
Либо "b" Либо задание сломано
Нажмите, чтобы раскрыть...
Ник пользователя сказал(а):↑На восклицательном знаке кончается отсчёт
Задание не сломаноНажмите, чтобы раскрыть...
Ник пользователя сказал(а):↑Заранее извиняюсь перед богами программирования в первую очередь. Я совсем новичок и вот такое "Kata" встретил:
Justin has an exceptionally smart dog. In the latest show of its unparalleled intelligence, the dog learned to communicate human words. To do that, it woofs the exact number of times it takes to get to the right letter in the English alphabet. For example, if the dog is interested in the letter "A", it woofs just one time, if it's "B", it woofs two times and so on. Justin is amazed by his pet, but he also finds it challenging to translate the woofs in his head. Write a decoder for him that takes a string of hyphen-separated woofs and returns their human-language representation
Things to keep in mind:
Each valid woof sequence stands for one letter. All of them are guaranteed to end with an exclamation point. A space, on the other hand, is not guaranteed to follow
Justin's audio recorder is not a very good one. Sometimes, it inserts some random sounds that should be ignored. With that in mind, a woof is any sequence of letters that has a "w", an "o", another "o", and an "f" – in that order but not necessarily consecutively and irrespective of the case. If a string has no valid woof sequences, the method should return "nothing to decode!"
Albeit a smart one, Justin's dog is still a dog. Sometimes, it just wants to bark! If the number of woofs in any woof sequence exceeds the number of letters in the English alphabet, you should return "just barking!"
Justin's dog has not yet learned the concept of spaces. The strings may represent more than one human word, but the returned string should not contain any white space characters
While input strings may contain letters of either case, the returned strings should be always in lower case
Examples:
"Woof-woof-woof-woof-woof-woof-woof-woof! Woof-woof-woof-woof-woof-woof-woof-woof-woof!" → "hi"
"Woof-woof-woof-woof-woof-woof!Woof-woof-woof-woof-woof! Woof-woof-woof-woof-woof! Woof-woof-woof-woof! Woof-woof-woof-woof-woof-woof-woof-woof-woof-woof-woof-woof-woof! Woof-woof-woof-woof-woof!" → "feedme"
"Woof-woof-woof-woof-woof-woof-woof-woof-woof-woof-woof-woof-woof-woof-woof-woof-woof-woof-woof-woof-woof-woof-woof-woof-woof-woof-woof!" → "just barking!"
"Shhhh!" → "nothing to decode!"
"WoofWoof!" → "a"
"Shhhhwoof!" → "a"
"Woofshhh! Shhh!" → "a"
"Wofowof!" → "a"
"khkhkhWbzzzzobzzzOghrrrrfseswsw!" → "a"
Я, как полный новичок, думал над этим 3 дня. Трое суток, чёрт возьми. Сложность там на уровне 6 (самое сложное 1, самое лёгкое 8)
То есть, задачка для совсем новичков. Моё решение составило в районе 100 строк, а решение от нормальных людей там в 3 строки.
Собственно, прошу ребят шарящих объяснить, как коротко решить эту задачку. Желательно, код с разъяснениями действий. Хочу словить минусов и разъяснений в решении. Это того стоит.
Хотя бы пойму, как люди это в 3-4 строки решают...Нажмите, чтобы раскрыть...тоесть ты совсем новичек в JS, но пошел решать задачки, которые требуют знаний. Темболее 6 уровня, а это уже не начальный уровень. Гениально
Ник пользователя сказал(а):↑Заранее извиняюсь перед богами программирования в первую очередь. Я совсем новичок и вот такое "Kata" встретил:
Justin has an exceptionally smart dog. In the latest show of its unparalleled intelligence, the dog learned to communicate human words. To do that, it woofs the exact number of times it takes to get to the right letter in the English alphabet. For example, if the dog is interested in the letter "A", it woofs just one time, if it's "B", it woofs two times and so on. Justin is amazed by his pet, but he also finds it challenging to translate the woofs in his head. Write a decoder for him that takes a string of hyphen-separated woofs and returns their human-language representation
Things to keep in mind:
Each valid woof sequence stands for one letter. All of them are guaranteed to end with an exclamation point. A space, on the other hand, is not guaranteed to follow
Justin's audio recorder is not a very good one. Sometimes, it inserts some random sounds that should be ignored. With that in mind, a woof is any sequence of letters that has a "w", an "o", another "o", and an "f" – in that order but not necessarily consecutively and irrespective of the case. If a string has no valid woof sequences, the method should return "nothing to decode!"
Albeit a smart one, Justin's dog is still a dog. Sometimes, it just wants to bark! If the number of woofs in any woof sequence exceeds the number of letters in the English alphabet, you should return "just barking!"
Justin's dog has not yet learned the concept of spaces. The strings may represent more than one human word, but the returned string should not contain any white space characters
While input strings may contain letters of either case, the returned strings should be always in lower case
Examples:
"Woof-woof-woof-woof-woof-woof-woof-woof! Woof-woof-woof-woof-woof-woof-woof-woof-woof!" → "hi"
"Woof-woof-woof-woof-woof-woof!Woof-woof-woof-woof-woof! Woof-woof-woof-woof-woof! Woof-woof-woof-woof! Woof-woof-woof-woof-woof-woof-woof-woof-woof-woof-woof-woof-woof! Woof-woof-woof-woof-woof!" → "feedme"
"Woof-woof-woof-woof-woof-woof-woof-woof-woof-woof-woof-woof-woof-woof-woof-woof-woof-woof-woof-woof-woof-woof-woof-woof-woof-woof-woof!" → "just barking!"
"Shhhh!" → "nothing to decode!"
"WoofWoof!" → "a"
"Shhhhwoof!" → "a"
"Woofshhh! Shhh!" → "a"
"Wofowof!" → "a"
"khkhkhWbzzzzobzzzOghrrrrfseswsw!" → "a"
Я, как полный новичок, думал над этим 3 дня. Трое суток, чёрт возьми. Сложность там на уровне 6 (самое сложное 1, самое лёгкое 8)
То есть, задачка для совсем новичков. Моё решение составило в районе 100 строк, а решение от нормальных людей там в 3 строки.
Собственно, прошу ребят шарящих объяснить, как коротко решить эту задачку. Желательно, код с разъяснениями действий. Хочу словить минусов и разъяснений в решении. Это того стоит.
Хотя бы пойму, как люди это в 3-4 строки решают...Нажмите, чтобы раскрыть...Кинь ссылку на codewars.
Ник пользователя сказал(а):↑Это решение работает просто после выполнения "Kata" дают посмотреть как другие его сделали. И там 3 строки. Вот такие:
function woofDecoder(s) {
const ms = s.toLowerCase().match(/w[^!-]*?o[^!-]*?o[^!-]*?f[^!-]*?[-!]/g) || []
const arr = ms.join('').split('!').map(s=>s&&s.split('-').length)
return arr.some(n=>n>26) ? "just barking!"
: arr.map(w=> w && String.fromCharCode(w+96) ).join('') || 'nothing to decode!'
И тяжело разобраться
Нажмите, чтобы раскрыть...Это через regex (регулярные выражения).
Ник пользователя сказал(а):↑То есть, задачка для совсем новичков. Моё решение составило в районе 100 строк, а решение от нормальных людей там в 3 строки.
Нажмите, чтобы раскрыть...Работает и ладно.
Те кто делают за 3 строки - хорошо кодят и используют такие задачки для разогрева.
В целом, если 1 день не можешь решить - пропускай и ищи задачу легче.
Накидал за минут 10 в развёрнутом варианте, чтобы тебе было понятно, что, куда и зачем
const alph = 'abcdefghijklmnopqrstuvwxyz'
function decodeWoof (woofs) {
const letters = woofs.split('!').reduce(reduceWoof, [])
if (letters.length === 0) {
return 'nothing to decode!'
}
const humanLanguage = letters.reduce(transformWoofToLetter, '')
if (humanLanguage.length === 0) {
return 'just barking!'
}
return humanLanguage
}
function reduceWoof (result, str) {
const woofs = str.split('-').filter(isWoofReal)
if (woofs.length > 0) {
result.push(woofs.length)
}
return result
}
function isWoofReal (woof) {
return /w.*?o.*?o.*?f/i.test(woof)
}function transformWoofToLetter (word, letterIndex) {
if (letterIndex <= alph.length) {
word += alph[letterIndex - 1]
}
return word
}Учтены абсолютно все кейсы из задачи
Из-за условия на разный ответ ("just barking!" и "nothing to decode!") пришлось разделить на 2 reduce, иначе можно справиться и с однимupd: переписал под typescript и попросил chatgpt написать мне тесты под это. Он написал всё с использованием jest, но я хз, как в playground добавить jest, разве что импорт по ссылке, но это ещё конфиг писать отдельно, в общем мне слишком лень, на вот такой тестер
Справа вкладка "logs" для вывода результатов
Ссылка
Александр сказал(а):↑Накидал за минут 10 в развёрнутом варианте, чтобы тебе было понятно, что, куда и зачем
const alph = 'abcdefghijklmnopqrstuvwxyz'
function decodeWoof (woofs) {
const letters = woofs.split('!').reduce(reduceWoof, [])
if (letters.length === 0) {
return 'nothing to decode!'
}
const humanLanguage = letters.reduce(transformWoofToLetter, '')
if (humanLanguage.length === 0) {
return 'just barking!'
}
return humanLanguage
}
function reduceWoof (result, str) {
const woofs = str.split('-').filter(isWoofReal)
if (woofs.length > 0) {
result.push(woofs.length)
}
return result
}
function isWoofReal (woof) {
return /w.*?o.*?o.*?f/i.test(woof)
}
function transformWoofToLetter (word, letterIndex) {
if (letterIndex <= alph.length) {
word += alph[letterIndex - 1]
}
return word
}
Учтены абсолютно все кейсы из задачи
Из-за условия на разный ответ ("just barking!" и "nothing to decode!") пришлось разделить на 2 reduce, иначе можно справиться и с одним
upd: переписал под typescript и попросил chatgpt написать мне тесты под это. Он написал всё с использованием jest, но я хз, как в playground добавить jest, разве что импорт по ссылке, но это ещё конфиг писать отдельно, в общем мне слишком лень, на вот такой тестер
Справа вкладка "logs" для вывода результатов
СсылкаНажмите, чтобы раскрыть...Когда я вставляю вот такое на проверку в твой код:
const example8 = "Woof! Woof" + "-woof".repeat(26) + "!"
console.log(decodeWoof(example8))
Он выдаёт "a" а должен выдавать "just barking!"
Тема закрыта
-
ЗаголовокОтветов ПросмотровПоследнее сообщение
-
Сообщений:4
Просмотров:6
-
Сообщений:1
Просмотров:3
-
внук берии 21 Dec 2024 в 14:31Сообщений: 2 21 Dec 2024 в 14:31
Сообщений:2
Просмотров:8
-
Сообщений:2
Просмотров:5
-
Сообщений:9
Просмотров:19