AOJ(問題集)6

AIZU ONLINE JUDGE: Programming Challenge
 

0051 Differential II

$<.readlines.drop(1).map {|a| a.chomp.chars.map(&:to_i).sort}.each do |ary|
  puts ary.reverse.join.to_i - ary.join.to_i
end

 

0052 Factorial II

until (n = $<.gets.to_i).zero?
  five = n / 5
  f = ->(x) {
    return five if n < x
    five += n / x
    f.(x * 5)
  }
  puts f.(25)
end

これはちょっと考えました。
 

0053 Sum of Prime Numbers

require 'prime'

nums = []
h = {}
until (i = $<.gets.to_i).zero?
  nums << i
  h[i] = 0
end
max_num = nums.max

sum = 0
Prime.each.with_index do |prime, i|
  break if i + 1 > max_num
  sum += prime
  h[i + 1] = sum if h[i + 1]
end
nums.each {|j| puts h[j]}

与えられた値が重複しているのだな。結構いい成績だった。
 

0054 Sum of Nth decimal places

$<.readlines.map {|a| a.split.map(&:to_i)}.each do |a, b, n|
  f = ->(x, i = 1, sum = 0) {
    return sum if i > n or x.zero?
    f.(x * 10 % b, i + 1, sum + x * 10 / b)
  }
  puts f.(a % b)
end

 

0055 Sequence

$<.readlines.map(&:to_f).each do |x|
  sum = 0
  solve = ->(n, i = 1) {
    sum += n
    return sum if i == 10
    (i + 1).even? ? solve.(n * 2.0, i + 1) : solve.(n / 3.0, i + 1)
  }
  puts solve.(x)
end

 

0056 Goldbach's Conjecture

require 'prime'

h = {}
primes = Prime.each(50000).to_a
primes.each {|pr| h[pr] = true}
until (n = $<.gets.to_i).zero?
  co = 0
  if n.odd?
    co = 1 if h[n - 2]
  else
    primes.each do |pr|
      break if pr > n / 2
      co += 1 if h[n - pr]
    end 
  end
  puts co
end

何か変なミスをしていた。何とタイムは挑戦者中最速。
 

0057 The Number of Area

$<.readlines.map(&:to_i).each do |n|
  puts 2 + (n - 1) * (n + 2) / 2
end

 

0058 Orthogonal

$<.readlines.map {|l| l.split.map(&:to_r)}.each do |xa, ya, xb, yb, xc, yc, xd, yd|
  x1, y1 = xb - xa, yb - ya
  x2, y2 = xd - xc, yd - yc
  puts x1 * x2 + y1 * y2 == 0 ? "YES" : "NO"
end

 

0059 Intersection of Rectangles

while (st = $<.gets)
  xa1, ya1, xa2, ya2, xb1, yb1, xb2, yb2 = st.split.map(&:to_f)
  if !(xa1 > xb2 or xa2 < xb1 or ya1 > yb2 or ya2 < yb1)
    puts "YES"
  else
    puts "NO"
  end
end

こんなに簡単なものが条件を見落としていた…。
 

0060 Card Game

$<.readlines.map {|a| a.split.map(&:to_i)}.each do |my1, my2, opp1|
  deck = [*1..10] - [my1, my2, opp1]
  limit = 20 - (my1 + my2)
  p = 0
  deck.each do |opp2|  
    n = (deck - [opp2]).take_while {|i| i <= limit}.size
    p += 1/7r * Rational(n, 6)
  end
  puts p >= 1/2r ? "YES" : "NO"
end