Dice game probabilities: Difference between revisions

m
syntax highlighting fixup automation
(implementation in Forth)
m (syntax highlighting fixup automation)
Line 11:
=={{header|11l}}==
{{trans|C}}
<langsyntaxhighlight lang="11l">F throw_die(n_sides, n_dice, s, [Int] &counts)
I n_dice == 0
counts[s]++
Line 37:
 
print(‘#.16’.format(beating_probability(4, 9, 6, 6)))
print(‘#.16’.format(beating_probability(10, 5, 7, 6)))</langsyntaxhighlight>
 
{{out}}
Line 48:
=={{header|Action!}}==
{{libheader|Action! Tool Kit}}
<langsyntaxhighlight Actionlang="action!">INCLUDE "D2:REAL.ACT" ;from the Action! Tool Kit
 
BYTE FUNC Roll(BYTE sides,dices)
Line 98:
Test(4,9,6,6)
Test(10,5,7,6)
RETURN</langsyntaxhighlight>
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Dice_game_probabilities.png Screenshot from Atari 8-bit computer]
Line 122:
 
=={{header|Ada}}==
<langsyntaxhighlight Adalang="ada">with Ada.Text_IO; use Ada.Text_IO;
with Ada.Numerics.Discrete_Random;
 
Line 179:
New_Line;
end Main;
</syntaxhighlight>
</lang>
{{output}}
<pre>
Line 189:
==={{header|BASIC256}}===
{{trans|Yabasic}}
<langsyntaxhighlight BASIC256lang="basic256">dado1 = 9: lado1 = 4
dado2 = 6: lado2 = 6
total1 = 0: total2 = 0
Line 224:
next lanza
return total
end function</langsyntaxhighlight>
{{out}}
<pre>
Line 232:
==={{header|FreeBASIC}}===
{{trans|Gambas}}
<langsyntaxhighlight lang="freebasic">Dim As Integer lado, jugador1, jugador2, total1, total2, cont, i
Dim As Integer dado1 = 9, lado1 = 4
Dim As Integer dado2 = 6, lado2 = 6
Line 270:
Next i
 
Sleep</langsyntaxhighlight>
{{out}}
<pre>
Line 290:
==={{header|Yabasic}}===
{{trans|FreeBASIC}}
<langsyntaxhighlight Yabasiclang="yabasic">dado1 = 9: lado1 = 4
dado2 = 6: lado2 = 6
total1 = 0: total2 = 0
Line 324:
next lanza
return total
end sub</langsyntaxhighlight>
{{out}}
<pre>
Line 331:
 
=={{header|C}}==
<langsyntaxhighlight lang="c">#include <stdio.h>
#include <stdint.h>
 
Line 385:
printf("%1.16f\n", beating_probability(10, 5, 7, 6));
return 0;
}</langsyntaxhighlight>
{{out}}
<pre>0.5731440767829801
Line 391:
 
=={{header|C++}}==
<langsyntaxhighlight lang="cpp">#include <cmath>
#include <cstdint>
#include <iomanip>
Line 433:
std::cout << probability(5, 10, 6, 7) << '\n';
return 0;
}</langsyntaxhighlight>
 
{{out}}
Line 443:
=={{header|D}}==
===version 1===
<langsyntaxhighlight lang="d">import std.stdio, std.range, std.algorithm;
 
void throwDie(in uint nSides, in uint nDice, in uint s, uint[] counts)
Line 477:
writefln("%1.16f", beatingProbability!(4, 9, 6, 6));
writefln("%1.16f", beatingProbability!(10, 5, 7, 6));
}</langsyntaxhighlight>
{{out}}
<pre>0.5731440767829801
Line 484:
===version 2 (Faster Alternative Version)===
{{trans|Python}}
<langsyntaxhighlight lang="d">import std.stdio, std.range, std.algorithm;
 
