2014年4月7日月曜日

AOJ 0029 ruby

AOJの0029、英文中に出てくる単語で最頻出のものと最長文字数のものを表示する問題です。
http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=0029



単語の出現頻度をカウントするためにcという配列を作ったのですが、それを初期化する際に学んだことのメモです。RubyでArrayクラスを使って配列オブジェクトを作成するにはいくつか方法があるそうですが、以下のふたつには微妙な違いが。

1
test = ["hoge","hoge","hoge"]
という風に各要素を指定した配列を作成したいとき、

「1.newメソッドを使った場合」
1
2
3
4
5
test = Array.new(3,"hoge")
 
# test = ["hoge","hoge","hoge"]
test[0].reverse! #test[0]の順番を逆にしてみると
# test = ["egoh","egoh","egoh"]
「2.ブロック付きのnewメソッドを使った場合」
1
2
3
4
5
test = Array.new(3) {"hoge"}
 
# test = ["hoge","hoge","hoge"]
test[0].reverse! #test[0]の順番を逆にしてみると
# test = ["egoh","hoge","hoge"]

上記のように、1では各要素に全て同一のオブジェクトが代入されてしまい、どれかひとつに変更を加えるとそれ以外全ての要素にも影響が出るようです。一方2では各要素は別々のオブジェクトになるので、それぞれに個別の操作ができます。にょーんって感じですね。

参考にさせていただいたサイト
http://www.rubylife.jp/ini/array/index3.html

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
words = gets
words = words.to_s.split(" ")
len = words.size #配列の要素数
 
max = 0
fre = 0
ans_max = 0
ans_fre = 0
c = Array.new(len){0}
 
len.times do |i|
    #単語の出現頻度
    i.times do |j|
        if words[i] == words[j] then
            c[i] += 1
        end
    end
    if c[i] > fre then
        fre = c[i]
        ans_fre = i
    end
    #単語の文字数
    num = words[i].size
    if num > max then
        max = num
        ans_max = i
    end
end
 
puts "#{words[ans_fre]} #{words[ans_max]}"

0 件のコメント:

コメントを投稿