检查是否数组已经排序? [英] Check to see if an array is already sorted?

查看:118
本文介绍了检查是否数组已经排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道如何的的为了一个阵列,但在这种情况下,我只是想看看它的的秩序。字符串数组是最简单的,我想,并在这一方面的回答美联社preciated,但包括检查依据一些任意参数顺序的能力,答案是最优的。

I know how to put an array in order, but in this case I just want to see if it is in order. An array of strings would be the easiest, I imagine, and answers on that front are appreciated, but an answer that includes the ability to check for order based on some arbitrary parameter is optimal.

下面是一个例子的数据集。名称:

Here's an example dataset. The name of:

[["a", 3],["b",53],["c",2]]

当元件是本身包含几个元件,其中第一个是一个字符串数组。我想看看如果这些元素基于此字符串按字母顺序排列。

Where the elements are themselves arrays containing several elements, the first of which is a string. I want to see if the elements are in alphabetical order based on this string.

推荐答案

让我们打开可枚举对于这样一个通用的抽象:

Let's open Enumerable for such a generic abstraction:

module Enumerable
  def sorted?
    each_cons(2).all? { |a, b| (a <=> b) <= 0 }
  end
end

[["a", 3], ["b", 53],["c", 2]].sorted? #=> true

公告称,不幸的是,我们必须写(A&LT; =&GT; B)&LT; = 0 而不是 A&LT; = b 因为有支持类&LT; =&GT; 但没有比较运营商(即阵列),因为它们不包括模块比较

Notice that, unfortunately, we have to write (a <=> b) <= 0 instead of a <= b because there are classes that support <=> but not the comparator operators (i.e. Array), because they do not include the module Comparator.

您也说您想拥有检查基于一些任意参数顺序的能力。有了同样的想法:

You also said you'd like to have the ability "to check for order based on some arbitrary parameter". With the same idea:

module Enumerable  
  def sorted_by?
    each_cons(2).all? { |a, b| ((yield a) <=> (yield b)) <= 0 }    
  end
end

[["a", 3], ["b", 1], ["c", 2]].sorted_by? { |k, v| v } #=> false

使用懒惰可枚举(红宝石=> 2.1),它的好得多,我们可以重新使用我们的previous抽象可枚举#分类写:

With lazy enumerables (Ruby => 2.1) it's much nicer, we can re-use our previous abstraction Enumerable#sorted? and write:

module Enumerable  
  def sorted_by?(&block)
    lazy.map(&block).sorted?
  end
end

这篇关于检查是否数组已经排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