2
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 コーディングテスト 便利メソッド一覧

Last updated at Posted at 2022-06-05

※自分用メモ
Rubyによるコーディングテストまたは競技プログラミングにうまく使えそうなメソッド一覧

irb上で処理速度を計測

irb(main):001:0> IRB.conf[:MEASURE] = true  
# または
irb(main):001:0> measure

[243,156,104,280,196,132,128,195,265,300,130].combination(5).select {|a| a.sum == 1000}
processing time: 0.000076s

Array#combination(組み合わせ)

a = [1, 2, 3, 4]
a.combination(1).to_a  #=> [[1],[2],[3],[4]]
a.combination(3).to_a  #=> [[1,2,3],[1,2,4],[1,3,4],[2,3,4]]

Array#permutation(順列)

a = [1,2,3]
a.permutation(2).to_a #=> [[1, 2], [1, 3], [2, 1], [2, 3], [3, 1], [3, 2]]

Array#product

[1,2,3].product([4,5])     # => [[1,4],[1,5],[2,4],[2,5],[3,4],[3,5]]
[1,2].product([1,2])       # => [[1,1],[1,2],[2,1],[2,2]]
[1,2].product([3,4],[5,6]) # => [[1,3,5],[1,3,6],[1,4,5],[1,4,6],[2,3,5],[2,3,6],[2,4,5],[2,4,6]]

Array#inject or Hash#inject

# 合計を計算する。
[2, 3, 4, 5].inject {|result, item| result + item }       #=> 14

[2, 3, 4, 5].inject(0) {|result, item| result + item**2 } #=> 54

Integer#prime_division

require 'prime'
# 素数とその数を求める
12.prime_division #=> [[2,2], [3,1]]
10.prime_division #=> [[2,1], [5,1]]

Prime.each(20).to_a #=> [2, 3, 5, 7, 11, 13, 17, 19]
# 小さな値から順に N 個の素数を求める
Prime.take(10) #=> [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]

Integer#lcm

# 最小公倍数を出す
4.lcm(3) #=> 12

Integer#gcd

# 最大公約数を出す
18.gcd(27) #=> 9

Integer#pow(冪乗を計算)

# 3の4乗を8で割ったあまりを出力
5.pow(3,  8)  # =>  5

Array#tally

# 要素ごとの数を求める
[1,2,3,4,1,1].tally #=> {1=>3, 2=>1, 3=>1, 4=>1}

Array#tranpose

# 行列の行と列を転移させる
[[1,2],[3,4],[5,6]].transpose
# => [[1, 3, 5], [2, 4, 6]]

Integer#[]

# ビット変換し、ビットが立っていた場合1を返す
例: 6 ⇨ 110
6[0] #=> 0
6[1] #=> 1
6[2] #=> 1

Object#tap


(1..10)                  .tap {|x| puts "original: #{x}" }
  .to_a                  .tap {|x| puts "array:    #{x}" }
  .select {|x| x.even? } .tap {|x| puts "evens:    #{x}" }
  .map {|x| x*x }        .tap {|x| puts "squares:  #{x}" }

Enumetable#partition

[10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0].partition {|i| i % 3 == 0 }
 #=> [[9, 6, 3, 0], [10, 8, 7, 5, 4, 2, 1]]
2
0
1

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
2
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?