This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Expand a random range from 1–5 to 1–7
I have seen the question in here: Link
The solution the author provided didn't seem to generate the same probability.
For example, the number 4, out of 10k calls for the function, was returned 1-2 times (when the other numbers, like 2, were returned about 2k times each).
Maybe I understood wrong, or I wrote the algorithm wrong, but here:
static int rand5()
{
return new Random().Next(1, 6);
}
static int rand7()
{
while (true)
{
int num = 5 * (rand5() - 1) + rand5();
if (num < 22) return ((num % 7) + 1);
}
}
static void Main(string[] args)
{
int limit = 10000;
int[] scores = new int[7];
for (int i = 0; i < limit; i++)
{
scores[rand7() - 1]++;
}
foreach (int n in scores)
{
Console.Write(n + " ");
}
Console.WriteLine();
}
Thanks in advance.
You are not generating random numbers in Rand5.
Do it like this:
static Random rand = new Random()
static int rand5()
{
return rand.Next(1, 6);
}
Related
This question already has answers here:
Random number generator with no duplicates
(12 answers)
Closed 2 years ago.
We are making our first 2D mobile game in Unity and we need some help. We coded on Java but is also our first time coding C#.
We are making a card game and we want to give to every player a random number, but (here's the important and difficult part for us) we want each random number not to repeat.
For example if we have 5 players and we want to assign a random number from 5 to 10, if number 6 is assigned to player 1 then number 6 cant be assigned to other player.
Here's where we are:
//Player class only have string name and int trabajo
public static void assignRandom(Player jug)
{
int randomnum;
bool aleatorio;
do
{
randomnum= Random.Range(1, 5);
aleatorio = comprobarAleatorio(randomnum);
}
while (aleatorio);
jug.setTrabajo(randomnum);
}
public static bool comprobarAleatorio(int numaleatorio)
{
bool exists = false;
int longitud = jugadoresList.Count;
for (int i = 0; i < 5; i++)
{
if (jugadoresList[i].getTrabajo().Equals(numaleatorio))
{
exists = true;
}
}
}
Then with the int we make a switch and show on screen what type of player you are. But clearly we are doing something wrong because the numbers repeat itselfs, even with 0 (we dont know how).
We appreciate every help. Thank you very much! (and sorry for our english)
One solution is you can generate a list that contains valid numbers and then shuffle them.
Code to shuffle a list from here:
// A Function to generate a
// random permutation of arr[]
static void randomize(int []arr, int n)
{
// Creating a object
// for Random class
Random r = new Random();
// Start from the last element and
// swap one by one. We don't need to
// run for the first element
// that's why i > 0
for (int i = n - 1; i > 0; i--)
{
// Pick a random index
// from 0 to i
int j = r.Next(0, i+1);
// Swap arr[i] with the
// element at random index
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
// Prints the random array
for (int i = 0; i < n; i++)
Console.Write(arr[i] + " ");
}
Check the code below :
public static void assignRandom(Player jug) //Player class only have string name and int trabajo
{
int randomnum;
private Random random = new Random(); //Declared an instance of Random
ArrayList randomNumsList = new ArrayList(); //Create arraylist to add random nums
bool aleatorio;
do
{
randomnum= random.next(1, 5); //Changed Random.ranged to random.next();
randomNumsList.add(randomnum); //add the random num to list
aleatorio = comprobarAleatorio(randomnum);
}
while (aleatorio);
if (!randomNumsList.Contains(randomnum) { //Only call setTrabajo if the randomNumsList don't have currently generated randomnum
jug.setTrabajo(randomnum);
}
}
public static bool comprobarAleatorio(int numaleatorio)
{
bool exists = false;
int longitud = jugadoresList.Count;
for (int i = 0; i < 5; i++)
{
if (jugadoresList[i].getTrabajo().Equals(numaleatorio))
{
exists = true;
}
}
return exists;
}
}
Tell me if it helps or if it does not help.
This question already has answers here:
Recursion Factorial terminating due to StackOverflowException
(2 answers)
Closed 3 years ago.
I need to write a factorisation calculator with recursion, for the purpose of learning nLog and how to build custom exceptions.
I have tried a few different implementations in visual studio 2019 CE with "if" and "for" loops but I don't really know what I'm doing.
public static int Factorial(int input)
{
try
{
// create a count for step of recursion
int factorCount = 0;
int sqrt = (int)Math.Ceiling(Math.Sqrt(input));
for (int step=1; step<=sqrt;step++)
{
if(input % step == 0) {
//incress the current step of recursion by one
factorCount++;
Console.WriteLine("Calculator.Factorial:Calculating",step);
}
Console.WriteLine(input);
}
The current code is throwing up a
"Process is terminated due to StackOverflowException." and that it is getting till at lest "Console.WriteLine("Calculator.Factorial:Calculating",step); "
before crashing.
you didn't use recursion in your code at all. recursion means a function call itself within itself. in factorial you for n! you have to calculate (n-1)! till n-1 =1. try this:
using System;
using System.Collections.Generic;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static int Fact(int n)
{
if (n <= 1)
return 1;
return n * Fact(n - 1);
}
static int Factorial(int n)
{
if (n <= 1)
return 1;
int result = 1;
for (int i = 2; i <= n; i++)
{
result = result * i;
}
return result;
}
static void Main(string[] args)
{
Console.Write("Enter a Number to find factorial: ");
int n = Convert.ToInt32(Console.ReadLine());
int r = Fact(n);
Console.WriteLine(n.ToString() + "! = " + r.ToString());
Console.Write("Enter a Number to find factorial: ");
n = Convert.ToInt32(Console.ReadLine());
r = Factorial(n);
Console.WriteLine(n.ToString() + "! = " + r.ToString());
}
}
}
This question already has answers here:
What is an IndexOutOfRangeException / ArgumentOutOfRangeException and how do I fix it?
(5 answers)
Closed 4 years ago.
I'm writing a Assignment for school (we are sepose to make one for the rest of the class) and I have run in to a problem. I'm having IndexOutOfRangeException errors when running the program and I can't figure out why I'm getting it.
Random rnd = new Random();
string strNumDice = tbxNumDice.Text;
int[] numDice = new int[int.Parse(strNumDice)];
int numSides = int.Parse(tbxNumSides.Text);
int trgNumber = int.Parse(tbxTarget.Text);
int sum = 0;
//int numTries = 0;
int var2 = 0;
if (int.Parse(strNumDice) * (numSides) >= trgNumber)
{
while (var2 != trgNumber)
{
tbxResult.AppendText("\n");
sum = 0;
foreach (int numberOfDice in numDice)
{
numDice[numberOfDice] = rnd.Next(1, numSides+1);
tbxResult.AppendText(numDice[numberOfDice].ToString() + " ");
sum += numDice[numberOfDice];
//numTries++;
}
tbxResult.AppendText("\n");
tbxResult.AppendText("The new sum is" + sum.ToString());
var2 = sum;
}
}
If I decide to roll 6 d6's and wan't a target sum of 36 it will continue to do so until it gets to 36.
The mistake is here:
foreach (int numberOfDice in numDice)
{
numDice[numberOfDice] = rnd.Next(1, numSides+1);
This is how javascript does foreach loops: you get the indexes of your array. C# gives you the values of the actual elements, rather than the indexes. As you will be modifying actual array elements, you want a for loop, rather than a foreach loop, like this:
for(int i = 0; i<numDice.Length; i++)
{
numDice[i] = rnd.Next(1, numSides+1);
I would like to generate array of 10 elements with random number between (-10,10).
And scenario is array can contain positive number between (0,10) for odd positions
and contain negative number between(-10,0) for even position
For Example: 1,-2,3,-4,7,-1,3,-3,2,-9
And im totally stucked in generating -ve number at even places because im new in programming.
Any Help Is Appreciated,Thanx In Advance
Ok, i got your point. Try This Code
Random rand = new Random();
int[] arr = new int[10];
for(int i = 0; i < 10; i++)
{
if(i % 2 == 0)
arr[i] = rand.Next(1,10);
else
arr[i] = (rand.Next(1,10)) * -1;
}
for(int i = 0; i < 10; i++)
{
Console.WriteLine(arr[i]);
}
Sample Output
1
-9
9
-8
1
-4
2
-6
4
-9
Try this:
using System;
namespace ConsoleApp
{
class Program
{
static void Main (string[] args)
{
var random = new Random ();
var array = new int[10];
for (int i = 0; i < array.Length; i++)
{
bool isOdd = (i % 2) == 1; // check remainder
int randomNumber = random.Next (0, 11); // 0..10
if (isOdd) randomNumber = -randomNumber; // change sign
array[i] = randomNumber;
}
}
}
}
This is easier than all the posted answers so far. Here is a basic infinite loop from which to base your specific needs.
public IEnumerable<int> RandomAlternatingSequence()
{
var random = new Random();
int sign = -1;
while (true)
{
sign *= -1;
yield return sign * random.Next();
}
}
I realize that the post is 2 years old but this may help others who come looking.
This question already has answers here:
Random number generator only generating one random number
(15 answers)
Closed 7 years ago.
I've run into a strange issue. When I run the following code, each of my text boxes get's filled with the same randomly generated number.
public void diceAdd()
{
int[] die = new int[4];
for(int i = 0; i < total.Length; i++)
{
for (int r = 0; r < die.Length; r++)
{
//Simulates rolling a 6 sided die
Random rand = new Random();
randomNumber = rand.Next(1, 7);
die[r] = randomNumber;
}
int smallest = die[0];
for (int c = 1; c < die.Length; ++c)
{
if (die[c] < smallest)
{
smallest = die[c];
}
}
total[i] = die[0] + die[1] + die[2] + die[3] - smallest;
}
strTxt.Text = total[0].ToString();
dexTxt.Text = total[1].ToString();
conTxt.Text = total[2].ToString();
intTxt.Text = total[3].ToString();
wisTxt.Text = total[4].ToString();
chaTxt.Text = total[5].ToString();
The thing is, if I add this messagebox
MessageBox.Show(i.ToString());
after
total[i] = die[0] + die[1] + die[2] + die[3] - smallest;
the numbers each get unique outputs, as intended.
I'm thinking it has something to do with threading, but figured I'd ask here before messing something up.
you are recreating the random number generator every time in the loop, create one before the loop:
Random rand = new Random();
for(int i = 0; i < total.Length; i++)
{
...
}
see also here and here, it explains why the numbers don't change