PowerShellの- 168 131 125 115
ゴルフしたコード:
nal g Random;1..1e4|%{$C=g 3;$P=g 3;$T+=$C-eq(0..2|?{$_-ne$P-and$_-ne(0..2|?{$_-ne$P-and$_-ne$C}|g)})};"$($T/100)%"
オリジナルからの変更:
元のスクリプトから53文字をトリミングして変更しました。
- PowerShellで許容されるスペースと括弧が削除されました。
- の代わりに
ForEach-Object、%エイリアスを介してループを使用しましたwhile。
0..2明示的に定義された配列の代わりに番号範囲(例:)を使用しました。
write最後のコマンドから削除されました-結局私はそれを必要としません。
- 短いパイプライン構文を使用するために、ホストの選択式を反転させました。
- 10000を1e4に置き換えました。
- 取ったジョーイの提案を省略
Get-からGet-Random。(注:この変更により、実行時間が大幅に膨張します。私のシステムでは、実行ごとに約20秒から30分近くにジャンプしました!)
- 代わりに、Rynantのトリックを使用しました。
$T+=...if(...){$T++}
いくつかのメモ:
このスクリプトは、モンティホールのシナリオをできるだけ完全にシミュレーションしながら、できるだけ簡潔にすることを目的としています。車がどこにあるのか、どのドアがプレイヤーが最初に選択するのかは想定していません。ホストがどの特定のシナリオで選択する特定のドアについても、想定は行われません。残りの仮定は、Monty Hall問題で実際に述べられているものだけです。
- ホストは、プレイヤーが最初に選択しなかったドアを選択します。ドアには車が含まれていません。
- プレイヤーが最初に車でドアを選んだ場合、それはホストに2つの可能な選択肢があることを意味します。
- プレーヤーの最終選択は、彼の最初の選択でもホストの選択でもありません。
コメントなしのゴルフ場:
# Setup a single-character alias for Random, to save characters later.
# Note: Script will run a lot (about 500 times) faster if you use Get-Random here.
# Seriously, as it currently is, this script will take about a half-hour or more to run.
# With Get-Random, it'll take less than a minute.
nal g Random;
# Run a Monty Hall simulation for each number from 1 to 10,000 (1e4).
1..1e4|%{
# Set car location ($C) and player's first pick ($P) to random picks from a pool of 3.
# Used in this way, Random chooses from 0..2.
$C=g 3;$P=g 3;
# Increment win total ($T) if the car is behind the door the player finally chooses.
# (Player's final choice represented by nested script.)
$T+=$C-eq(
# Filter the doors (0..2) to determine player's final choice.
0..2|?{
# Player's final choice will be neither their original choice, nor the host's pick.
# (Host's pick represented by nested script.)
$_-ne$P-and$_-ne(
# Filter the doors to determine host's pick.
0..2|?{
# Host picks from door(s) which do not contain the car and were not originally picked by the player.
$_-ne$P-and$_-ne$C
# Send filtered doors to Random for host's pick.
}|g
)
}
)
};
# After all simulations are complete, output overall win percentage.
"$($T/100)%"
# Variable & alias cleanup. Not included in golfed script.
rv C,P,T;ri alias:g
このスクリプトを何度か実行しましたが、結果は常に3分の2に近い確率で結果を出力します。いくつかのサンプル:
(上記のように)
(Get-Random単にの代わりに、エイリアス定義として使用Random)
- 66.92%
- 67.71%
- 66.6%
- 66.88%
- 66.68%
- 66.16%
- 66.96%
- 66.7%
- 65.96%
- 66.87%