文章目录
codewars-js练习
2021/2/14----情人节快乐
github 地址
【1】<7kyu>【Elevator Distance】
Imagine you start on the 5th floor of a building, then travel down to the 2nd floor, then back up to the 8th floor. You have travelled a total of 3 + 6 = 9 floors of distance.
Given an array representing a series of floors you must reach by elevator, return an integer representing the total distance travelled for visiting each floor in the array in order.
example:
[5,2,8]// 9
[1,2,3]//2
solution
<script type="text/javascript">
function elevatorDistance(array) {
var temp = [];
var sum =0; temp = 0;
for(var i=0;i<array.length-1;i++){
temp = array[i] - array[i+1];
temp = temp>0?temp:(-temp);
// console.log('temp',temp);
sum = sum + temp;
// temp.push(sum);
// console.log('sum;',sum);
}
// console.log(sum);
return sum;
}
// // 验证
console.log(elevatorDistance([5,2,8]));// 9
console.log(elevatorDistance([1,2,3]));//2
</script>
【2】<7kyu>【Guess the Sequence】
You must guess a sequence.It will have something to do with the number given.
example:
x = 16
result = [1, 10, 11, 12, 13, 14, 15, 16, 2, 3, 4, 5, 6, 7, 8, 9]
solution
<script type="text/javascript">
function sequence(x) {
var temp = [];
for(var i =1;i<=x;i++){
temp.push(i);
}
result = temp.sort();
// console.log(result);
return result;
}
// // 验证
console.log(sequence(16)); //[1, 10, 11, 12, 13, 14, 15, 16, 2, 3, 4, 5, 6, 7, 8, 9]
console.log(sequence(9));//[1, 2, 3, 4, 5, 6, 7, 8, 9]
</script>
【3】<8kyu>【Lario and Muigi Pipe Problem】
Given the a list of numbers, return the list so that the values increment by 1 for each index up to the maximum value.
给定一个数字列表,返回这个列表,使每个索引的值增加1,直到最大值。
example:
Input: 1,3,5,6,7,8
Output: 1,2,3,4,5,6,7,8
solution
<script type="text/javascript">
function pipeFix(numbers){
// console.log(numbers);
var temp = [];
for(var i=0;i<numbers.length-1;i++){
if(numbers[i+1]!=numbers[i]+1){
temp.push(numbers[i]);
for(var j=1;j<numbers[i+1]-numbers[i];j++){
temp.push(numbers[i]+j);
}
}else{
temp.push(numbers[i]);
}
}
temp.push(numbers[numbers.length-1]);
// console.log(temp);
return temp;
}
// 验证
console.log(pipeFix([1,2,3,5,6,8,9]));//[1,2,3,4,5,6,7,8,9]
console.log(pipeFix([6,9]));//[6,7,8,9])
console.log(pipeFix([1,2,3]));//[1,2,3]
</script>
以上为自己思路供大家参考,可能有更优的思路。
本文档记录了2021年2月14日情人节当天进行的三道 Codewars JavaScript 练习题。题目分别为:【1】ElevatorDistance(计算电梯行程距离)、【2】GuesstheSequence(生成特定序列)和【3】LarioandMuigiPipeProblem(修复管道序列)。每个题目都提供了详细的解决方案和测试用例,供读者参考和学习。

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



