LoginSignup
0
0

More than 1 year has passed since last update.

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

Last updated at Posted at 2021-09-08

 現在僕は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 < 5; i++) {
			ArrayList<Integer> list = new ArrayList<Integer>();
			for (int j = num; j < num+15; j++) {
				list.add(j);
			}
			Collections.shuffle(list);
			lists.add(list);
			num += 15;
		}
		
        System.out.println("  B |  I |  N |  G |  O");
		
		for (int k = 0; k < 5; k++) {
			System.out.printf("%3d%s",lists.get(0).get(k)," |");
			System.out.printf("%3d%s",lists.get(1).get(k)," |");
			if (k == 2) {
				System.out.printf("%5s","|");
			} else {
				System.out.printf("%3d%s",lists.get(2).get(k)," |");
			}
			System.out.printf("%3d%s",lists.get(3).get(k)," |");
			System.out.printf("%3d",lists.get(4).get(k));
			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])

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


0
0
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0