简体   繁体   English

以特殊顺序对数组进行排序

[英]Sort an array in a peculiar order

I've been trying to figure out how to solve this problem but I can't seem to find the proper sorting order. 我一直在尝试找出解决这个问题的方法,但似乎找不到正确的排序顺序。

Instructions: 说明:

Write a program that orders a list of numbers in the following way: 编写一个以下列方式对数字列表进行排序的程序:

3,-2,1,0,-1,0,-2,1 => -2,-1,-2,0,0,3,1,1 3,-2,1,0,-1,0,-2,1 => -2,-1,-2,0,0,3,1,1

'use strict';
let myNumbers = '3,-2,1,0,-1,0,-2,1';
// I receive the input as a string and split and map it into an array
let myNumbers = gets().split(',').map(Number);

I've tried applying the sort() method in ascending order to all integers below zero and doing the opposite for those above but that's not quite the order in the expected output. 我尝试对所有小于零的整数按升序应用sort()方法,对上述整数进行相反的处理,但这并不是预期输出中的顺序。

I've also attempted to splice the first array after applying sort() to 0 and then re-arrange the spliced part and concatenate it. 在将sort()应用于0之后,我还尝试拼接第一个数组,然后重新排列拼接部分并将其连接起来。 However, that won't work with all test inputs. 但是,这不适用于所有测试输入。

Another example: 3,-12,0,0,13,5,1,0,-2 => -12,-2,0,0,0,3,13,5,1 另一个示例:3,-12,0,0,13,5,1,0,-2 => -12,-2,0,0,0,3,13,5,1

What is the logic in this order? 此顺序的逻辑是什么? Thanks. 谢谢。

Because this sounds like the solution to a homework problem or something of the like, I'll let you write the code:) But the way I would do it is in one iteration through the array, create three separate arrays: 因为这听起来像是解决家庭作业问题或类似问题的解决方案,所以我将让您编写代码:)但是,我要这样做的方法是在数组的一次迭代中创建三个单独的数组:

  1. Negative numbers 负数
  2. 0s 0秒
  3. Positive numbers 正数

Squish the arrays together without sorting and you have your O(N) solution. 将数组压在一起而不进行排序,您将获得O(N)解决方案。

So based on sketrik answer which covers the logic, this is the code: 因此,根据涵盖逻辑的sketrik答案,这是代码:

 const myNumbers = '3,-2,1,0,-1,0,-2,1'; const arr = myNumbers.split(',').map(Number) const res = arr.filter(i => i < 0) .concat(arr.filter(i => i === 0)) .concat(arr.filter(i => i > 0)) console.log(res) 

This works thanks to two very basic JS methods of Array.prototype: 这要归功于Array.prototype的两个非常基本的JS方法:

concat and filter . concatfilter I could not explain them better than the documentation, check it out! 我无法比文档更好地解释它们,请查看!

But basically, what I am doing is: 但基本上,我正在做的是:

  1. find the chunk with negatives with arr.filter(i => i < 0) arr.filter(i => i < 0)查找带有负数的块
  2. find the chunk with zeros with arr.filter(i => i === 0) arr.filter(i => i === 0)查找零
  3. find the chunk with positives with arr.filter(i => i > 0) arr.filter(i => i > 0)查找带有正数的块
  4. concat them all into one array. concat它们全部组合成一个阵列。

I am Neo. 我是Neo。

 'use strict'; let myInput = '3,-2,1,0,-1,0,-2,1'; let myNumbers = myInput.split(',').map(Number); let negatives = []; let zeroes = []; let positives = []; for (const element of myNumbers) { if (element < 0) { negatives.push(element); } else if (element === 0) { zeroes.push(element); } else if (element > 0) { positives.push(element); } } let sortedArr = negatives.concat(zeroes, positives); console.log(sortedArr.join(',')); 

Logic or Typo? 逻辑还是错别字?

"...ascending order to all integers below zero and doing the opposite for those above..." “ ...对所有小于零的整数升序,对大于零的整数则相反...”

Following what was posted in question the examples should be: 按照所发布的内容,示例应为:

