Hatena::Grouprubyist

てーげーRuby

2008-06-30

練習問題 ハッシュ(後半)

| 19:36

(5) 順番を保存するハッシュ、OrderdHashクラスを定義してください。

こんなんでいいでしょうか。

  1 class OrderdHash
  2   include Enumerable
  3
  4   def initialize
  5     @hash_ary = []
  6   end
  7
  8   def []=(key, val)
  9     @hash_ary.each do |e|
 10       e[key]=val if e.key?(key)
 11     end
 12     @hash_ary << Hash[key, val]
 13   end
 14
 15   def [](key)
 16     @hash_ary.each do |e|
 17       return e[key] if e.key?(key)
 18     end
 19     return nil
 20   end
 21
 22   def each
 23     @hash_ary.each do |e|
 24       ary = e.to_a.flatten
 25       yield(ary[0], ary[1])
 26     end
 27   end
 28 end
irb(main):096:0> load 'orderd_hash.rb'
=> true
irb(main):097:0> h = OrderdHash.new
=> #<OrderdHash:0xb7f72544 @hash_ary=[]>
irb(main):098:0> h["one"] = 1
=> 1
irb(main):099:0> h["two"] = 2
=> 2
irb(main):100:0> h["three"] = 3
=> 3
irb(main):101:0> h["four"] = 4
=> 4
irb(main):102:0> h["five"] = 5
=> 5
irb(main):103:0> h.each do |k,v|
irb(main):104:1*  puts "key is #{k} and value is #{v}"
irb(main):105:1> end
key is one and value is 1
key is two and value is 2
key is three and value is 3
key is four and value is 4
key is five and value is 5
=> [{"one"=>1}, {"two"=>2}, {"three"=>3}, {"four"=>4}, {"five"=>5}]

練習問題 文字列(後半)

| 17:13

(2) "七千百二十三"といった、漢数字による数の表現を、「7123」のような

数値に変換するメソッドkan2numを定義してください。

lock
irb(main):001:0> load "kan2num.rb"
=> true
irb(main):002:0> kan2num("七千百二十三")
=> 7123

(3) "12"といった数値による文字列を、"**********"というように、その数だけ

*」が並ぶ文字列に変換するメソッドnum2astriskを、Numericクラス(またはその

サブクラス)のオブジェクトやメソッドを使わずに定義してください。

  1 def num2astrisk(num)
  2   print_astrisk = ""
  3   keta = 1
  4   num.scan(/./).reverse.each do |e|
  5     if e == "0"
  6     elsif e == "1"
  7       astrisk = "*"
  8     elsif e == "2"
  9       astrisk = "**"
 10     elsif e == "3"
 11       astrisk = "***"
 12     elsif e == "4"
 13       astrisk = "****"
 14     elsif e == "5"
 15       astrisk = "*****"
 16     elsif e == "6"
 17       astrisk = "******"
 18     elsif e == "7"
 19       astrisk = "*******"
 20     elsif e == "8"
 21       astrisk = "********"
 22     elsif e == "9"
 23       astrisk = "*********"
 24     end
 25     print_astrisk += astrisk * keta if astrisk
 26     keta = keta*10
 27   end
 28
 29   puts print_astrisk
 30 end
irb(main):001:0> load "num2astrisk.rb"
=> true
irb(main):002:0> num2astrisk("12")
************
=> nil
irb(main):003:0> num2astrisk("100")
****************************************************************************************************
=> nil

練習問題 文字列(前半)

| 17:09

(1) "ruby is an object oriented programming language"という

文字列があります。この文字列を使って次の処理を行ってください

(a) 文字列に含まれる各単語を要素とする配列を作ってください。

irb(main):041:0> "ruby is an object oriented programming language".split
=> ["ruby", "is", "an", "object", "oriented", "programming", "language"]

(b) (a)の配列をアルファベット順にソートしてください。

irb(main):042:0> "ruby is an object oriented programming language".split.sort
=> ["an", "is", "language", "object", "oriented", "programming", "ruby"]

