codewars练习(javascript)-2021/1/20

本文记录了在 Codewars 上进行的 JavaScript 练习,包括建塔、字母位置替换、正数求和、BMI 计算、作业纸张计算、简单问题解决、立方体体积差、奇数筛选、字符解析、CSV 表示等题目,详细阐述了解题思路和解决方案,适合编程初学者参考学习。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

codewars-js练习

2021/1/20

github 地址

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

【1】 <6kyu>【Build Tower】

Build Tower by the following given argument (即 建塔)

example

a tower of 3 floors looks like below
[
  '  *  ', 
  ' *** ', 
  '*****'
]

a tower of 6 floors looks like below
[
  '     *     ', 
  '    ***    ', 
  '   *****   ', 
  '  *******  ', 
  ' ********* ', 
  '***********'
]

思路:

以a tower of6 floors looks like below为例

i前空格数*数后空格数
0515
1434
2353
3272
4191
50110

因此:

  • *数=2*i+1
  • 前空格数=nFloors -i -1
  • 后空格数=nFloors -i -1

solution:

<script type="text/javascript">
 		function towerBuilder(nFloors) {
 			// console.log(nFloors);
 			var result = [];
 			for(var i=0;i<nFloors;i++){
 				result.push(" ".repeat(nFloors-i-1) 
 							+ "*".repeat(2*i+1) 
 							+ " ".repeat(nFloors-i-1));
 				console.log(result);
 			}
 			return result;
		}
		 		
		// 验证
		console.log(towerBuilder(1));//['*']
		console.log(towerBuilder(3));//["  *  "," *** ","*****"]
	</script>
【2】<6 kyu>【Replace With Alphabet Position】

In this kata you are required to, given a string, replace every letter with its position in the alphabet.(即 给定一个字符串,用它在字母表中的位置替换每个字母。)

example

alphabetPosition("The sunset sets at twelve o' clock.")
//"20 8 5 19 21 14 19 5 20 19 5 20 19 1 20 20 23 5 12 22 5 15 3 12 15 3 11"

思路:

  • 将文本全部转为大写;
  • 利用正则表达式将不是[A-Z]的内容替换成掉;
  • 按照空格分隔放到arr数组中;
  • 匹配到unicode编码,并用join连接返回。

solution:

<script type="text/javascript">
 		function alphabetPosition(text) {
 			// 将文本全部转为大写
 			var str = text.toUpperCase();

 			// 利用正则表达式将不是[A-Z]的内容替换成掉
 			str = str.replace(/[^A-Z]/g,'');

 			// 按照空格分隔放到arr数组中
 			var arr = str.split('');

 			// 匹配到unicode编码,并用join连接返回
 			// charCodeAt()返回指定位置的unicode编码
 			arr = arr.map((c) => c.charCodeAt()-64).join(' ');
 			// console.log(arr);
		  	return arr;
		}
		 		
		// 验证
		console.log(alphabetPosition("The sunset sets at twelve o' clock."));//"20 8 5 19 21 14 19 5 20 19 5 20 19 1 20 20 23 5 12 22 5 15 3 12 15 3 11"
	</script>
【3】<8 kyu>【Sum of positive】

You get an array of numbers, return the sum of all of the positives ones.(即返回所有正数的和)

example

[1,-4,7,12] => 1 + 7 + 12 = 20

solution:

<script type="text/javascript">
 		function positiveSum(arr) {
 			var length = arr.length;
 			if(length !=0){
 				var sum=0;
 				for(var i=0;i<length;i++){
	 				// console.log(arr[i]);
	 				if(arr[i]>=0){
	 					sum +=arr[i];
	 					// console.log(sum);
 					}
 				}
	 			return sum;
 			}else{
 				return 0;
 			}
  
		}
 		
		// 验证
		console.log(positiveSum([1,2,3,4,5]));//15
		console.log(positiveSum([1,-2,3,4,5]));//13
		console.log(positiveSum([]));//0
	</script>
</head>
【4】<8kyu>【Calculate BMI】

Write function bmi that calculates body mass index (bmi = weight /( height ^ 2)).

if bmi <= 18.5 return “Underweight”

if bmi <= 25.0 return “Normal”

if bmi <= 30.0 return “Overweight”

if bmi > 30 return “Obese”

example

bmi(80, 1.80));//Normal

solution:

