「10分でコーディング」やってみた(Ruby)


たぶん10分以内にできたと思う。

問題は、num_player 人のプレーヤーに deck で与えられたカードを切るというもの。ただし、全員に同じ枚数だけ配らないといけない。

class Cards
  def deal(num_players, deck)
    ar = Array.new(num_players) {""}
    (deck.length / num_players).times do |i|
      num_players.times {|j| ar[j] += deck[i * num_players + j]}
    end
    ar
  end
end

p Cards.new.deal(4, "123123123")    #=>["12", "23", "31", "12"]
p Cards.new.deal(6, "01234")        #=>["", "", "", "", "", ""]

 
 

もう一問やってみた(15分)

問題なし。簡単。

class ReportAccess
  def who_can_see(user_names, allowed_data, report_data)
    ar = []
    user_names.each_with_index do |uname, i|
      ad = allowed_data[i].split(" ")
      catch(:exit) do
        report_data.each {|d| throw(:exit) unless ad.include?(d)}
        ar << uname
      end
    end
    ar
  end
end

ra = ReportAccess.new
p ra.who_can_see(["joe", "nick", "ted"],
                 ["clients products", "products orders", "clients orders"],
                 ["clients", "products"])
#=>["joe"]

 
 

さらにもうひとつ(10分)

問題なし。簡単。

class CCipher
  def decode(ciphertest, shift)
    st = ""
    ciphertest.each_byte do |byte|
      nb = byte - shift
      nb += 26 if nb < 65
      st += nb.chr
    end
    st
  end
end

p CCipher.new.decode("VQREQFGT", 2)    #=>"TOPCODER"

 
リンク先のブログ主は Java でコーディングしておられるが、Rubyist からは Java は書くことが多すぎるように見える。