ruby勉強会の演習問題を解いてみた

ruby関係はこっちに纏めるために移行&一部修正。

※for while禁止

1.九九の表を作成

  |  1  2  3  4  5  6  7  8  9
--+---------------------------
1 |  1  2  3  4  5  6  7  8  9
2 |  2  4  6  8 10 12 14 16 18
3 |  3  6  9 12 15 18 21 24 27
4 |  4  8 12 16 20 24 28 32 36
5 |  5 10 15 20 25 30 35 40 45
6 |  6 12 18 24 30 36 42 48 54
7 |  7 14 21 28 35 42 49 56 63
8 |  8 16 24 32 40 48 56 64 72
9 |  9 18 27 36 45 54 63 72 81
x = (1..9).to_a
y = x
#y = (1..9).to_a
puts("  |  " + x.join("  "))
puts("--+---------------------------")
x.each do |i|
  printf("%i |" ,i)
  y.each{|j| printf("%3i" ,i*j)}
  printf("\n")
end

2.100マス計算

  |  1  9  2  3  7  5  6  4  8
--+---------------------------
 3|
 8|
 1|
 5|
 6|
 7|
 4|
 2|
 9|

  |  1  9  2  3  7  5  6  4  8
--+---------------------------
 3|  3 27  6  9 21 15 18 12 24
 8|  8 72 16 24 56 40 48 32 64
 1|  1  9  2  3  7  5  6  4  8
 5|  5 45 10 15 35 25 30 20 40
 6|  6 54 12 18 42 30 36 24 48
 7|  7 63 14 21 49 35 42 28 56
 4|  4 36  8 12 28 20 24 16 32
 2|  2 18  4  6 14 10 12  8 16
 9|  9 81 18 27 63 45 54 36 72
#配列をランダムにソート
def sortbyrand(a)
  a.sort_by{rand}
end

#100マス計算出力
def xmasu(x, y, calc_flg)
  puts("  |  " + x.join("  "))
  print "--+"
  x.size.times{print "---"}
  printf("\n")
  #puts("--+---------------------------")
  y.each do |yy|
    x.each_with_index do |xx, n|
      printf("%2i|", yy)   if n == 0
      printf("%3i", xx*yy) if calc_flg
    end
    printf("\n")
  end
end
t = (1..9).to_a
x = sortbyrand(t)
y = sortbyrand(t)

xmasu(x,y,false)
printf("\n")
xmasu(x,y,true)

3.色見本作成

rgb.txtから色見本htmlを生成
rgb.txtはwebで検索してこちらからお借りしました。
なんかスマートじゃないなぁ。

inf = open("rgb.txt")
ouf = open("out.html", "w")

#ヘッダ部出力
ouf.puts "<html>"
ouf.puts "<head>"
ouf.puts "<title>rgb_sample<title>"
ouf.puts "</head>"

#body部出力
ouf.puts "<body>"
ouf.puts "<table border='1'>"
ouf.puts "<tr>"
ouf.puts "<th>color name</th>"
ouf.puts "<th>rgb</th>"
ouf.puts "</tr>"
#  以下ファイルから
inf.each{|x|
	# tabを空白に置換(tabが複数あったりrgbの区切りにも使用されていたので全部空白にします)
	ar = x.chomp.gsub(/\t+/, " ").split(" ")
	#color = "#" + format("%x", ar[0]) + format("%x", ar[1]) + format("%x", ar[2])
	color = "#"
	(0..2).each{|i| color += format("%x", ar[i])}
	ouf.puts "<tr>"
	ouf.puts "<td>" + ar[3] + "</td>"
	ouf.puts "<td bgcolor=\"" + color + "\">" + color + "</td>"
	ouf.puts "</tr>"
}
inf.close

#フッタ部出力
ouf.puts "</table>"
ouf.puts "</body>"
ouf.puts "</html>"
ouf.close