codewars-js练习
2021/3/14
github 地址
【1】<6kyu>【Cumulative Triangle】
example:
1
2 3
4 5 6
7 8 9 10
...
Given N, return the sum of all numbers on the Nth Row
2//2+3=5
3//4+5+6=15
思路
第n行首字母就是 n ( n − 1 ) 2 + 1 \frac{n(n-1)}{2} + 1 2n(n−1)+1
solution
<script type="text/javascript">
function cumulativeTriangle(n) {
console.log(n)
var first = (n*(n-1))/2 + 1;
var last = first + (n-1);
var sum = 0;
for(var i=first;i<=last;i++){
sum +=i;
}
return sum;
}
// 验证
console.log(cumulativeTriangle(2));// 5
console.log(cumulativeTriangle(3));//15
</script>
【2】<6kyu>【Follow that Spy】
example:
[ [USA, BRA], [JPN, PHL], [BRA, UAE], [UAE, JPN] ]//"USA, BRA, UAE, JPN, PHL"
solution
<script type="text/javascript">
function findRoutes(routes) {
console.log(routes);
var arr=routes[0];
for(var i=0;i<routes.length;i++){
for(var j=1;j<routes.length;j++){
if(routes[j][0] == arr[arr.length-1]){
arr.push(routes[j][1])
}else if(routes[j][1] == arr[0]){
arr.unshift(routes[j][0]);
}
}
}
return arr.join(', ');
}
// 验证
console.log(findRoutes([["MNL", "TAG"], ["CEB", "TAC"], ["TAG", "CEB"], ["TAC", "BOR"]]));//"MNL, TAG, CEB, TAC, BOR"
console.log(findRoutes([["USA", "BRA"], ["JPN", "PHL"], ["BRA", "UAE"], ["UAE", "JPN"]]));//"USA, BRA, UAE, JPN, PHL"
</script>