文章目录
codewars-js练习
2021/1/30
github 地址
【1】<8kyu>【Check the exam】
The first input array is the key to the correct answers to an exam, like [“a”, “a”, “b”, “d”]. The second one contains a student’s submitted answers.
The two arrays are not empty and are the same length. Return the score for this array of answers, giving +4 for each correct answer, -1 for each incorrect answer, and +0 for each blank answer, represented as an empty string (in C the space character is used).
If the score < 0, return 0.
example:
checkExam(["a", "a", "b", "b"], ["a", "c", "b", "d"]) → 6
checkExam(["a", "a", "c", "b"], ["a", "a", "b", ""]) → 7
checkExam(["a", "a", "b", "c"], ["a", "a", "b", "c"]) → 16
checkExam(["b", "c", "b", "a"], ["", "a", "a", "c"]) → 0
solution
<script type="text/javascript">
function checkExam(array1, array2) {
// console.log(array1,array2);
var correct = 0;
var error = 0;
var other = 0;
for(var i=0;i<array1.length;i++){
if(array1[i] == array2[i]){
correct ++;
}else if(array2[i] == ''){
other = 0;
}else{
error ++;
}
}
// console.log(correct,error);
var result = correct * 4 + error * (-1) + other;
if(result <0){
return 0;
}
return result;
}
验证
console.log(checkExam(["a", "a", "b", "b"], ["a", "c", "b", "d"]));// 6
console.log(checkExam(["a", "a", "c", "b"], ["a", "a", "b", ""]));//7
console.log(checkExam(["b", "c", "b", "a"], ["", "a", "a", "c"]));//0
</script>
【2】<7kyu>【Love vs friendship】
If a = 1, b = 2, c = 3 ... z = 26
Then l + o + v + e = 54
and f + r + i + e + n + d + s + h + i + p = 108
So friendship
is twice stronger than love
😃
The input will always be in lowercase and never be empty.
example:
wordsToMarks("attitude")// 100
wordsToMarks("friends")//75
solution
<script type="text/javascript">
function wordsToMarks(string){
var arr = [];
var count = 0;
for(var i=0;i<string.length;i++){
// 获取到string每个字母的大小,放入到新数组中
var temp = string.substring(i,i+1).charCodeAt()-96;
arr.push(temp);
}
// console.log(arr);
for(var j=0;j<arr.length;j++){
count += arr[j];
}
return count;
}
// 验证
console.log(wordsToMarks("attitude"));// 100
console.log(wordsToMarks("friends"));//75
</script>
【3】<7kyu>【Remove anchor from URL】
Complete the function/method so that it returns the url with anything after the anchor (#
) removed.
example:
// returns 'www.codewars.com'
removeUrlAnchor('www.codewars.com#about')
// returns 'www.codewars.com?page=1'
removeUrlAnchor('www.codewars.com?page=1')
solution
<script type="text/javascript">
function removeUrlAnchor(url){
var index = url.indexOf('#');
// console.log(index);
if(index !=-1){
url = url.substring(0,index);
}
return url;
}
// 验证
console.log(removeUrlAnchor("www.codewars.com#about"));// www.codewars.com
console.log(removeUrlAnchor("www.codewars.com?page=1"));//www.codewars.com?page=1
</script>
以上为自己思路供大家参考,可能有更优的思路。