AOJ(問題集)23

0220 Binary Digit A Doctor Loved

小数の2進表現かあ。勉強になるなあ。なお、10進表現で循環小数でなくとも、2進表現で循環小数になる場合がある。

def calc(r, str = "")
  return str if str.length > 4
  a = r * 2
  b = a.to_i
  str += b.to_s
  c = a - b
  if c.zero?
    return str
  else
    calc(c, str)
  end
end


until (n = gets.to_f.rationalize) < 0
  integer_part = n.to_i
  decimal_part = n - integer_part
  
  result = "NA"
  str = integer_part.to_s(2)
  if str.length <= 8
    str = str.rjust(8, "0")
    tmp = calc(decimal_part)
    if tmp.length <= 4
      result = str + "." + tmp.ljust(4, "0")
    end
  end
  
  puts result
end

 

0221 FizzBuzz

発言データを一気読みしていなくてハマった。0.24秒。

e = Enumerator.new do |y|
  i = 1
  loop do
    y << case
         when (i % 15).zero? then "FizzBuzz"
         when (i %  3).zero? then "Fizz"
         when (i %  5).zero? then "Buzz"
         else i.to_s
         end
    i += 1
  end
end

until (given = gets.chomp) == "0 0"
  m, n = given.split.map(&:to_i)
  data = n.times.map {gets.chomp}
  table = Array.new(m, true)
  pointer = 0
  count = m
  
  inc = ->{
    pointer += 1
    pointer = 0 if pointer >= m
  }
  
  data.each do |said|
    break if count == 1
    inc.() until table[pointer]
    if said != e.next
      table[pointer] = false
      count -= 1
    end
    inc.()
  end
  
  puts table.map.with_index {|a, i| a ? (i + 1).to_s : nil}.compact.join(" ")
  e.rewind
end

 
これで0.21秒。あまり変わらないな。

e = Enumerator.new do |y|
  i = 1
  loop do
    y << case
         when (i % 15).zero? then "FizzBuzz"
         when (i %  3).zero? then "Fizz"
         when (i %  5).zero? then "Buzz"
         else i.to_s
         end
    i += 1
  end
end

until (given = gets.chomp) == "0 0"
  m, n = given.split.map(&:to_i)
  data = n.times.map {gets.chomp}
  table = (1..m).map(&:itself)
  pointer = 0
  
  data.each do |said|
    if said != e.next
      table.delete_at(pointer)
      break if table.size == 1
    else
      pointer += 1
    end
    pointer = 0 if pointer >= table.size
  end
  
  puts table.join(" ")
  e.rewind
end