Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/sorting/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby中的条件排序_Ruby_Sorting_Decimal_Bits - Fatal编程技术网

Ruby中的条件排序

Ruby中的条件排序,ruby,sorting,decimal,bits,Ruby,Sorting,Decimal,Bits,我有这个阵列: arr = [3, 8, 2, 13, 7] 我需要先按元素位的1的个数,然后按十进制数对元素进行排序: bits | decimal -----+-------- 10 | 2 11 | 3 0001 | 8 111 | 7 1011 | 13 要获得结果,请执行以下操作: [2, 3, 8, 7, 13] 我有以下代码: arr = arr.sort { |x, y| x <=> y } a

我有这个阵列:

arr = [3, 8, 2, 13, 7]
我需要先按元素位的1的个数,然后按十进制数对元素进行排序:

bits | decimal
-----+--------
  10 |       2
  11 |       3
0001 |       8
 111 |       7
1011 |      13
要获得结果,请执行以下操作:

[2, 3, 8, 7, 13]
我有以下代码:

arr = arr.sort { |x, y| x <=> y }
arr = arr.sort { |x, y| x.to_s(2).count(?1) <=> y.to_s(2).count(?1) }
arr # => [2, 8, 3, 13, 7]
arr=arr.sort{| x,y | x y}
arr=arr.sort{x,y | x.to_s(2).count(?1)y.to_s(2).count(?1)}
arr#=>[2,8,3,13,7]
我怎样才能修好它

arr.sort_by { |item| [item.to_s(2).count(?1), item] }
# => [2, 8, 3, 7, 13]
这与所述的期望输出相矛盾,但我相信这与问题的描述是一致的(并且所述的期望输出是不正确的):2、8各有1位,3各有2、7和13各有3位;2先于8,7先于13

这是因为数组的默认比较器是按元素进行比较;e、 g.对于
2
8
,比较器看到
[1,2][1,8]
;因为第一个元素是相同的,所以将第二个元素作为一个断开连接的元素进行比较

我把“十进制”理解为“数值”,如OP的代码所示;如果它被字面理解为“十进制表示”,那么


你所说的“按你的比特数1排序”是什么意思?在什么系统下,
0001
等于十进制
8
?@moveson我很确定这是
1000
的打字错误。你是说“按1排序”和“按1的数量排序”一样吗?你试图在这里定义平局破坏者代码,但从数字上来说,这些值平局的唯一方式是如果它们相等,那么平局破坏者就不相关了。为什么3应该在8之前?还有,你说的“按小数点”是什么意思?Decimal是一种表示,一个字符串,所以13应该在7之前?@StefanPochmann:“期望的结果”与问题陈述相矛盾,正如你自己所指出的。Ok:-)。顺便说一句,我同意你的第一个解决方案可能是他想要的(我已经写了同样的,同时还写了一条尖刻的评论,嘲笑他的句子“先按1的位数排序元素,然后按小数点排序”的逐条翻译在我发布之前,我只是在等待他确认/修复他的错误…
arr.sort_by{| item |[item.digits(2).count(1),items]}
是另一种选择。按字母顺序排列数字似乎很奇怪<代码>10、11、100、2?@Amadan谢谢你的解决方案,这就是我需要的。对不起大家,我的问题不好!
arr.sort_by { |item| [item.to_s(2).count(?1), item.to_s] }
# => [2, 8, 3, 13, 7]