Skip to content

Instantly share code, notes, and snippets.

@qsona
Created October 13, 2018 14:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save qsona/a07f6b1bb45976f5ba1ccdea6d0cfbbe to your computer and use it in GitHub Desktop.
Save qsona/a07f6b1bb45976f5ba1ccdea6d0cfbbe to your computer and use it in GitHub Desktop.
# 22 引数に配列をとって、重複している値を昇順の配列にして返す関数を作れ。
# 例)引数 [1, 3, 2, 3, 8, 3, 2] => 返り値 [2, 3]
def q22(array)
dup = {} # key: number, value: duplicate count (2以上のときは2)
ans = []
array.each do |num|
case dup[num]
when nil
dup[num] = 1
when 1
dup[num] = 2
ans << num
end
end
ans.sort
end
p q22([1, 3, 2, 3, 8, 3, 2])
# 22 引数に配列をとって、重複している値を昇順の配列にして返す関数を作れ。
# 例)引数 [1, 3, 2, 3, 8, 3, 2] => 返り値 [2, 3]
def q22_2(array)
dup = {} # key: number, value: Bool (true if the num is duplicated)
array.each { |num| dup[num] = !dup[num].nil? }
ans = []
dup.each { |num, is_dup| ans << num if is_dup }
ans.sort
end
p q22_2([1, 3, 2, 3, 8, 3, 2])
# q23.
# 引数に配列をとり、重複している要素の値をキー、重複した回数を値にもつハッシュを返す関数を作れ。
# e.g. 引数[1,3,2,3,8,3,2] => 返り値{2=>2,3=>3}
def q23(array)
hash = {}
array.each do |num|
hash[num] ||= 0
hash[num] += 1
end
hash.select { |k, v| v >= 2 }.to_h
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment