How ruby takes out and rearranges duplicate values in an array

Asked 2 years ago, Updated 2 years ago, 30 views

Ruby takes out duplicate values in the array and
How do I sort them in order of the number of duplicates and output them as arrays?

[1,2,3,4,5,6,7,8,9,1,3,5,7,9,1,3,5,7,7,7,1,3,5,1,3,3,1,1]

[1,3,5,7,9]

ruby

2022-09-30 10:38

5 Answers

I tried using Ruby 2.7's tally.

arr=[1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 3, 5, 7, 9, 1, 3, 5, 7, 7, 7, 1, 3, 5, 7, 1, 3, 5, 7, 1, 3, 5, 5, 5, 7, 1, 3, 5, 1, 3, 1, 1, 1, 1, 1, 1, 1, 3, 3, 1, 1, 1, 1, 1, 3, 1, 3, 1, 1, 3, 1, 3, 1, 3, 1, 3, 1, 3, 1, 3, 1, 3, 1, 3, 1, 3, 1, 3, 1, 3, 1, 3, 7, 1, 3, 1, 3, 1, 3, 1, 3, 1, 3, 1, 3, 1, 3, 1, 3, 3, 1, 3, 3, 3, 1,
US>arr.tally.sort_by {|_,v|-v}.select {|i|i[1]>1}.map (&:first)

=>[1,3,5,7,9]


2022-09-30 10:38

I was able to execute it with the following code.

ary
.select {|v|arr.count(v)>1}#Remove less than one element
.sort {|a,b|arr.count(b)-arr.count(a)}#Sort by the number of elements
.uniq#Remove duplicate values


2022-09-30 10:38

I tried to deal with the specifications in a straightforward manner.

require 'test/unit'

define_ordered(list)
  list
    .group_by(&:itself)#{1=>[1,1,1,1,1,1],2=>[2],3=>[3,3,3,3,3],4=>[4],5=>[5,5,5,5],6=>[6],7=>[7,9,8];>[7,9];;;;8];
    .select {|_,v|v.size>1}#{1=>[1,1,1,1,1,1],3=>[3,3,3,3,3],5=>[5,5,5,5],7=>[7,7,7],9=>[9,9]}
    .sort_by{|_,v|-v.size}#[1,[1,1,1,1,1,1]],[3,[3,3,3,3,3]],[5,[5,5,5,5]],[7,7,7]],[9,9]]]]
    .map(&:first)#[1,3,5,7,9]
end

class UniqueOrderedTest<Test::Unit::TestCase
  default_unique_ordred
    input = [1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 3, 5, 7, 9, 1, 3, 5, 7, 7, 7, 1, 3, 5, 7, 1, 3, 5, 5, 7, 1, 3, 5, 1, 1, 1, 1, 1, 1, 1, 3, 5, 5, 5, 5, 5, 7, 1, 1, 1, 3, 3, 3, 3, 3, 1, 1, 3, 7, 1, 3, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
    assert_equal [1,3,5,7,9], unique_ordered (input)
  end
end


2022-09-30 10:38

What do you think like this?

arr=[1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 3, 5, 7, 9, 1, 3, 5, 7, 7, 7, 1, 3, 5, 7, 1, 3, 5, 7, 1, 3, 5, 5, 5, 7, 1, 3, 5, 1, 3, 1, 1, 1, 1, 1, 1, 1, 3, 3, 1, 1, 1, 1, 1, 3, 1, 3, 1, 1, 3, 1, 3, 1, 3, 1, 3, 1, 3, 1, 3, 1, 3, 1, 3, 1, 3, 1, 3, 1, 3, 1, 3, 7, 1, 3, 1, 3, 1, 3, 1, 3, 1, 3, 1, 3, 1, 3, 1, 3, 3, 1, 3, 3, 3, 1,
arr.inject(Hash.new(1)){|a,e|a[e]-=1;a}.select{|k,v|v.nonzero?}.sort_by {|k,v|v}.map(&first)    
=>[1,3,5,7,9] 


2022-09-30 10:38

I think it's okay if it's like this.

ary=[1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 3, 5, 7, 9, 1, 3, 5, 7, 7, 7, 1, 3, 5, 7, 1, 3, 5, 7, 1, 3, 5, 5, 5, 7, 1, 3, 5, 1, 3, 1, 1, 1, 1]
every
  .uniq
  .select {|v|ary.index(v)!=ary.rindex(v)}
  .sort_by { | v | -ary.count(v)}


2022-09-30 10:38

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.