codewars练习记录3 (javascript)

这篇博客探讨了四个编程挑战,包括保持原始顺序对数组中的奇数进行排序,寻找整数数组中出现奇数次的元素,从URL中提取域名,以及创建有序序列。解决方案涉及使用filter,map,reduce等函数以及位运算技巧,展示了简洁高效的编程思想。

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

【6 kyu】Sort the odd

You will be given an array of numbers. You have to sort the odd numbers in ascending order while leaving the even numbers at their original positions.

Examples
[7, 1] => [1, 7]
[5, 8, 6, 3, 4] => [3, 8, 6, 5, 4]
[9, 8, 7, 6, 5, 4, 3, 2, 1, 0] => [1, 8, 3, 6, 5, 4, 7, 2, 9, 0]

翻译:
你将得到一个数字数组。您必须按升序对奇数进行排序,同时将偶数保留在其原始位置。

解一:

/**
将奇数过滤出来成为新的数组并排序
构建一个数组保存奇数的位置
根据奇数位置数组,把排好序的奇数数组放入原数组中
**/
function sortArray(array) {
   var b = []
  var a = array.filter(function (x, index) { if (x % 2 != 0) { b.push(index); return x } }).sort((a, b) => a - b)
  for (var t = 0; t < a.length; t++) {
    array[b[t]] = a[t]
  }
  return array
}

优秀解法:

function sortArray(array) {
  const odd = array.filter((x) => x % 2).sort((a,b) => a - b);
  return array.map((x) => x % 2 ? odd.shift() : x);
}
【6 kyu】Find the odd int

Given an array of integers, find the one that appears an odd number of times.

There will always be only one integer that appears an odd number of times.

Examples
[7] should return 7, because it occurs 1 time (which is odd).
[0] should return 0, because it occurs 1 time (which is odd).
[1,1,2] should return 2, because it occurs 1 time (which is odd).
[0,1,0,1,0] should return 0, because it occurs 3 times (which is odd).
[1,2,2,3,3,3,4,3,3,3,2,2,1] should return 4, because it appears 1 time (which is odd).

翻译:
给定一个整数数组,找出出现奇数次的那个。
始终只有一个整数出现奇数次。
解一:

// 利用循环计数
function findOdd(A) {
  let sum =0
  for(let i=0;i<A.length;i++){
    for(let j=0;j<A.length;j++){
      if(A[i] == A[j]){
        sum++
      }
    }
    if(sum%2 != 0){
        var result=A[i];
      break;
    }
  }
  return result;
}

解二:

function findOdd(A) {
  return A.find((item, index) => A.filter(el => el == item).length % 2)
}

优秀解法:

function findOdd(A) {
  return A.reduce((a,b)=>a^b)
}

a^b 是异或运算符,是位运算符,例如 :
a=5,b=6,那么a ^ b=5 ^ 6= 0101 ^ 0110 = 0011 = 3

例题例子:[ 1 , 2 , 2 , 3 , 3 , 3 , 4 , 3 , 3 , 3 , 2 , 2 , 1 ]
1 ^ 2 = 0001 ^ 0010 = 0011 = 3
3 ^ 2 = 0011 ^ 0010 = 0001 = 1
1 ^ 3 = 0001 ^ 0011 = 0010 = 2
2 ^ 3 = 0010 ^ 0011 = 0001 = 1
1 ^ 3 = 0001 ^ 0011 = 0010 = 2
2 ^ 4 = 0010 ^ 0100 = 0110 = 6
6 ^ 3 = 0110 ^ 0011 = 0101 = 5
5 ^ 3 = 0101 ^ 0011 = 0110 = 6
6 ^ 3 = 0110 ^ 0011 = 0101 = 5
5 ^ 2 = 0101 ^ 0010 = 0111 = 7
7 ^ 2 = 0111 ^ 0010 = 0101 = 5
5 ^ 1 = 0101 ^ 0001 = 0100 = 4
最后得出结果是4,符合

【5 kyu】Extract the domain name from a URL

Write a function that when given a URL as a string, parses out just the domain name and returns it as a string. For example:

url = “http://github.com/carbonfive/raygun” -> domain name = “github”
url = “http://www.zombie-bites.com” -> domain name = “zombie-bites”
url = “https://www.cnet.com” -> domain name = cnet"

翻译:
编写一个函数,当将URL作为字符串给定时,只解析域名并将其作为字符串返回
解法一:

//比较傻瓜式解法直接去判断是哪种形式开头的url再截取
function domainName(url){
  if (url.indexOf("//") == -1) {
     if (url.indexOf("www") == -1) {
      return url.split(".")[0]
    }
    return url.slice(url.indexOf('www')).split(".")[1]
  } else {
      if (url.indexOf("www") == -1){
      return url.slice(url.indexOf('/')).replace('//', '').split(".")[0]
  } 
     return url.slice(url.indexOf('/')).replace('//', '').split(".")[1]
  }
}

优秀解法:

function domainName(url){
  return  url.replace('http://', '')
             .replace('https://', '')
             .replace('www.', '')
             .split('.')[0];
}

正则解法:

function domainName(url){  
  return url.replace(/.+\/\/|www.|\..+/g, '')
}
【6 kyu】Unique In Order

Implement the function unique_in_order which takes as argument a sequence and returns a list of items without any elements with the same value next to each other and preserving the original order of elements.
For example:

uniqueInOrder(‘AAAABBBCCDAABBB’) == [‘A’, ‘B’, ‘C’, ‘D’, ‘A’, ‘B’]
uniqueInOrder(‘ABBCcAD’) == [‘A’, ‘B’, ‘C’, ‘c’, ‘A’, ‘D’]
uniqueInOrder([1,2,2,3,3]) == [1,2,3]

翻译:
实现函数unique_in_order,该函数以一个序列为参数,返回一个项目列表,其中不包含任何相邻具有相同值的元素,并保留元素的原始顺序。
解一:

// 利用循环当后一个字母与前一个字不相同时,将字母取出
var uniqueInOrder=function(iterable){
  var arr = [];
  for(var i = 0; i < iterable.length; i++){
    if(iterable[i] != iterable[i+1]){
      arr.push(iterable[i]);
    }
  }
  return arr;
}

解二:

// 简便写法
var uniqueInOrder=function(iterable){
    return [...iterable].filter((a, i) => a !== iterable[i-1])
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值