(c) (a)の配列を大文字と小文字の区別をせずにアルファベット順に

ソートしてください。

irb(main):046:0> "ruby is an object oriented programming language".split.sort_by{|e| e.upcase}
=> ["an", "is", "language", "object", "oriented", "programming", "ruby"]

(d) すべての単語の先頭を大文字にして

"Ruby Is An Object Oriented Programming Language"

にしてください。

irb(main):050:0> "ruby is an object oriented programming language".split.map{|e| e.capitalize}.join(' ')
=> "Ruby Is An Object Oriented Programming Language"

(e) 文字列に含まれる文字とその数を次のような形式で表示させてください

(空白文字が6つ、'R'が1つ、'a'が4つ、'b'が……という意味です)

' ': ******

'R': *

'a': ****

'b': **

'c': *

...

irb(main):148:0> h = Hash.new
=> {}
irb(main):149:0>
irb(main):150:0* "ruby is an object oriented programming language".scan(/./).sort.each do |e|
irb(main):151:1*   unless h[e]
irb(main):152:2>      h[e] = 1
irb(main):153:2>   else
irb(main):154:2*      h[e]+=1
irb(main):155:2>   end
irb(main):156:1> end
=> [" ", " ", " ", " ", " ", " ", "a", "a", "a", "a", "b", "b", "c", "d", "e", "e", "e", "e", "g", "g", "g", "g", "i", "i", "i", "j", "l", "m", "m", "n", "n", "n", "n", "o", "o", "o", "p", "r", "r", "r", "r", "s", "t", "t", "u", "u", "y"]
irb(main):157:0>
irb(main):158:0* h.each do |k,v|
irb(main):159:1*  puts("'#{k}': #{'*'*v}")
irb(main):160:1> end
' ': ******
'l': *
'a': ****
'm': **
'b': **
'y': *
'n': ****
'c': *
'o': ***
'd': *
'p': *
'e': ****
'r': ****
'g': ****
's': *
't': **
'i': ***
'u': **
'j': *
=> {" "=>6, "l"=>1, "a"=>4, "m"=>2, "b"=>2, "y"=>1, "n"=>4, "c"=>1, "o"=>3, "d"=>1, "p"=>1, "e"=>4, "r"=>4, "g"=>4, "s"=>1, "t"=>2, "i"=>3, "u"=>2, "j"=>1}


練習問題 数値

| 17:07

(3) randメソッドを用いて、1~6までの数字をランダムに返すメソッドdice

定義してください。

irb(main):050:0> def dice
irb(main):051:1>  rand(6)+1
irb(main):052:1> end
=> nil
irb(main):053:0> dice
=> 5
irb(main):054:0> dice
=> 3
irb(main):055:0> dice
=> 5
irb(main):056:0> dice
=> 4

(4) 整数numが素数であるかどうかを調べるメソッドprime?を定義してください。

def prime?(num)
  prime = true
  2.upto(num - 1) do |n|
    if num % n == 0
      prime = false
    end
  end
  prime
end

練習問題 配列(後半)

| 17:06

(7) 1から100までの要素を含む配列aryから、1~10、11~20、21~30と

いうように10個の要素を含む配列を10個取り出します。取り出した

すべての配列を、順に別の配列resultに格納するとき、以下の???の

部分に当てはまる式を考えてください。

ary = [1~100の要素を含む配列]

result = Array.new

10.times { |i|

result << ary[???]

}

irb(main):174:0> ary = Array(1..100)
=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100]
irb(main):175:0> result = Array.new
=> []
irb(main):176:0> 10.times{|i| result << ary[i*10, 10]}
=> 10
irb(main):177:0> result
=> [[1, 2, 3, 4, 5, 6, 7, 8, 9, 10], [11, 12, 13, 14, 15, 16, 17, 18, 19, 20], [21, 22, 23, 24, 25, 26, 27, 28, 29, 30], [31, 32, 33, 34, 35, 36, 37, 38, 39, 40], [41, 42, 43, 44, 45, 46, 47, 48, 49, 50], [51, 52, 53, 54, 55, 56, 57, 58, 59, 60], [61, 62, 63, 64, 65, 66, 67, 68, 69, 70], [71, 72, 73, 74, 75, 76, 77, 78, 79, 80], [81, 82, 83, 84, 85, 86, 87, 88, 89, 90], [91, 92, 93, 94, 95, 96, 97, 98, 99, 100]]