ulong[] combos(R)(R sides, in uint n) pure nothrow @safe
Line 522:
writefln("%1.16f", winning(iota(1u, 5u), 9, iota(1u, 7u), 6));
writefln("%1.16f", winning(iota(1u, 11u), 5, iota(1u, 8u), 6));
}</langsyntaxhighlight>
{{out}}
<pre>0.5731440767829801
Line 528:
 
=={{header|Factor}}==
<langsyntaxhighlight lang="factor">USING: dice generalizations kernel math prettyprint sequences ;
IN: rosetta-code.dice-probabilities
 
Line 536:
 
9 4 6 6 winning-prob
5 10 6 7 winning-prob [ . ] bi@</langsyntaxhighlight>
{{out}}
<pre>
Line 546:
{{works with|gforth|0.7.3}}
<br>
<langsyntaxhighlight lang="forth">#! /usr/bin/gforth
 
\ Dice game probabilities
Line 675:
 
bye
</syntaxhighlight>
</lang>
 
{{out}}
Line 690:
=={{header|Gambas}}==
'''[https://gambas-playground.proko.eu/?gist=ef255e4239a713aba35598a4617af3c9 Click this link to run this code]'''
<langsyntaxhighlight lang="gambas">' Gambas module file
 
Public Sub Main()
Line 738:
Return iTotal
 
End</langsyntaxhighlight>
Output:
<pre>
Line 758:
=={{header|Go}}==
{{trans|C}}
<langsyntaxhighlight lang="go">package main
 
import(
Line 805:
fmt.Println(beatingProbability(4, 9, 6, 6))
fmt.Println(beatingProbability(10, 5, 7, 6))
}</langsyntaxhighlight>
 
{{out}}
Line 815:
More idiomatic go:
 
<langsyntaxhighlight lang="go">package main
 
import (
Line 846:
fmt.Println(set{9, 4}.beats(set{6, 6}, 1000))
fmt.Println(set{5, 10}.beats(set{6, 7}, 1000))
}</langsyntaxhighlight>
 
{{out}}
Line 855:
=={{header|Haskell}}==
{{trans|Python}}
<langsyntaxhighlight lang="haskell">import Control.Monad (replicateM)
import Data.List (group, sort)
 