<script type="text/javascript">
 		function bmi(weight, height) {
			console.log(weight,height);
			var h = height*100;
			var bmi = (weight/(Math.pow(h,2)))*10000;
			// console.log(bmi);
			if(bmi <=18.5){
				return "Underweight";
			}else if(bmi>18.5 &&bmi<=25.0){
				return "Normal";
			}else if(bmi>25.0 &&bmi<=30.0){
				return "Overweight";
			}else{
				return "";
			}
		}
 		
		// 验证
		console.log(bmi(80, 1.80));//Normal
	</script>
【5】<8kyu>【Beginner Series #1 School Paperwork】

Your classmates asked you to copy some paperwork for them. You know that there are ‘n’ classmates and the paperwork has ‘m’ pages.

Your task is to calculate how many blank pages do you need. If n < 0 or m < 0 return 0.

example

n= 5, m=5: 25
n=-5, m=5:  0

solution:

<script type="text/javascript">
 		function paperwork(n, m) {
 			if(n<0||m<0){
 				return 0;
 			}else{
 				return n*m;
 			}
		}
 		
		// 验证
		console.log(paperwork(5,5));//25
		console.log(paperwork(-5,5));//0
	</script>
【6】<8kyu>【Super Duper Easy】

Make a function that returns the value multiplied by 50 and increased by 6. If the value entered is a string it should return “Error”.

example

problem("hello")//"Error"
problem(1)//56

solution:

<script type="text/javascript">
 		function problem(x){
			if(typeof x=='string'){
				return "Error";
			}else{
				return x*50+6;
			}
		}
 		
		// 验证
		console.log(problem("hello"));//"Error"
		console.log(problem(1));//56
	</script>
【7】<8kyu>【Difference of Volumes of Cuboids】

In this simple exercise, you will create a program that will take two lists of integers, a and b. Each list will consist of 3 positive integers above 0, representing the dimensions of cuboids a and b. You must find the difference of the cuboids’ volumes regardless of which is bigger.

For example, if the parameters passed are ([2, 2, 3], [5, 4, 1]), the volume of a is 12 and the volume of b is 20. Therefore, the function should return 8.

example

findDifference([3, 2, 5], [1, 4, 4]), 14
findDifference([15, 20, 25], [10, 30, 25]), 0

solution:

<script type="text/javascript">
 		function findDifference(a, b) {
			var temp1 = 1;
			var temp2 = 1;
			for(var i=0;i<a.length;i++){
				temp1 *=a[i];
			}
			for(var j=0;j<b.length;j++){
				temp2 *=b[j];
			}
			var result = temp2-temp1;
			return result>=0?result:-result;
		}
 		
		// 验证
		console.log(findDifference([3, 2, 5], [1, 4, 4]));//14
		console.log(findDifference([15, 20, 25], [10, 30, 25]));//0
	</script>
【8】<8kyu>【Are arrow functions odd?】

example

odds([1,2,3,4,5]) // [1,3,5]

solution:

 	<script type="text/javascript">
 		function odds(values){
			var result = [];
			for(var i=0;i<values.length;i++){
				if(values[i] % 2 !=0){
					result.push(values[i]);
				}
			}
			return result;
		}
 		
		// 验证
		console.log(odds([1,2,3,4,5]));//[1,3,5]
	</script>
【9】<8kyu>【Parse nice int from char problem】

example

getAge"4 years old")//44

solution:

<script type="text/javascript">
 		function getAge(inputString){
			var arr = inputString.split(' ');
			return parseInt(arr[0]);
		}
 		
		// 验证
		console.log(getAge("4 years old")) //4
	</script>
【10】<8kyu>【CSV representation of array】

CSV representation of array==(即 创建一个返回二维数值数组的CSV表示形式的函数。)==

example

input:
   [[ 0, 1, 2, 3, 4 ],
    [ 10,11,12,13,14 ],
    [ 20,21,22,23,24 ],
    [ 30,31,32,33,34 ]] 

output:
     '0,1,2,3,4\n'
    +'10,11,12,13,14\n'
    +'20,21,22,23,24\n'
    +'30,31,32,33,34'

solution:

<script type="text/javascript">
		function toCsvText(array) {
			return array.join('\n');;
		}
 		
		// 验证
		console.log(toCsvText([
                                [ 0, 1, 2, 3, 45 ],
                                [ 10,11,12,13,14 ],
                                [ 20,21,22,23,24 ],
                                [ 30,31,32,33,34 ]
                               ] ));
	</script>

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值