不格好エンジニア

wordpress.comから引っ越しました。

コーディング面接対策サイトCodilityの練習問題を解いてみた(CyclicRotation)

問題

与えられた配列aの各要素をk回,右に動かす(このとき、最後尾の要素は先頭に持ってくる)。

Codility

回答

def solution(a, k)
  b = []
  for current_index in 0..(a.length-1)
    new_index = (current_index + k) % a.length
    b[new_index] = a[current_index]
  end
  b
end

p solution([3,8,9,7,6], 3) == [9, 7, 6, 3, 8]
p solution([3,8,9,7,6], 0) == [3, 8, 9, 7, 6]
p solution([3,8,9,7,6], 5) == [3, 8, 9, 7, 6]

感想

パフォーマンスは気にしなくて良いらしい。 kが配列の要素数よりも大きい場合を考慮する必要がある。