Line 876:
main = do
print $ (4, 9) `succeeds` (6, 6)
print $ (10, 5) `succeeds` (7, 6)</langsyntaxhighlight>
{{out}}
<pre>0.5731440767829815
Line 883:
=={{header|J}}==
'''Solution:'''
<langsyntaxhighlight Jlang="j">gen_dict =: (({. , #)/.~@:,@:(+/&>)@:{@:(# <@:>:@:i.)~ ; ^)&x:
 
beating_probability =: dyad define
Line 889:
'C1 P1' =. gen_dict/ y
(C0 +/@:,@:(>/&:({."1) * */&:({:"1)) C1) % (P0 * P1)
)</langsyntaxhighlight>
'''Example Usage:'''
<langsyntaxhighlight Jlang="j"> 10 5 (;x:inv)@:beating_probability 7 6
┌─────────────────────┬────────┐
│3781171969r5882450000│0.642789│
Line 898:
┌─────────────────┬────────┐
│48679795r84934656│0.573144│
└─────────────────┴────────┘</langsyntaxhighlight>
gen_dict explanation:<br>
<code>gen_dict</code> is akin to <code>gen_dict</code> in the python solution and
Line 922:
 
=={{header|Java}}==
<langsyntaxhighlight lang="java">import java.util.Random;
 
public class Dice{
Line 979:
System.out.println("p1 wins " + (100.0 * p1Wins / rolls) + "% of the time");
}
}</langsyntaxhighlight>
{{out}}
<pre>10000 rolls, p1 = 9d4, p2 = 6d6
Line 995:
=={{header|JacaScript}}==
===simulating===
<langsyntaxhighlight lang="javascript">
let Player = function(dice, faces) {
this.dice = dice;
Line 1,038:
p2 = new Player(6, 7);
contest(p1, p2, 1e6);
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,056:
{{works with|jq}}
'''Works with gojq, the Go implementation of jq'''
<langsyntaxhighlight lang="jq"># To take advantage of gojq's arbitrary-precision integer arithmetic:
def power($b): . as $in | reduce range(0;$b) as $i (1; . * $in);
 
Line 1,083:
 
beatingProbability(4; 9; 6; 6),
beatingProbability(10; 5; 7; 6)</langsyntaxhighlight>
{{out}}
<pre>
Line 1,093:
{{works with|Julia|0.6}}
 
<langsyntaxhighlight lang="julia">play(ndices::Integer, nfaces::Integer) = (nfaces, ndices) ∋ 0 ? 0 : sum(rand(1:nfaces) for i in 1:ndices)
 
simulate(d1::Integer, f1::Integer, d2::Integer, f2::Integer; nrep::Integer=1_000_000) =
Line 1,099:
 
println("\nPlayer 1: 9 dices, 4 faces\nPlayer 2: 6 dices, 6 faces\nP(Player1 wins) = ", simulate(9, 4, 6, 6))
println("\nPlayer 1: 5 dices, 10 faces\nPlayer 2: 6 dices, 7 faces\nP(Player1 wins) = ", simulate(5, 10, 6, 7))</langsyntaxhighlight>
 
{{out}}
Line 1,112:
=={{header|Kotlin}}==
{{trans|C}}
<langsyntaxhighlight lang="scala">// version 1.1.2
 
fun throwDie(nSides: Int, nDice: Int, s: Int, counts: IntArray) {
Line 1,146:
println(beatingProbability(4, 9, 6, 6))
println(beatingProbability(10, 5, 7, 6))
}</langsyntaxhighlight>
 
{{out}}
Line 1,156:
=={{header|Lua}}==
===Simulated===
<langsyntaxhighlight lang="lua">
local function simu(ndice1, nsides1, ndice2, nsides2)
local function roll(ndice, nsides)
Line 1,178:
simu(9, 4, 6, 6)
simu(5, 10, 6, 7)
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,186:
 
===Computed===
<langsyntaxhighlight lang="lua">
local function comp(ndice1, nsides1, ndice2, nsides2)
local function throws(ndice, nsides)
Line 1,220:
comp(9, 4, 6, 6)
comp(5, 10, 6, 7)
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,228:
 
=={{header|Mathematica}} / {{header|Wolfram Language}}==
<langsyntaxhighlight Mathematicalang="mathematica">ClearAll[GetProbability]
GetProbability[{dice1_List, n_Integer}, {dice2_List, m_Integer}] :=
Module[{a, b, lena, lenb},
Line 1,247:
]
GetProbability[{Range[4], 9}, {Range[6], 6}]
GetProbability[{Range[10], 5}, {Range[7], 6}]</langsyntaxhighlight>
{{out}}
<pre>48679795/84934656
Line 1,254:
=={{header|Nim}}==
{{libheader|bignum}}
<langsyntaxhighlight Nimlang="nim">import bignum
from math import sum
 
Line 1,288:
 
echo beatingProbability(9, 4, 6, 6).toFloat
echo beatingProbability(5, 10, 6, 7).toFloat</langsyntaxhighlight>
 
{{out}}
Line 1,296:
=={{header|ooRexx}}==
===Algorithm===
<langsyntaxhighlight lang="oorexx">Numeric Digits 30
Call test '9 4 6 6'
Call test '5 10 6 7'
Line 1,352:
psum+=p1.x
End
Return</langsyntaxhighlight>
{{out}}
<pre>Player 1 has 9 dice with 4 sides each
Line 1,363:
 
===Algorithm using rational arithmetic===
<langsyntaxhighlight lang="oorexx">Numeric Digits 30
Call test '9 4 6 6'
Call test '5 10 6 7'
Line 1,465:
Parse Arg a,b
if b = 0 then return abs(a)
return ggt(b,a//b)</langsyntaxhighlight>
{{out}}
<pre>Player 1 has 9 dice with 4 sides each
Line 1,479:
===Algorithm using class fraction===
Class definition adapted from Arithmetic/Raional.
<langsyntaxhighlight lang="oorexx">Numeric Digits 50
Call test '9 4 6 6'
Call test '5 10 6 7'
Line 1,637:
::attribute denominator GET
 
::requires rxmath library</langsyntaxhighlight>
{{out}}
<pre>Player 1 has 9 dice with 4 sides each
Line 1,651:
===Test===
Result from 10 million tries.
<langsyntaxhighlight lang="oorexx">oid='diet.xxx'; Call sysFileDelete oid
Call test '9 4 6 6'
Call test '5 10 6 7'
Line 1,696:
o:
Say arg(1)
Return lineout(oid,arg(1))</langsyntaxhighlight>
 
{{out}}
Line 1,714:
=={{header|Perl}}==
{{trans|Python}}
<langsyntaxhighlight lang="perl">use List::Util qw(sum0 max);
 
sub comb {
Line 1,748:
 
print '(', join(', ', winning([1 .. 4], 9, [1 .. 6], 6)), ")\n";
print '(', join(', ', winning([1 .. 10], 5, [1 .. 7], 6)), ")\n";</langsyntaxhighlight>
{{out}}
<pre>
Line 1,757:
=={{header|Phix}}==
{{trans|Go}}
<!--<langsyntaxhighlight Phixlang="phix">(phixonline)-->
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #008080;">function</span> <span style="color: #000000;">throwDie</span><span style="color: #0000FF;">(</span><span style="color: #004080;">integer</span> <span style="color: #000000;">nSides</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">nDice</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">s</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">sequence</span> <span style="color: #000000;">counts</span><span style="color: #0000FF;">)</span>
Line 1,787:
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"%0.16f\n"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">beatingProbability</span><span style="color: #0000FF;">(</span><span style="color: #000000;">4</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">9</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">6</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">6</span><span style="color: #0000FF;">))</span>
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"%0.16f\n"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">beatingProbability</span><span style="color: #0000FF;">(</span><span style="color: #000000;">10</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">5</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">7</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">6</span><span style="color: #0000FF;">))</span>
<!--</langsyntaxhighlight>-->
{{out}}
<small>
Line 1,805:
=={{header|PL/I}}==
===version 1===
<langsyntaxhighlight lang="pli">*process source attributes xref;
dicegame: Proc Options(main);
Call test(9, 4,6,6);
Line 1,879:
End;
End;
End;</langsyntaxhighlight>
{{out}}
<pre>Player 1 has 9 dice with 4 sides each
Line 1,889:
Probability for player 1 to win: 0.642703175544738770</pre>
===version 2 using rational arithmetic===
<langsyntaxhighlight lang="pli">*process source attributes xref;
dgf: Proc Options(main);
Call test(9, 4,6,6);
Line 2,033:
End;
 
End;</langsyntaxhighlight>
{{out}}
<pre>Player 1 has 9 dice with 4 sides each
Line 2,046:
 
=={{header|Python}}==
<langsyntaxhighlight lang="python">from itertools import product
 
def gen_dict(n_faces, n_dice):
Line 2,064:
 
print beating_probability(4, 9, 6, 6)
print beating_probability(10, 5, 7, 6)</langsyntaxhighlight>
{{out}}
<pre>0.573144076783
Line 2,070:
 
To handle larger number of dice (and faster in general):
<langsyntaxhighlight lang="python">from __future__ import print_function, division
 
def combos(sides, n):
Line 2,095:
 
# mountains of dice test case
# print(winning((1, 2, 3, 5, 9), 700, (1, 2, 3, 4, 5, 6), 800))</langsyntaxhighlight>
{{out}}
<pre>
Line 2,103:
 
If we further restrict die faces to be 1 to n instead of arbitrary values, the combo generation can be made much faster:
<langsyntaxhighlight lang="python">from __future__ import division, print_function
from itertools import accumulate # Python3 only
 
Line 2,126:
print(winning(5, 10, 6, 7))
 
#print(winning(6, 700, 8, 540))</langsyntaxhighlight>
{{out}}
<pre>
Line 2,135:
=={{header|R}}==
Solving these sorts of problems by simulation is trivial in R.
<langsyntaxhighlight lang="rsplus">probability <- function(facesCount1, diceCount1, facesCount2, diceCount2)
{
mean(replicate(10^6, sum(sample(facesCount1, diceCount1, replace = TRUE)) > sum(sample(facesCount2, diceCount2, replace = TRUE))))
}
cat("Player 1's probability of victory is", probability(4, 9, 6, 6),
"in the first game and", probability(10, 5, 7, 6), "in the second.")</langsyntaxhighlight>
{{out}}
<pre>Player 1's probability of victory is 0.572652 in the first game and 0.642817 in the second.</pre>
Line 2,146:
=={{header|Racket}}==
 
<langsyntaxhighlight lang="racket">#lang racket
 
(define probs# (make-hash))
Line 2,182:
 
(printf "GAME 2 (5D10 vs 6D7) [what is a D7?]~%")
(game-probs 5 10 6 7)</langsyntaxhighlight>
 
{{out}}
Line 2,200:
(formerly Perl 6)
{{works with|Rakudo|2020.08.1}}
<syntaxhighlight lang="raku" perl6line>sub likelihoods ($roll) {
my ($dice, $faces) = $roll.comb(/\d+/);
my @counts;
Line 2,219:
# We're using standard DnD notation for dice rolls here.
say .gist, "\t", .raku given beating-probability < 9d4 6d6 >;
say .gist, "\t", .raku given beating-probability < 5d10 6d7 >;</langsyntaxhighlight>
{{out}}
<pre>0.573144077 <48679795/84934656>
Line 2,229:
{{trans|ooRexx}}
(adapted for Classic Rexx)
<langsyntaxhighlight lang="rexx">/* REXX */
Numeric Digits 30
Call test '9 4 6 6'
Line 2,292:
res=res p.x
End
Return res</langsyntaxhighlight>
{{out}}
<pre>
Line 2,305:
 
===version 2===
<langsyntaxhighlight lang="rexx">/* REXX */
oid='diet.xxx'; 'erase' oid
Call test '9 4 6 6'
Line 2,351:
o:
Say arg(1)
Return lineout(oid,arg(1))</langsyntaxhighlight>
{{out}}
<pre>Player 1: 9 dice with 4 sides each
Line 2,368:
===optimized===
This REXX version is an optimized and reduced version of the first part of the 1<sup>st</sup> REXX example.
<langsyntaxhighlight lang="rexx">/*REXX pgm computes and displays the probabilities of a two─player S─sided, N─dice game.*/
numeric digits 100 /*increase/decrease to heart's desire. */
call game 9 4, 6 6 /*1st player: 9 dice, 4 sides; 2nd player: 6 dice, 6 sides*/
Line 2,398:
ns= n*s; do j=0 to ns; p.j= #.j / pow; end /*j*/
do k=n to ns; $= $ p.k; end /*k*/
return $ /* ◄──────────────── probability of 1st player to win, S─sided, N dice.*/</langsyntaxhighlight>
{{out|output|text=&nbsp; when using the default inputs:}}
<pre>
Line 2,411:
 
=={{header|Ruby}}==
<langsyntaxhighlight lang="ruby">def roll_dice(n_dice, n_faces)
return [[0,1]] if n_dice.zero?
one = [1] * n_faces
Line 2,435:
puts "Probability for player 1 to win: #{win[1]} / #{sum}",
" -> #{win[1].fdiv(sum)}", ""
end</langsyntaxhighlight>
 
{{out}}
Line 2,451:
 
=={{header|Rust}}==
<langsyntaxhighlight lang="rust">// Returns a vector containing the number of ways each possible sum of face
// values can occur.
fn get_totals(dice: usize, faces: usize) -> Vec<f64> {
Line 2,487:
println!("{}", probability(9, 4, 6, 6));
println!("{}", probability(5, 10, 6, 7));
}</langsyntaxhighlight>
 
{{out}}
Line 2,497:
=={{header|Sidef}}==
{{trans|Python}}
<langsyntaxhighlight lang="ruby">func combos(sides, n) {
n || return [1]
var ret = ([0] * (n*sides.max + 1))
Line 2,526:
 
display_results('9D4 vs 6D6', winning(range(1, 4), 9, range(1,6), 6))
display_results('5D10 vs 6D7', winning(range(1,10), 5, range(1,7), 6))</langsyntaxhighlight>
{{out}}
<pre>
Line 2,543:
 
To handle the nested loop in <tt>NdK</tt>, [[Tcl]]'s metaprogramming abilities are exercised. The goal is to produce a script that looks like:
<langsyntaxhighlight Tcllang="tcl">foreach d0 {1 2 3 4 5 6} {
foreach d1 {1 2 3 4 5 6} {
...
Line 2,551:
...
}
}</langsyntaxhighlight>
 
See the comments attached to that procedure for a more thorough understanding of how that is achieved (with the caveat that <tt>$d0..$dN</tt> are reversed).
Line 2,557:
Such metaprogramming is a very powerful technique in Tcl for building scripts where other approaches (in this case, recursion) might not be appealing, and should be in every programmer's toolbox!
 
<langsyntaxhighlight Tcllang="tcl">proc range {b} { ;# a common standard proc: [range 5] -> {0 1 2 3 4}
set a 0
set res {}
Line 2,614:
puts [format "p1 has %dd%d; p2 has %dd%d" {*}$p1 {*}$p2]
puts [format " p1 wins with Pr(%s)" [win_pr [NdK {*}$p1] [NdK {*}$p2]]]
}</langsyntaxhighlight>
 
{{Out}}
Line 2,628:
I include this to <em>emphasise</em> the importance and power of metaprogramming in a Tcler's toolbox, as well as sharing a useful proc.
 
<langsyntaxhighlight Tcllang="tcl">package require Tcl 8.6 ;# for [tailcall] - otherwise use [uplevel 1 $script]
# This proc builds up a nested foreach call, then evaluates it.
#
Line 2,671:
foreach* {*}$args $script
return $sum
}</langsyntaxhighlight>
 
=={{header|Vlang}}==
{{trans|Go}}
<langsyntaxhighlight lang="vlang">import math
 
fn min_of(x int, y int) int {
Line 2,717:
println(beating_probability(4, 9, 6, 6))
println(beating_probability(10, 5, 7, 6))
}</langsyntaxhighlight>
 
{{out}}
Line 2,727:
=={{header|Wren}}==
{{trans|Kotlin}}
<langsyntaxhighlight lang="ecmascript">var throwDie // recursive
throwDie = Fn.new { |nSides, nDice, s, counts|
if (nDice == 0) {
Line 2,756:
 
System.print(beatingProbability.call(4, 9, 6, 6))
System.print(beatingProbability.call(10, 5, 7, 6))</langsyntaxhighlight>
 
{{out}}
Line 2,766:
=={{header|zkl}}==
{{trans|Python}}
<langsyntaxhighlight lang="zkl">fcn combos(sides, n){
if(not n) return(T(1));
ret:=((0).max(sides)*n + 1).pump(List(),0);
Line 2,787:
s := p1.sum(0)*p2.sum(0);
return(win.toFloat()/s, tie.toFloat()/s, loss.toFloat()/s);
}</langsyntaxhighlight>
<langsyntaxhighlight lang="zkl">println(winning([1..4].walk(), 9, [1..6].walk(),6));
println(winning([1..10].walk(),5, [1..7].walk(),6)); # this seem hardly fair</langsyntaxhighlight>
{{out}}
<pre>
10,333

edits