![見出し画像](https://assets.st-note.com/production/uploads/images/19205259/rectangle_large_type_2_c83be383447841c7ae4d827e7752d1d7.png?width=1200)
【シミュレーション】じゃんけんにおける、あいこになる確率
今回は、じゃんけんであいこになる確率を、人数を変化させて、エクセルVBAを用いてシミュレートしました!
設定の概要
設定:
n 人でじゃんけんをする。
「 n 人全員が同じ手だったとき」または「 3 種類の手が揃ったとき」、あいことする。
問題:
あいことなる確率は?
解析解については、下の記事が詳しいです。
シミュレーション
シミュレーションの結果が以下の表と図です。
結論
理論値と有効桁数 2 ~ 5 桁で一致しました!
エクセルとVBA全文
今回の計算に使用したエクセルです。
VBAの全文を示します。
Option Explicit
Const MAX_COUNT As Long = 100000
Sub main()
Dim hands As Variant
Dim tmp2 As Variant
Dim n As Long
Dim row As Long
Dim i As Long
Dim count As Long
row = 3
Do While Cells(row, 2) <> ""
n = Cells(row, 2).Value
count = 0
For i = 1 To MAX_COUNT
hands = game(n)
If isあいこ(hands) Then
count = count + 1
End If
Next i
Cells(row, 3).Value = count / MAX_COUNT
row = row + 1
Loop
End Sub
● n 人分の”手”を配列として返す関数
Function game(ByVal numberOfPersons As Long) As String()
Dim hands() As String
ReDim hands(1 To numberOfPersons) As String
Dim i As Long
For i = 1 To numberOfPersons
Select Case WorksheetFunction.RandBetween(1, 3)
Case 1
hands(i) = "グー"
Case 2
hands(i) = "チョキ"
Case 3
hands(i) = "パー"
End Select
Next i
game = hands
End Function
● あいこかどうかをブール値で返す関数
Function isあいこ(ByRef hands As Variant) As Boolean
Dim block As Long: block = 0
Dim scissors As Long: scissors = 0
Dim paper As Long: paper = 0
Dim hand As Variant
For Each hand In hands
Select Case hand
Case "グー"
block = block + 1
Case "チョキ"
scissors = scissors + 1
Case "パー"
paper = paper + 1
End Select
Next hand
If block * scissors * paper <> 0 Then
isあいこ = True
ElseIf block * scissors + scissors * paper + paper * block = 0 Then
isあいこ = True
Else
isあいこ = False
End If
End Function
―――――記事はここまで―――――
記事はここまでです。ありがとうございました!