ハイパーニートプログラマーへの道

頑張ったり頑張らなかったり

【Crystal】ランダムな数の中から最も差が小さい2つの数を取得する

Crystal 0.20.0
crystal play上で実行

def closest_two_numbers
  xx, yy, dd = 0, 0, 0
  dd = Float64::INFINITY
  seq = (1..100).map { Random.rand(10**10) }.sort.uniq
  seq.each_cons(2) do |cons|
    x, y = cons[0], cons[1]
    d = (x - y).abs
    if d < dd
      xx, yy, dd = x, y, d
    end
  end
  return [xx, yy, dd]
end

results = closest_two_numbers
puts "
the closest two numbers
-----------------------
1st number: #{results[0]}
2nd number: #{results[1]}
difference: #{results[2]}
"

なぜdd = Float64::INFINITYで正の無限大を用意しているかというと、1番最初のd < dd の比較に使用するため。
以降は、2つの数の差(d) をddに格納しておき、それをまた新たな2つの数の差と比較していくと。

実行結果は

the closest two numbers
-----------------------
1st number: 414497986
2nd number: 414546754
difference: 48768

こちらがPython3バージョン

from random import randrange
seq = sorted([randrange(10**10) for i in range(100)])
dd = float("inf")
for i in range(len(seq)-1):
  x, y = seq[i], seq[i+1]
  if x == y:
    continue
  d = abs(x-y)
  if d < dd:
    xx, yy, dd = x, y, d

result = """
the closest two numbers
-----------------------
1st number: %d
2nd number: %d
difference: %d
""" % (xx, yy, dd)

print(result)
the closest two numbers
-----------------------
1st number: 6437661962
2nd number: 6438850998
difference: 1189036

元ネタはこちらの Chapter 4 - INDUCTION AND RECURSION ... AND REDUCTION より

Python Algorithms: Mastering Basic Algorithms in the Python Language

Python Algorithms: Mastering Basic Algorithms in the Python Language