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

codewars-js练习

2021/4/15

github 地址

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

【1】<7kyu>【Drone Fly-By】

example

'xxxxxx', '====T'//'ooooox'
'xxxxxxxxx', '==T'// 'oooxxxxxx'
'xxxxxxxxxxxxxxx', '=========T'// 'ooooooooooxxxxx'

solution

<script type="text/javascript">
	function flyBy(lamps, drone){
		// console.log(lamps,drone)
		var len = drone.length;
		var str = lamps.substring(0,len).replace(/x/g,'o');;
		return str + lamps.substring(len,);
	}
</script>
【2】<8kyu>【Abbreviate a Two Word Name】

example

Sam Harris` => `S.H
Patrick Feeney` => `P.F

solution

<script type="text/javascript">
	function abbrevName(name){
		// console.log(name)
		var arr = name.split(' ');
		return arr[0].substring(0,1).toUpperCase() + '.' + arr[1].substring(0,1).toUpperCase() ;
	}
</script>
【3】<7kyu>【Substituting Variables Into Strings: Padded Numbers】

example

solution(5) // should return "Value is 00005"

solution

<script type="text/javascript">
	function solution(value){
		console.log(value)
		if(value == 0)return "Value is 00000";
		var len = 5 - (value.toString().split('').length);
		var arr = [];
		for(var i=0;i<len;i++){
			arr.push(0)
		}
		arr.push(value)
		return 'Value is ' + arr.join('');
		// ---------------------------------------
		return "Value is " + ("00000" + value).slice(-5);

	}
	
	// 验证
	console.log(solution(5));//"Value is 00005"
	console.log(solution(1204));//"Value is 01204"
	console.log(solution(0));//"Value is 00000"
</script>
<script type="text/javascript">
	function solution(value){
		console.log(value)
		return "Value is " + ("00000" + value).slice(-5);

	}
	
	// 验证
	console.log(solution(5));//"Value is 00005"
	console.log(solution(1204));//"Value is 01204"
	console.log(solution(0));//"Value is 00000"
</script>

2021/4/16

【1】<7kyu>【JavaScript Array Filter】

example

getEvenNumbers([2,4,5,6]) // should == [2,4,6]?2

solution

<script type="text/javascript">
	function check(numbers){
		return (numbers % 2 ==0);
	}
	function getEvenNumbers(numbersArray){
		// console.log(numbersArray)
		// 返回的都是2的倍数
		return  numbersArray.filter(check);
	}

	
	// 验证
	console.log(getEvenNumbers([1,2,3,6,8,10]));// [2,6,8,10]
	console.log(getEvenNumbers([1,2]));// [2]
	console.log(getEvenNumbers([12,14,15]));//[12,14]
	console.log(getEvenNumbers([13,15]));// []
</script>
【2】<6kyu>【Point in Polygon】

测试一个点是否在多边形内。

该多边形将是多边形顶点的点数组。数组中的最后一个点连接回第一个点。

example

[[-5, -5], [5, -5], [0, 5]]      [0,0]//true)

solution

<script type="text/javascript">
	function pointInPoly(poly, point) {
		let inside = false;

		const px = point[0];
		const py = point[1];

		for (var start = 0, end = poly.length - 1; start < poly.length; end = start++) {    
			const x1 = poly[start][0];
			const y1 = poly[start][1];    
			const x2 = poly[end][0];
			const y2 = poly[end][1];    
			const dx = x2 - x1;
			const dy = y2 - y1;
			const t = (py - y1) / dy;    // Determine t where segment intersects horizontal ray

			if (y1 > py != y2 > py)      // Check if start and end of segment are on opposite sides of the ray          
			  if (dx * t + x1 >= px)     // Check if X component of intersection point is t > 0 on ray
			    inside = !inside;        // If it is the ray intersects the segment, so flip inside flag    
		}
		return inside;
}

	// 验证
	var poly = [[-5, -5], [5, -5],[5, 5], [-5, 5]];
	console.log(pointInPoly(poly, [-6,0]));//false
	console.log(pointInPoly(poly, [1,1]));// true
</script>

2021/4/18

【1】<7kyu>【Spraying trees】

There are five workers : James,John,Robert,Michael and William.They work one by one and on weekends they rest. Order is same as in the description(James works on mondays,John works on tuesdays and so on).

Your function should return string like this : 'It is (weekday) today, (name), you have to work, you must spray (number) trees and you need (x) dollars to buy liquid'

example

task('Monday',15,2) -> 'It is Monday today, James, you have to work, you must spray 15 trees and you need 30 dollars to buy liquid'

solution

<script type="text/javascript">
	function task(w, n, c) {
		console.log(w,n,c)
		var map = {'Monday':'James','Tuesday':'John','Wednesday':'Robert','Thursday':'Michael','Friday':'William'};
		var money = n*c;
		return 'It is '+ w +' today, '+ map[w] +', you have to work, you must spray '+ n +' trees and you need '+money+' dollars to buy liquid'
	}

	// 验证
	console.log(task('Wednesday',10,2));//'It is Wednesday today, Robert, you have to work, you must spray 10 trees and you need 20 dollars to buy liquid'
	console.log(task('Monday',4,3));//'It is Monday today, James, you have to work, you must spray 4 trees and you need 12 dollars to buy liquid'
	console.log(task('Friday',5,4));//'It is Friday today, William, you have to work, you must spray 5 trees and you need 20 dollars to buy liquid'
</script>

2021/4/19

【1】<7kyu>【Harvest Festival】

种子(字符串)-确定植物产生的花的类型。

水(整数)-每个单位的水延伸的部分茎之间的花。它也给出了茎+花簇应该重复的次数

fert(整数)-每单位肥料增加花的数量,分组成簇

温度(整数)——如果给定的温度在20°C到30°C之间,则植物正常生长;否则,除茎端部的一朵花外,所有花都死亡。

example

plant("@", 3, 3, 25) => "---@@@---@@@---@@@"
// Water gives the length of the stem portions between flowers
// Water also gives the total number of segments(number of times flowers + stems should be repeated)
// Fertilizer gives the length of the flower clusters.
// Temperature is in the range of 20°C and 30°C

plant("$", 4, 2, 30) => "----$$----$$----$$----$$"

plant("&", 1, 5, 20) => "-&&&&&"

plant("^", 3, 3, 35) => "---------^"
// The temperature is not in the correct range, so all flowers die, except the last one at the end.
// The stem is not affected by the temperature

solution

<script type="text/javascript">
	function plant(seed, water, fert, temp){
		console.log(seed,water,fert,temp)
		var temp1=[];
		var temp2=[];
		for(var i=0;i<water;i++)temp1.push('-');
		for(var j=0;j<fert;j++)temp2.push(seed);
		var str = temp1.join('') + temp2.join('');
		var result = [];
		if(temp<20 || temp>30){
			for(var i=0;i<water;i++){
				result.push(temp1.join(''));
			}
			return result.join('') + seed;
		}
</script>
<script type="text/javascript">
	function plant(seed, water, fert, temp){
		let arr = [];
		for(let i = 0; i < water; i += 1) {
			arr.push('-'.repeat(water));
			arr.push(seed.repeat(fert))
		}
		return temp < 20 || temp > 30 ? arr.join('').replace(/[^-]/g, '')+seed : arr.join('');
	}
</script>

2021/4/20

【1】<7kyu>【Word to binary】

example

'man' should return [ '01101101', '01100001', '01101110' ]

solution

<script type="text/javascript">
	function wordToBin(str){
		console.log(str)
		// 先得到对应的ascii码,然后再将十进制转换成二进制
		var arr = str.split('');
		var result = [];
		for(var i=0;i<arr.length;i++){
			// console.log(arr[i].charCodeAt().toString(2))
			result.push('0'+arr[i].charCodeAt().toString(2))
		}
		return result
	}

	// 验证
	console.log(wordToBin('man'));//[ '01101101', '01100001', '01101110' ]
	console.log(wordToBin('AB'));// ['01000001', '01000010']
	console.log(wordToBin('wecking'));//[ '01110111', '01100101', '01100011', '01101011', '01101001', '01101110', '01100111' ]
</script>
【2】<6kyu>【Meeting】

使这个字符串大写,按姓氏的字母顺序排序。

当姓氏相同时,按名字排序。客人的姓和名出现在由逗号分隔的圆括号中。

example

"(CORWILL, ALFRED)(CORWILL, FRED)(CORWILL, RAPHAEL)(CORWILL, WILFRED)(TORNBULL, BARNEY)(TORNBULL, BETTY)(TORNBULL, BJON)"

solution

<script type="text/javascript">
	function meeting(s) {
		console.log(s)
		let string = s.toUpperCase().split(';')
                .map(x => x.split(':').reverse().join(', '))
                .sort()
                .join(')(')
  		return '(' + string + ')'
	}

	// 验证
	console.log(meeting("Alexis:Wahl;John:Bell;Victoria:Schwarz;Abba:Dorny;Grace:Meta;Ann:Arno;Madison:STAN;Alex:Cornwell;Lewis:Kern;Megan:Stan;Alex:Korn"));//"(ARNO, ANN)(BELL, JOHN)(CORNWELL, ALEX)(DORNY, ABBA)(KERN, LEWIS)(KORN, ALEX)(META, GRACE)(SCHWARZ, VICTORIA)(STAN, MADISON)(STAN, MEGAN)(WAHL, ALEXIS)"
</script>

2021/4/21

【1】<7kyu>【Valid Spacing】

有效空格的定义是单词之间的一个空格,不包含前导或尾随空格。

example

'Hello world' = true
' Hello world' = false
'Hello world  ' = false
'Hello  world' = false
'Hello' = true
// Even though there are no spaces, it is still valid because none are needed
'Helloworld' = true 
// true because we are not checking for the validity of words.
'Helloworld ' = false
' ' = false
'' = true

solution

<script type="text/javascript">
	function validSpacing(s) {
		console.log(s)
		return s.replace(/\s+/g," ").trim()==s;
	}

	// 验证
	console.log(validSpacing('Hello world'));// true
	console.log(validSpacing('Hello'));// true
	console.log(validSpacing('Hello  world '));//false
</script>

2021/4/22

【1】<7kyu>【Evens times last】

给定一个整数序列,返回所有具有偶数下标的整数的和,再乘以最后一个下标的整数。

example

evenLast([2, 3, 4, 5]), 30

solution

<script type="text/javascript">
	function evenLast(numbers) {
		console.log(numbers);
		var len = numbers.length;
		var sum = 0;
		if(len == 0)return 0;
		for(var i=0;i<numbers.length;i++){
			if(i%2==0){
				sum +=numbers[i];
			}
		}
		return sum * numbers[len-1]
	}

	// 验证
	console.log(evenLast([2, 3, 4, 5]));// 30
	console.log(evenLast([]));//0
</script>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值