LoginSignup
0
0

More than 3 years have passed since last update.

じゃんけんが決まる平均の回数

Last updated at Posted at 2021-02-11

何人かでやったときにじゃんけんの決まる平均の回数

import java.io.*;

public class Game {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        int input=0;
        for (;;) {
            try {
                System.out.println("何人でじゃんけんするのか入力してください");
                input=Integer.parseInt(br.readLine());
                if (input==0) {
                    System.out.println("0以外の数を入力してください");
                }else if (input!=0) break;
            }catch (NumberFormatException e) {
                System.out.println("数字のみ入力してください");
            }
        }
        double count = 1.0;
        for (int j=0; j<1000000; j++) {
            int num = sumNum(input);
            count+=num;
        }
        System.out.println("勝者が一人に決まるまでの平均回数は"+count/1000000+"回です");
    }
    public static int sumNum(int input) {
        for (int i=1;;i++) {
            int rock=0;int scissors=0; int paper=0;
            for (int j=0;j<input;j++) {
                int rand = new java.util.Random().nextInt(3);
                if (rand==0) {
                    rock++;
                } else if (rand==1) {
                    scissors++;
                } else {
                    paper++;
                }
            }
            if (input>=3) {
                if (rock!=0&&scissors!=0&&paper!=0);
                else if (rock==input||scissors==input||paper==input);
                else if (rock==0) input=scissors;
                else if (scissors==0) input=paper;
                else if (paper==0) input=rock;
            }else if (input==2) {
                if (rock==input||scissors==input||paper==input);
                else return i;
            }if (input==1) return i;
        }
    }
}

javaの初心者でこのコードは比較的わかりやすいし色々と学べるところもあるからおすすめです。
参考:http://mittsu2017.com/post-224/

0
0
0

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