文章目录
codewars-js练习
2021/4/5
github 地址
【1】<7kyu>【Number of Rectangles in a Grid】
给定一个大小为m × n的网格,计算这个矩形中包含的矩形的总数。所有整数大小和位置都被计算。
example:
numberOfRectangles(3, 2) == 18
numberOfRectangles(4, 4) == 100
solution
<script type="text/javascript">
function numberOfRectangles(m, n) {
// console.log(m.n)
return (m*(m+1)*n*(n+1))/4
}
// 验证
console.log(numberOfRectangles(4, 4));// 100
console.log(numberOfRectangles(5, 5));// 225
</script>
公式
*[ n(n+1)m(m+1)]/4
【2】<6kyu>【Your order, please】
您的任务是对给定的字符串进行排序。字符串中的每个单词将包含一个数字。这个数字是单词在结果中的位置。
example:
"is2 Thi1s T4est 3a" --> "Thi1s is2 3a T4est"
"4of Fo1r pe6ople g3ood th5e the2" --> "Fo1r the2 g3ood 4of th5e pe6ople"
"" --> ""
solution
<script type="text/javascript">
function order(words){
// console.log(words)
//提取数字,然后按照数字排序
if(words.length == 0)return words;
var obj = {};
var a = words.split(' ');
var arr = words.match(/\d/g);
// console.log(arr);
for(var i=0;i<arr.length;i++){
obj[arr[i]] = a[i];
}
// console.log(obj)
var result = [];
for(var j in obj){
result.push(obj[j])
}
return result.join(' ');
}
// 验证
console.log(order("is2 Thi1s T4est 3a"));// "Thi1s is2 3a T4est"
console.log(order("4of Fo1r pe6ople g3ood th5e the2"));//"Fo1r the2 g3ood 4of th5e pe6ople"
console.log(order(""));// ""
</script>
function order(words){
return words.split(' ').sort(function(a, b){
return a.match(/\d/) - b.match(/\d/);
}).join(' ');
}
308

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



