12
12

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Ruby - 配列から最頻出要素を取り出す問題

Posted at

@KaitoMiyazaki から、配列から最頻出要素を取り出す問題を出されたので、
解いてみましたー

問題

[3, 2, 3, 4, 4, 4, 6]

以下のような配列があります。
この中から最頻出要素を取り出してください。
つまり4

私の回答

ary = [3, 2, 3, 4, 4, 4, 6]
ary.uniq.sort_by{|x| ary.count x }.reverse[0]

( ˘⊖˘)。o(これはRubyっぽくない)

ary = [3, 2, 3, 4, 4, 4, 6]
ary.uniq.sort{|x,y| ary.count(y) <=> ary.count(x) }[0]

こんな感じかなー

他にも思いついた回答あったらくださいー

12
12
4

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
12
12

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?