EzDevInfo.com

Dice

Dice - a lightweight Dependency Injection Container for PHP Dice - PHP Dependency Injection Container dice is a minimal, lightning fast php dependency injection container with a focus on being easy to use.

Determine if a dice roll contains certain combinations?

I am writing a dice game simulator in Python. I represent a roll by using a list containing integers from 1-6. So I might have a roll like this:

[1,2,1,4,5,1]

I need to determine if a roll contains scoring combinations, such as 3 of a kind, 4 of a kind, 2 sets of 3, and straights.

Is there a simple Pythonic way of doing this? I've tried several approaches, but they all have turned out to be messy.


Source: (StackOverflow)

Making a dice in ruby language

Im coding a dice in ruby in which when i rolled it, it would either come up north south east or west.

what im having trouble with is when i roll it how do i tell it to return to me one of these directions?

any help would be great.


Source: (StackOverflow)

Advertisements

Number to the left/right on a dice?

I was wondering if there is a formula/trick to calculate what number is to the right or to the left on a standard 6-sided die if you know which number is on top and which is facing you.

Need it to solve a problem, but I don't feel like listing all 24 possibilities in an if-statement...:)


Source: (StackOverflow)

Java setter, getter (rolling a die)

I have some questions about java. There are two questions in the code (I left them as comments). Also what is the purpose of using setting and getting methods? Could you please explain it very briefly. I am a beginner. Thank you :)

public class Die
{
   private final int MAX = 6;  
   private int faceValue;  

   public Die()
   {
      faceValue = 1;

      //why do you set the faceValue as 1?
   }

   public int roll()
   {
      faceValue = (int)(Math.random() * MAX) + 1;
      //Why do we use MAX instead of just number 6?

      return faceValue;
   }

   public void setFaceValue (int value)
   {
      if (value > 0 && value <= MAX)
         faceValue = value;
   }

   public int getFaceValue()
   {
      return faceValue;
   }

   public String toString()
   {
      String result = Integer.toString(faceValue);
      return result;
   }
}

Source: (StackOverflow)

Random numbers for dice game [duplicate]

Possible Duplicate:
random string generation - two generated one after another give same results

I am writing a simple dice game for windows phone 7, that involves rolling two dice at the same time. Here is my Dice Roll Code:

 private int DiceRoll()
    {
        int result;
        Random rnd = new Random();

        result = rnd.Next(1, 7);
        return result;
    }

I then have this code that rolls the dice when a button is clicked:

   private void roll_Click(object sender, RoutedEventArgs e)
    {
        roll1 = DiceRoll();
        roll2 = DiceRoll();}

My problem is that both die get the same result.

Any idea how I can get a rolling algorithm that will usually return different results, but occasionally return the same?


Source: (StackOverflow)

Dice Sum Probability with Different types of Dice

I am currently working on a java application where I need to calculate the probabilities of rolling each sum for a variety of dice. The dice types I am supporting are d4 (4 sided dice), d6 (6 sided dice), d8 (8 sided dice), d10, d12, and d20. The user will be able to input the number of each type of dice they want to use in the calculation. For example, a user may enter 6 d6 and 4 d4.

With this given information (the number of dice of each type), I am looking to calculate the probability that each possible sum could be rolled. I will then be using this information to create a chart showing the probability distribution from the selected combination of dice provided.

This application is being written in Java.

Where I am currently at is I have a function that will calculate the probability of a specific sum for a using only one size of dice

/*
    Recursively calculates the probability of rolling a particular number
    when rolling multiple dice of one type
    @param dice Number of dice
    @param seekedValue Value whose probability is being calculated
    @param sides Number of sides on the type of die
     */
    private double diceProb(int dice, int seekedValue, int sides){
        if (dice == 0){
            if (seekedValue == 0){
                return 1.0;
            } else {
                return 0.0;
            }
        } else {
            double sum = 0;
            for (int i = seekedValue - sides; i < seekedValue; i++){
                sum += diceProb(dice -1, i, sides) / sides;
            }
            return sum;
        }

    }

I then use this code to find all the possible probabilites

/*
Variable Explanations:
diceEntries: This array list contains the number of each dice supplied by the user.
It is ordered by number of sides, with d4 at the beginning and d20 at the end
diceValues: This array contains the sides of the dice types
probArray: this array list will contain the probabilities of each sum possible
min: the minimum sum  possible
max: the maximum sum possible
*/
ArrayList<Integer> diceEntries
ArrayList<Float> probArray = new ArrayList<>();
int[] diceValues = {4,6,8,10,12,20};
float prob = 0;
for (int i = min; i <= max; i++){
    for (int j = 0; j <= 5; j++) {
        prob = (float) diceProb(diceEntries.get(j), i, diceValues[j]);
        if (prob != 0) {
            probArray.add(prob);
        }
    }
}

