Help us understand the problem. What is going on with this article?

rubyでスターリンソートをやってみた(ブロック渡しも可能)

今話題のスターリンソートruby で実装してみました。

準備

stalin_sort.rb
class Array
  # Githubの実装と同様
  def stalin_sort
    return [] if empty?

    max = first
    select do |x|
      next if max > x

      max = x
      x
    end
  end

  # ブロックあり
  def stalin_sort_by(&block)
    return [] if empty?

    max = yield(first)
    map { |x| [yield(x), x] }
      .select { |y, _x| next if max > y; max = y }
      .map    { |_y, x| x }
  end
end

Githubの実装Array を引数に取り実行していますが、 ruby の良さを活かすためクラス拡張に変更しました。

実行

[1, 2, 1, 1, 4, 3, 9].stalin_sort
# => [1, 2, 4, 9]

names = %w(alice bob ava benjamin carol)

# ブロックなし
names.stalin_sort
# => ["alice", "bob", "carol"]

# ブロックあり
names.stalin_sort_by(&:length)
# => ["alice", "benjamin"]

簡単になりますが以上です。
掲載したものより良いコードがあれば是非ともお願いします!

引用元

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした