Home > Web Front-end > JS Tutorial > Example tutorial of code war

Example tutorial of code war

零下一度
Release: 2017-06-23 09:35:33
Original
1327 people have browsed it

Today I will continue to do a question about arrays:

One difficulty here is that there are negative numbers in the numerical sorting. Sorting using sort will also report an error.

So, after several thoughts and tests, my answer is as follows:

function highAndLow(numbers){  var numArr=[],numArr1=[],numArr2=[];
  numbers.split(' ').map(function(n){      if(n>=0){
          numArr2.push(n);
      }else{
          numArr1.push(n);
      }
  });
  numArr1.sort((a,b)=>b-a);
  numArr2.sort((a,b)=>b-a);
  numArr = numArr2.concat(numArr1);
  numArr.splice(1,numArr.length-2);  return numArr.join(' ')
}
Copy after login

First divide the positive and negative numbers into two groups, then sort them separately, and finally merge the arrays , just take the first and last digits of the array.

The method is a bit stupid. Hahaha, I am that stupid bird.

Finally check out the code written by others:

The most practical one is

function highAndLow(numbers){
  numbers = numbers.split(' ').map(Number);  return Math.max.apply(0, numbers) + ' ' + Math.min.apply(0, numbers);
}
Copy after login

directly uses the max and min methods of Math (I Why didn't you think of it? Pig head, 555...)

There is another one that is closest to my original idea:

function highAndLow(numbers){  var arr = numbers.split(' ').sort(function(a, b) { return a - b });  return arr[arr.length -1] + ' ' + arr[0];
}
Copy after login

It's just that I wrote it as

function highAndLow(numbers){
  numbers.split(' ').sort((a, b)=> a - b });
  numbers.splice(1,numbers.length-2);  return numbers.join(' ');
}
Copy after login

Because the numbers were not converted into an array, an error occurred (low-level error)

The above is the detailed content of Example tutorial of code war. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template