0
0

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 1 year has passed since last update.

Ruby問題 配列の並び替え

Posted at

(1) 配列の並び替え

【Q】 数字の配列を、偶数はそのままの位置で、奇数のみを昇順に並び替えなさい。

例)
[7, 1]  =>  [1, 7]
[5, 8, 6, 3, 4]  =>  [3, 8, 6, 5, 4]
[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]  =>  [1, 8, 3, 6, 5, 4, 7, 2, 9, 0]

私の回答

def sort_array(array)
  oddsArr = array.select {|n| n.odd? }.sort
  array.map {|n| n.even? ? n : oddsArr.shift }
end
  1. 配列の中から奇数のみを取り出したいので、selectメソッドを使いました。
    sortメソッドで昇降順に並び替えて、新しい配列に入れます。

  2. 元の配列を三項演算子を使って、並び替えます。
    n.even? 偶数であるかどうかを判断
    YES => そのまま配列に入れる
    NO => 奇数なので、oddsArrからshiftメソッドで1個ずつ取り出して返していきます。

0
0
0

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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?