【Python】【Ruby】【Java】ビンゴカード作成問題!


 現在僕はPythonを学んでいます。Pythonを学び始めて1週間ほどが経過したので、過去にRubyやJavaで作成していたプログラムをPythonでも作ってみることにしました。

B:1~15のどれか
I:16~30のどれか
N:31~45のどれか
G:46~60のどれか
O:61~75のどれか

 B |  I |  N |  G |  O
13 | 22 | 32 | 48 | 61
 3 | 23 | 43 | 53 | 63
 4 | 19 |    | 60 | 65
12 | 16 | 44 | 50 | 75
 2 | 28 | 33 | 56 | 68

 上記のような出力結果を得るプログラムになります。

  • Rubyの場合
  • Javaの場合
  • Pythonの場合

 以上の流れでコードを載せていきます。

Rubyの場合

puts "  B |  I |  N |  G |  O"

b = (1..15).to_a.sample(5)
i = (16..30).to_a.sample(5)
n = (31..45).to_a.sample(5)
g = (46..60).to_a.sample(5)
o = (61..75).to_a.sample(5)

5.times do |count|
  printf("%3d", b[count])
  print " |"

  print " #{i[count]} |"
  if count == 2
    print "    |"
  else
    print " #{n[count]} |"
  end
  print " #{g[count]} |"
  print " #{o[count]}  "
  puts "\n"
end

 後半部分はもう少し綺麗な記述ができそうです。

Javaの場合

package example;

import java.util.ArrayList;
import java.util.Collections;

public class Bingo {

    public static void main(String[] args) {

        ArrayList<ArrayList<Integer>> lists = new ArrayList<ArrayList<Integer>>();
        int num = 1;
        for (int i = 0; i <= 4; i++) {
            ArrayList<Integer> list = new ArrayList<>();
            for (int j = num; j <= num + 14; j++) {
                list.add(j);
            }
            Collections.shuffle(list);
            lists.add(list);
            num += 15;
        }

        System.out.println("  B |  I |  N |  G |  O");

        for (int i = 0; i <= 4; i++) {
            for (int j = 0; j <= 4; j++) {
                if (i == 2 && j == 2) {
                    System.out.print("   ");
                } else {
                    System.out.printf("%3d", lists.get(j).get(i));
                }
                if (j != 4) {
                    System.out.print(" |");
                }
            }
            System.out.println();

        }

    }

}

Pythonの場合

 今回作ったPythonでのビンゴカード作成問題です。Rubyとほぼ同じやり方で解きました。Pythonの方がRubyよりもシンプルな記述が可能な印象です。
 「sample」のように、重複なしで特定の範囲から複数の値を取得できるメソッドがJavaでは見当たらなかったため、Javaの場合はその辺が少し複雑になっています。

import random

b = random.sample(range(1,16),5)
i = random.sample(range(16,31),5)
n = random.sample(range(31,46),5)
g = random.sample(range(46,61),5)
o = random.sample(range(61,76),5)

print("  B |  I |  N |  G |  O ")
for j in range(5):
    print("%3d"  % b[j],end=" |")
    print("%3d"  % i[j],end=" |")
    if j == 2:
        print("   ",end=" |")
    else:
        print("%3d"  % n[j],end=" |")
    print("%3d"  % g[j],end=" |")
    print("%3d"  % o[j])


 ご意見いただけると非常に勉強になります。よろしくお願いいたします。