文章目录
codewars-js练习
2021/3/1
github 地址
【1】<7kyu>【Currying functions: multiply all elements in an array】
To complete this Kata you need to make a function multiplyAll/multiply_all which takes an array of integers as an argument. This function must return another function, which takes a single integer as an argument and returns a new array.
The returned array should consist of each of the elements from the first array multiplied by the integer.
即要创建两个函数
example:
multiplyAll([1, 2, 3])(2) = [2, 4, 6];
solution
<script type="text/javascript">
function multiplyAll(arr){
return function (n){
// console.log(arr)
if(arr.length == 0)return [];
let result = [];
for(let i=0;i<arr.length;i++){
result.push(arr[i]*n);
}
return result;
}
}
// 验证
console.log(multiplyAll([1, 2, 3])(1));//[1,2,3]
console.log(multiplyAll([1, 2, 3])(2));//[2,4,6]
console.log(multiplyAll([])(10));//[]
</script>
【2】<8kyu>【Is he gonna survive?】
each dragon takes 2 bullets to be defeated, our hero has no idea how many bullets he should carry.
example:
hero(10, 5)// true
hero(7, 4)// false
hero(100, 40)//true
hero(0,1)//false
solution
<script type="text/javascript">
function hero(bullets, dragons){
// console.log(bullets,dragons)
if(bullets < dragons*2)return false
return true
}
// 验证
console.log(hero(10, 5));// true
console.log(hero(7, 4));// false
console.log(hero(100, 40));//true
console.log(hero(0,1));//false
</script>
【3】<6kyu>【A Cinema】
b boys and g girls went to the cinema and bought tickets for consecutive seats in the same row. Write a function that will tell you how to sit down for boys and girls, so that at least one girl sits next to each boy, and at least one boy sits next to each girl.
example:
cinema(1,1) === "BG" (the result like "GB" is also valid)
cinema(5,5) === "BGBGBGBGBG" (the result like "GBGBGBGBGB" is also valid)
cinema(5,3) === "BGBGBBGB" (the results like "BGBBGBBG" or "BGBBGBGB" and so on are also valid)
cinema(3,3) === "BGBGBG" (the result like "GBGBGB" is also valid)
cinema(100,3) === null
solution
<script type="text/javascript">
function cinema(boys, girls) {
if (boys > girls * 2 || girls > boys * 2) {
return null;
} else if (boys === girls) {
return "".padStart(boys + girls, "BG");
} else if (boys > girls) {
return "BGB".repeat(boys - girls).padEnd(boys + girls, "GB");
}
return "GBG".repeat(girls - boys).padEnd(boys + girls, "BG");
}
// 验证
console.log(cinema(1,1));// "BG"
console.log(cinema(5,5));// "BGBGBGBGBG"
console.log(cinema(5,3));// "BGBBGBGB"
console.log(cinema(100,3));//null
</script>
知识点
padStart()用于头部补全,padEnd()用于尾部补全。
'x'.padStart(5, 'ab') // 'ababx'
'x'.padStart(4, 'ab') // 'abax'
'x'.padEnd(5, 'ab') // 'xabab'
'x'.padEnd(4, 'ab') // 'xaba'
以上为自己思路供大家参考,可能有更优的思路。
又是一个工作日
本文介绍了三个Codewars JavaScript编程挑战的解决方案,包括数组元素乘法、英雄生存判断及电影院座位分配问题。通过这些练习,可以提升JavaScript编程技能。
222

被折叠的 条评论
为什么被折叠?