-2, -2, -1, 0, 0, 3, 1, 1 and -12, -2, 0, 0, 0, 13, 5, 3, 1 -2, -2, -1, 0, 0, 3, 1, 1-12, -2, 0, 0, 0, 13, 5, 3, 1

Zero and less ascending: -3, -2, -1, 0 . 零且递增程度较小: -3, -2, -1, 0 Greater than zero descending: 3, 2, 1 :大于零下降大于3, 2, 1

To get those results see Demo 1 . 要获得这些结果,请参见演示1


Strictly going by the examples is simpler: 严格按照示例进行操作比较简单:

-2, -1, -2, 0, 0, 3, 1, 1 and -12, -2, 0, 0, 0, 3, 13, 5, 1 -2, -1, -2, 0, 0, 3, 1, 1-12, -2, 0, 0, 0, 3, 13, 5, 1

Group negative numbers, then zeros, and then positive numbers: [-][0][+] . 分组负数,然后是零,然后是正数: [-][0][+] No order within the three arrays is required. 三个阵列中不需要顺序。 Order is only required for the three groups. 这三个组仅需订购。

To get those results see Demo 2 . 要获得这些结果,请参见演示2


Explanation 说明

Demo 1 演示1

  1. First, sort array in ascending order: 首先,按升序对数组进行排序:

    const ordered = array .sort ((current, next) => current - next); constordered = array .sort ((当前,下一个)=>当前-下一个);

  2. Next, find the index of the first number that's greater than 0, then extract all numbers beginning at that index and ending at the last number. 接下来,找到第一个大于0的数字的索引,然后提取所有从该索引开始到最后一个数字结束的数字。 Store the extracted array in a variable: 将提取的数组存储在变量中:

    const positive = ordered .splice (ordered .findIndex (number => number > 0)); const positive =有序.splice (有序.findIndex (数字=>数字> 0));

  3. Finally, sort extracted array in descending order and then concatenate the extracted array to the end of the original array: 最后,按降序对提取的数组进行排序,然后将提取的数组连接到原始数组的末尾:

    return ordered .concat (positive.sort((current, next) => next - current)); 返回有序的.concat (positive.sort((current,next)=> next-current));

Demo 2 演示2

  1. Create three new arrays returned by the filter() method: negative ( n < 0 ), zero ( n === 0) , and positive ( n > 0 ). 创建由filter()方法返回的三个新数组:负数( n < 0 ),零( n === 0)和正数( n > 0 )。

  2. Then concatenate them into one array: 然后将它们串联成一个数组:

    const negative = array.filter(number => number < 0); const negative = array.filter(number => number <0);

    const zero = array.filter(number => number === 0); const 0 = array.filter(number => number === 0);

    const positive = array.filter(number => number > 0); const positive = array.filter(number => number> 0);

    return negative.concat(zero, positive); 返回negative.concat(零,正);


Demo 1 演示1

 const unorderedA = [3, -2, 1, 0, -1, 0, -2, 1]; const unorderedB = [3, -12, 0, 0, 13, 5, 1, 0, -2]; const illogical = array => { const ordered = array.sort((current, next) => current - next); const positive = ordered.splice(ordered.findIndex(number => number > 0)); return ordered.concat(positive.sort((current, next) => next - current)); }; // For demonstration purposes const log = data => { const string = Array.isArray(data) ? `[${data.join(', ')}]` : data; return console.log(string); }; log(illogical(unorderedA)); log(illogical(unorderedB)); 

Demo 2 演示2

 const unorderedA = [3, -2, 1, 0, -1, 0, -2, 1]; const unorderedB = [3, -12, 0, 0, 13, 5, 1, 0, -2]; const illogical = array => { const negative = array.filter(number => number < 0); const zero = array.filter(number => number === 0); const positive = array.filter(number => number > 0); return negative.concat(zero, positive); }; // For demonstration purposes const log = data => { const string = Array.isArray(data) ? `[${data.join(', ')}]` : data; return console.log(string); }; log(illogical(unorderedA)); log(illogical(unorderedB)); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM