codewars练习(javascript)-2021/2/14--情人节快乐

本文档记录了2021年2月14日情人节当天进行的三道 Codewars JavaScript 练习题。题目分别为:【1】ElevatorDistance(计算电梯行程距离)、【2】GuesstheSequence(生成特定序列)和【3】LarioandMuigiPipeProblem(修复管道序列)。每个题目都提供了详细的解决方案和测试用例,供读者参考和学习。

codewars-js练习

2021/2/14----情人节快乐

github 地址

my 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>

以上为自己思路供大家参考,可能有更优的思路。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值