(8) 数値からなる配列nums1とnums2に対して、それらの個々の要素を足し合わせた

要素からなる配列を返すメソッドsum_arrayを定義してください。

irb(main):190:0> def sum_array(nums1, nums2)
irb(main):191:1>   nums1.each_index{|k| nums1[k] += nums2[k] }
irb(main):192:1> end
=> nil
irb(main):193:0> nums1 = Array(1..100)
=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100]
irb(main):194:0> nums2 = Array(1..100)
=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100]
irb(main):195:0> sum_array(nums1,nums2)
=> [2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 34, 36, 38, 40, 42, 44, 46, 48, 50, 52, 54, 56, 58, 60, 62, 64, 66, 68, 70, 72, 74, 76, 78, 80, 82, 84, 86, 88, 90, 92, 94, 96, 98, 100, 102, 104, 106, 108, 110, 112, 114, 116, 118, 120, 122, 124, 126, 128, 130, 132, 134, 136, 138, 140, 142, 144, 146, 148, 150, 152, 154, 156, 158, 160, 162, 164, 166, 168, 170, 172, 174, 176, 178, 180, 182, 184, 186, 188, 190, 192, 194, 196, 198, 200]

Array#zipに足し算するブロックを渡して配列に詰める方がいい

irb(main):339:0> num1 = [1,2,3,4,5]
=> [1, 2, 3, 4, 5]
irb(main):340:0>  num2 = [1,2,3]
=> [1, 2, 3]
irb(main):341:0> num1.zip(num2)
=> [[1, 1], [2, 2], [3, 3], [4, nil], [5, nil]]
irb(main):342:0>  num1.zip(num2) do |a, b|
irb(main):343:1*    a ||= 0
irb(main):344:1>    b ||= 0
irb(main):345:1>  result << a + b
irb(main):346:1> end
=> nil
irb(main):347:0> result
=> [2, 4, 6, 4, 5]

(9) (、)、{、}という4つの文字を要素とした配列があります。この配列に

対して、カッコが正しく対応していうかどうかを調べるメソッド、

balanced?を定義してください。なお、「カッコが正しく対応している」とは

・(と)の数が同じ

・{と}の数が同じ

・「()」の対応と「{}」の対応が交差することがない

といった状態のことです。

def balanced?(ary)
  return false if ary.select{|e| e == '('}.size != ary.select{|e| e == ')'}.size
  return false if ary.select{|e| e == '{'}.size != ary.select{|e| e == '}'}.size

  chk_ary = []
  ary_reverse = ary.reverse
  ary.each_index do |idx|
    chk_ary << ary[idx] if ary[idx] == '(' && ary_reverse[idx] == ')'
    chk_ary << ary[idx] if ary[idx] == '{' && ary_reverse[idx] == '}'
    chk_ary << ary[idx] if ary[idx] == ')' && ary_reverse[idx] == '('
    chk_ary << ary[idx] if ary[idx] == '}' && ary_reverse[idx] == '{'
  end
  return false if chk_ary.size != ary.size
  true
end
irb(main):308:0> balanced?("{((({()})))}".scan(/./))
=> true
irb(main):311:0>  balanced?(["(", "{", "}", ")"])
=> true
irb(main):312:0> balanced?(["(", ")", "{"])
=> false
irb(main):313:0> balanced?(["{", "}", "("])
=> false
irb(main):314:0> balanced?(["(", "{", ")", "}"])
=> false

ほんとはこういう対応モノ(HTMLのタグとか)はスタックでやるものですね

ゲスト



トラックバック - http://rubyist.g.hatena.ne.jp/tohtas/20080630