My current code is only able to handle dice of one size, ie only d6s or d4s and not a mix of them.

If the community can provide some guidance, it would be greatly appreciated. I am open to over approaches as well. For example, I have read that generating functions might be a better way of doing this, but my combinatorics statistics are a bit weak and if someone did have a way of coding that up, it would nice to see it.

Thanks a lot folks


Source: (StackOverflow)

recursion resulting in extra unwanted data

I'm writing a module to handle dice rolling. Given x die of y sides, I'm trying to come up with a list of all potential roll combinations.

This code assumes 3 die, each with 3 sides labeled 1, 2, and 3. (I realize I'm using "magic numbers" but this is just an attempt to simplify and get the base code working.)

        int[] set = { 1, 1, 1 };
        list = diceroll.recurse(0,0, list, set);

...

    public ArrayList<Integer> recurse(int index, int i, ArrayList<Integer> list, int[] set){
        if(index < 3){
//          System.out.print("\n(looping on "+index+")\n");
            for(int k=1;k<=3;k++){
//              System.out.print("setting i"+index+" to "+k+" ");
                set[index] = k;
                dump(set);
                recurse(index+1, i, list, set);
            }
        }
        return list;
    }

(dump() is a simple method to just display the contents of list[]. The variable i is not used at the moment.)

What I'm attempting to do is increment a list[index] by one, stepping through the entire length of the list and incrementing as I go.

This is my "best attempt" code. Here is the output:

Bold output is what I'm looking for. I can't figure out how to get rid of the rest. (This is assuming three dice, each with 3 sides. Using recursion so I can scale it up to any x dice with y sides.)

[1][1][1] [1][1][1]

[1][1][1] [1][1][2] [1][1][3] [1][2][3]

[1][2][1] [1][2][2] [1][2][3] [1][3][3]

[1][3][1] [1][3][2] [1][3][3] [2][3][3] [2][1][3]

[2][1][1] [2][1][2] [2][1][3] [2][2][3]

[2][2][1] [2][2][2] [2][2][3] [2][3][3]

[2][3][1] [2][3][2] [2][3][3] [3][3][3] [3][1][3]

[3][1][1] [3][1][2] [3][1][3] [3][2][3]

[3][2][1] [3][2][2] [3][2][3] [3][3][3]

[3][3][1] [3][3][2] [3][3][3]

I apologize for the formatting, best I could come up with.

Any help would be greatly appreciated. (This method was actually stemmed to use the data for something quite trivial, but has turned into a personal challenge. :)

edit: If there is another approach to solving this problem I'd be all ears, but I'd also like to solve my current problem and successfully use recursion for something useful.

edit2: Running code including the "easy fix." Beware unused variables and weird hacks, I haven't cleaned it up yet.

package code.testing;

import java.util.ArrayList;

public class CodeTesting {

    public static void main(String[] args) {
        ArrayList<Integer> list = new ArrayList<Integer>();
        int[] set = { 1, 1, 1 };
        list = recurse(0,0, list, set);
    }

    public static ArrayList<Integer> recurse(int index, int i, ArrayList<Integer> list, int[] set){
        if(index < 3){
//          System.out.print("\n(looping on "+index+")\n");
            for(int k=1;k<=3;k++){
//              System.out.print("setting i"+index+" to "+k+" ");
                set[index] = k;
                if (index==2){
                    dump(set);
                }
                recurse(index+1, i, list, set);
            }
        }
        return list;
    }

    static void dump(int[] arr) {
        for (int s : arr) {
            System.out.format("[%s]", s);
        }
        System.out.println();
    }
}

Source: (StackOverflow)

Number of Dice rolling till reaches a Stop Value

I am trying to count the number of dice rolls till it reaches to a definite stop value. For example, I want the stop value as 100. I am writing the following code:

sumofsides <- function(stopvalue) {
  totalsum <- 0
  while (totalsum < stopvalue) {
    face <- sample(6, 1, replace= TRUE)
    totalsum <- totalsum + face
  }
  return(total value)
}

sumofsides(100)
[1] 103

When I am writing the following code to get the number of rolling till it reaches to the stop value. But it's always giving value of 1 which is wrong.

numofrolls <- function(stopvalue) {
  totalsum <- 0
  while (totalsum < stopvalue) {
    face <- sample(6, 1, replace= TRUE)
    totalsum <- totalsum + face
  }
  return(length(face))
}

numofrolls(100)
[1] 1

Any help is appreciated.


Source: (StackOverflow)

Basic C# Dice Game

I am new to c# and coding in general. To try and improve my skills I am trying to create a basic game where two players roll a dice and keep record of their score. The player wins by reaching 20. Each player takes turns rolling a dice adding their first roll to their second and so on until one of them reaches 20. A player can roll the dice again if they roll a six.

The current code I have is:


        do
        {

            Console.Write("Enter the name of Player 1: ");
            Player[0] = Console.ReadLine();
            Console.Write("Enter the name of Player 2: ");
            Player[1] = Console.ReadLine();

            Random DiceRandom = new Random();
            DiceThrow[0] = DiceRandom.Next(1, 7);

            int i = 0;
            while (i <= 1)
            {
                DiceThrow[0 + i] = DiceRandom.Next(1, 7);
                Console.ReadLine();
                Console.Write(Player[0 + i] + " rolled a " + DiceThrow[0 + i]);
                if (DiceThrow[0 + i] != 6) i++;
            }

            Console.ReadLine();
            PlayerTotal[0] = DiceThrow[0];
            PlayerTotal[1] = DiceThrow[1];


            Console.ReadLine();
            Console.Write(Player[0] + " currently has " + PlayerTotal[0]);
            Console.ReadLine();
            Console.Write(Player[1] + " currently has " + PlayerTotal[1]);
            Console.ReadLine();

        }
        while (PlayerTotal[0] == 20);
        while (PlayerTotal[1] == 20);

What I am specifically struggling with is adding the players first roll to there second roll. And if a player rolls a six that it adds the 6 to what they get in the re-roll.

Any help at all will be greatly appreciated.


Source: (StackOverflow)

Loop with Dice rolling program, previous roll and double check

A fairly trivial problem to most I am sure but I can't quite work out how I'm meant to get the previous dice integer to remain the same as the previous roll of die in the program. I think the code is fairly self explanatory and this is such a trivial program I'm kicking myself for not being able to get my head around it.

import java.util.Random;

public class Dice {

    public static void main(String[] args) {
        Random rand = new Random();
        int min = 1;
        int max = 6;
        int loop = 0;
        int diceRollOne = 0;
        int diceRollTwo = 0;
        int diceTotal = 0;
        int prevDiceTotal = 0;

        while (loop < 15000) {
            loop++;
            diceRollOne = rand.nextInt(max - min + 1) + min;
            diceRollTwo = rand.nextInt(max - min + 1) + min;
            diceTotal = diceRollOne + diceRollTwo;

            System.out.println("Dice Roll 1: " + diceRollOne);
            System.out.println("Dice Roll 2: " + diceRollTwo);
            System.out.println("Dice Total: " + diceTotal);
            System.out.println("previous total: " + prevDiceTotal);

            prevDiceTotal = diceTotal;

            if (diceRollOne == diceRollTwo || diceTotal == prevDiceTotal) {
                System.out.println("After " + loop + " loops the");
                System.out.println("Numbers Match, YOU GET NOTHING, YOU LOSE, GOOD DAY SIR!");
                System.exit(0);
            }
        }
    }
}

The basic idea being 15,000 simulations. Roll two dice. If you roll a double quit. If you roll the same sum in the current roll as the sum of the previous roll then quit. I've tried debugging by printing out the previous dice total but it defaults to zero every time.


Source: (StackOverflow)

looping in unit test bad?

I have a unit test that relies on a random dice roll. I roll a 20 sided die and if the value is 20 it counts as a critical hit.

What I'm doing right now is rolling the 20 sided die up to 300 times. If any one of those rolls is a 20 then I know I had a critical hit.

Here's what the code looks like:

public class DiceRoll
{
    public int Value { get; set; }
    public bool IsCritical { get; set; }

    // code here that sets IsCritical to true if "Value" gets set to 20
}

[Test]
public void DiceCanRollCriticalStrikes()
{
    bool IsSuccessful = false;
    DiceRoll diceRoll = new DiceRoll();

    for(int i=0; i<300; i++)
    {
        diceRoll.Value = Dice.Roll(1, 20); // roll 20 sided die once
        if(diceRoll.Value == 20 && diceRoll.IsCritical)
        {
            IsSuccessful = true;
            break;
        }
    }

    if(IsSuccessful)
        // test passed
    else
        // test failed 
}

Although the test does exactly what I want it to I can't help but feel like I'm doing something wrong.

On a related note, the DiceRoll class has other information in it as well but my question is specifically about looping in a unit test, so I left it out to make it more clear


Source: (StackOverflow)

Combinatorics Counting Puzzle: Roll 20, 8-sided dice, what is the probability of getting at least 5 dice of the same value

Assume a game in which one rolls 20, 8-sided die, for a total number of 8^20 possible outcomes. To calculate the probability of a particular event occurring, we divide the number of ways that event can occur by 8^20.

One can calculate the number of ways to get exactly 5 dice of the value 3. (20 choose 5) gives us the number of orders of 3. 7^15 gives us the number of ways we can not get the value 3 for 15 rolls.

number of ways to get exactly 5, 3's = (20 choose 5)*7^15.

The answer can also be viewed as how many ways can I rearrange the string 3,3,3,3,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 (20 choose 5) times the total number of values we the zero's (assuming 7 legal values) 7^15 (is this correct).

  • Question 1: How can I calculate the number of ways to get exactly 5 dice of the same value(That is, for all die values). Note: if I just naively use my first answer above and multiply bt 8, I get an enormous amount of double counting?

    I understand that I could solve for each of the cases (5 1's), (5, 2's), (5, 3's), ... (5's, 8) sum them (more simply 8*(5 1's) ). Then subtract the sum of number of overlaps (5 1's) and (5 2's), (5 1's) and (5 3's)... (5 1's) and (5, 2's) and ... and (5, 8's) but this seems exceedingly messy. I would a generalization of this in a way that scales up to large numbers of samples and large numbers of classes.

  • How can I calculate the number of ways to get at least 5 dice of the same value?

    So 111110000000000000000 or 11110100000000000002 or 11111100000001110000 or 11011211222222223333, but not 00001111222233334444 or 000511512252363347744.

I'm looking for answers which either explain the math or point to a library which supports this (esp python modules). Extra points for detail and examples.


Source: (StackOverflow)

C# code only gives expected results on step through?

Ok so I have a dice throw app...

When I step through the code it functions normally and 'results' contains the correct number of throw results and they appear to be random, when I leave the code to run and do exactly the same thing it produces a set of identical numbers.

I'm sure this is a logical error I cannot see but fiddling with it for hours hasnt improved the situation, so any help is much appriciated. :)

    class Dice
{

    public int[] Roll(int _throws, int _sides, int _count)
    {
        Random rnd = new Random();
        int[] results = new int[_throws];
        // for each set of dice to throw pass data to calculate method
        for (int i = 0; i < _throws; i++)
        {
            int thisThrow = Calculate(_sides, _count);
            //add each throw to a new index of array... repeat for every throw
            results[i] = thisThrow; 
        }

        return results;
    }


    private int Calculate(int _sides, int _count)
    {
        Random rnd = new Random();
        int[] result = new int[_count];
        int total = 0;
        //for each dice to throw put data into result
        for (int i = 0; i < _count; i++)
        {
            result[i] = rnd.Next(1, _sides);
        }
        //count the values in result
        for (int x = 0; x < _count; x++)
        {
            total = total + result[x];
        }
        //return total of all dice to Roll method
        return total;
    }
}

Source: (StackOverflow)

Calculating odds distribution with 6-sided dice

I'm trying to calculate the odds distribution of a changing number of 6-sided die rolls. For example, 3d6 ranges from 3 to 18 as follows:

3:1, 4:3, 5:6, 6:10, 7:15, 8:21, 9:25, 10:27, 11:27, 12:25, 13:21, 14:15, 15:10, 16:6, 17:3, 18:1

I wrote this php program to calculate it:

function distributionCalc($numberDice,$sides=6) {
for ( $i=0; $i<pow($sides,$numberDice); $i++)
    {
    $sum=0;
    for  ($j=0; $j<$numberDice; $j++)
        { $sum+=(1+(floor($i/pow($sides,$j))) % $sides); }
    $distribution[$sum]++;
    }
return $distribution;
}

The inner $j for-loop uses the magic of the floor and modulus functions to create a base-6 counting sequence with the number of digits being the number of dice, so 3d6 would count as:

111,112,113,114,115,116,121,122,123,124,125,126,131,etc.

The function takes the sum of each, so it would read as: 3,4,5,6,7,8,4,5,6,7,8,9,5,etc. It plows through all 6^3 possible results and adds 1 to the corresponding slot in the $distribution array between 3 and 18. Pretty straightforward. However, it only works until about 8d6, afterward i get server time-outs because it's now doing billions of calculations.

But I don't think it's necessary because die probability follows a sweet bell-curve distribution. I'm wondering if there's a way to skip the number crunching and go straight to the curve itself. Is there a way to do this with, for example, 80d6 (range: 80-480)? Can the distribution be projected without doing 6^80 calculations?

I'm not a professional coder and probability is still new to me, so thanks for all the help!

Stephen


Source: (StackOverflow)

From 5 dice rolls, generate a random number in the range [1 - 100]

I was going through some coding exercises, and had some trouble with this question:

From 5 dice (6-sided) rolls, generate a random number in the range [1 - 100].

I implemented the following method, but the returned number is not random (called the function 1,000,000 times and several numbers never show up in 1 - 100).

public static int generator() {

     Random rand = new Random();
     int dices = 0;

     for(int i = 0; i < 5; i++) {
         dices += rand.nextInt(6) + 1;
     }

     int originalStart = 5;
     int originalEnd = 30;
     int newStart = 1;
     int newEnd = 100;

     double scale = (double) (newEnd - newStart) / (originalEnd - originalStart);
     return (int) (newStart + ((dices - originalStart) * scale));
}

Source: (StackOverflow)