codewars练习(javascript)-2021/4/9

2021/4/9 12:26:59

本文主要是介绍codewars练习(javascript)-2021/4/9,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

文章目录

    • codewars-js练习
      • 2021/4/9
        • github 地址
        • 【1】<7kyu>【Slaphead】
        • 【2】<6kyu>【Handshake problem】

codewars-js练习

2021/4/9

github 地址

my github地址,上面有做的习题记录,不断更新…

【1】<7kyu>【Slaphead】

剃干净的头发用“-”表示,散乱的头发用“/”表示。你的任务是检查头部是否有散落的头发并把它们清除掉。

example

0 hairs --> "Clean!"
1 hair --> "Unicorn!"
2 hairs --> "Homer!"
3-5 hairs --> "Careless!"
>5 hairs --> "Hobo!"


 "------/------" you shoud return:
["-------------", "Unicorn"]

solution

<script type="text/javascript">
	function bald(x){
		console.log(x)	
		var len = x.length;
		var s = x.match(/[/]/g);
		var temp = [];
		if(s == null) return [x,'Clean!']
		var num = s.length;
		for(var i=0;i<len;i++){
			temp.push('-');
		}
		var str = temp.join('');
		var result = [str];
		if(num == 0)result.push('Clean!');
		else if(num == 1)result.push('Unicorn!')
		else if (num == 2)result.push('Homer!')
		else if (num>=3&& num<=5)result.push('Careless!')
		else result.push('Hobo!')		
		return result;
	}
	// 验证
	// console.log(bald('/---------'));// ['----------', 'Unicorn!']
	// console.log(bald('/-----/-'));//['--------', 'Homer!']
	// console.log(bald('--/--/---/-/---'));// ['---------------', 'Careless!']
	console.log(bald('-----'));//['----','Clean!']
</script>

【2】<6kyu>【Handshake problem】

Johnny想通过计算所有的握手次数来了解今年参与的人数。

该函数获取握手次数,并返回执行这些握手所需的最小人数(一对农民只握手一次)。

握手次数最小人数
01
12
33
64

example

6//4
7//5

solution

<script type="text/javascript">
	function getParticipants(handshakes){
		// console.log(handshakes)
		x = (1 + Math.sqrt(1+8*handshakes))/2
		return Math.ceil(x)
	}
	// 验证
	console.log(getParticipants(0));// 1
	console.log(getParticipants(1));// 2
	console.log(getParticipants(3));//3
	console.log(getParticipants(6));//4
	console.log(getParticipants(7));//5
</script>


这篇关于codewars练习(javascript)-2021/4/9的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程