i need some help with my code.
i've got to make a math game with subtracting without getting negatives but my code doesn't seem to work.
int c = a - b;
if (c < 0)
{
Random ro = new Random();
a = ro.Next(10) + 1;
b = ro.Next(10) + 1;
lb_getal1.Text = a.ToString();
lb_getal2.Text = b.ToString();
}
if (txt_antwoord.Text == c.ToString())
{
MessageBox.Show("You provided the right answer!");
score += 1;
Random r = new Random();
a = r.Next(10) + 1;
b = r.Next(10) + 1;
lb_getal1.Text = a.ToString();
lb_getal2.Text = b.ToString();
}
else
{
MessageBox.Show("You were wrong!");
}
if (score == 5)
{
MessageBox.Show("You answered 5 answers correctly! Well done!");
this.Close();
RM_menu form = new RM_menu();
form.Show();
}
There are several problems in your code. The first thing to improve is: use only one instance of Random.
The Random class provides pseudo random numbers from a list. If you create an instance with the default constructor new Random(), the instance is initialized with a seed taken from the current time. Since there is not much time between your two calls, both instances probably use the same seed and you will get the same values for a and b again.
I suggest to create only one instance and store it in a member variable of your class.
Second problem: if your first try results in a negative c, you only try again once, but that does not make sure that this time it will be positive. A better approach is to compare a and b and switch if b is larger.
So the your code could look like this:
public class YourGame : Form // I guess it's a Form
{
private Random randomGenerator = new Random();
private int a;
private int b;
private int score;
public void CreateQuestion()
{
a = randomGenerator.Next(10) + 1;
b = randomGenerator .Next(10) + 1;
if (b > a)
{
// switch values
int tmp = b;
b = a;
a = tmp;
}
lb_getal1.Text = a.ToString();
lb_getal2.Text = b.ToString();
}
private void OnAnswer()
{
int c = a - b; // will never be negative as we checked a and b above
if (txt_antwoord.Text == c.ToString())
{
MessageBox.Show("You provided the right answer!");
score += 1;
CreateQuestion();
}
else
MessageBox.Show("You were wrong!");
if (score == 5)
{
MessageBox.Show("You answered 5 answers correctly! Well done!");
this.Close();
RM_menu form = new RM_menu();
form.Show();
}
}
}
I am not trying to solve this problem, but trying to give some inputs on how to make sure that the value would not be less than zero when using Random.
int a, b, c;
Random ro;
ro = new Random();
b = ro.Next(10);
a = ro.Next(b, 10);
c = a - b;
As you can see, first we set a random value to b using ro.Next(10) and then we specify a minimum value by using ro.Next(b, 10)
Doing so, it is guaranteed that the value would not be less than zero when doing a-b.
you can use Math.Abs
int c = Math.Abs (a-b);
Related
This is my random unique numbers generator I try to create for my cards software. It generates numbers and write into array OK. I have problem with the loop here. when integer i reaches 29, it stops growing and code cycles infinitely and never reaches 30, which would stop the loop.
Without the if statement it works, but it won't fill the range needed.
fixed the code, now works OK, the initial value in array was the problem. now I ged needed 0-29 values
public partial class Form1 : Form
{
int[] rndCards = new int[30];
public Form1()
{
InitializeComponent();
richTextBox1.Text = #"random numbers";
}
private void button1_Click(object sender, EventArgs e)
{
int i = 0;
rndCards = new int[30];
richTextBox1.Clear();
Random rnd = new Random();
while (i < 30)
{
int cardTest = rnd.Next(0, 30);
while (rndCards.Contains(cardTest))
{
cardTest++;
if (cardTest == 31)
{
cardTest = 1;
}
}
rndCards[i] = cardTest;
i++;
}
i = 0;
while (i < 30)
{
rndCards[i] = rndCards[i] -1;
richTextBox1.Text += rndCards[i] + ", ";
i++;
}
}
}
You problem lies in the simple fact that the array already contains the number 0 when you create it (because each item of an array is initialized to the default value for its member's type) That's why you should start your i from 1 and not zero.
int i = 1;
Alternative Simpler Approach:
You can do this as a simple random number generation:
Random rnd = new Random();
rndCards = Enumerable.Range(0, 30).OrderBy(x => rnd.Next()).ToArray();
foreach(var card in rndCards)
{
// do something
}
rnd.Next(0,30) would return a random number from 0-29.
From the documentation for Random.Next(Int32, Int32):
The Next(Int32, Int32) overload returns random integers that range from minValue to maxValue – 1. However, if maxValue equals minValue, the method returns minValue.
Use int cardText = rnd.Next(0, 31);, and this should solve your issue.
The upper bound is exclusive (C# Random.Next - never returns the upper bound?).
int cardTest = rnd.Next(0, 31);
In my c# code I have a static method. Here is the code sample:
public class RandomKey
{
public static string GetKey()
{
Random rng = new Random();
char[] chars = new char[8];
for (int i = 0; i < chars.Length; i++)
{
int v = rng.Next(10 + 26 + 26);
char c;
if (v < 10)
{
c = (char)('0' + v);
}
else if (v < 36)
{
c = (char)('a' - 10 + v);
}
else
{
c = (char)('A' - 36 + v);
}
chars[i] = c;
}
string key = new string(chars);
key += DateTime.Now.Ticks.ToString();
return key;
}
}
I am calling this function from another Class's method.
Class SomeClass
{
Void SomeMethod()
{
for(int i=0; i<100; i++)
{
System.Diagnostics.Debug.WriteLine(i + "===>" + RandomKey.GetKey());
}
}
}
But now the problem is sometimes I am getting the same output from the static method though the function was called separately. Is there any wrong with my code?
The reason is that you are initializing the Random object inside the method.
When you call the method in close time proximity (like inside a loop), the Random object is initialized with the same seed. (see Matthew Watson's comment to find out why.)
To prevent that you should declare and initialize the Random object as a static field, like this:
public class RandomKey
{
static Random rng = new Random();
public static string GetKey()
{
// do your stuff...
}
}
You keep reinitializing the Random value. Move that out to a static field. Also you can format numbers in hex using ToString with a formatter.
Also, DateTime.Now is a bad idea. See this answer for a better way to allocate unique, timestamp values.
Index out of bounds when create new thread with parameters? - Continue to my previous topic , now i got a new problem with my my Bakery Algorithm code !
Here's my code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace BakeryAlgorithm
{
class Program
{
static int threads = 10;
static string x = "";
static int count = 0;
static int[] ticket = new int[threads];
static bool[] entering = new bool[threads];
public static void doLock(int pid)
{
for (int i = 0; i < threads; i++)
{
ticket[i] = 0;
entering[i] = false;
}
entering[pid] = true;
int max = 0;
for (int i = 0; i < threads; i++)
{
if (ticket[i] > ticket[max]) { max = i; }
}
ticket[pid] = 1+max;
entering[pid] = false;
for (int i = 0; i < threads; ++i)
{
if (i != pid)
{
while (entering[i])
{
Thread.Yield();
}
while (ticket[i] != 0 && (ticket[pid] > ticket[i] ||
(ticket[pid] == ticket[i] && pid > i)))
{
Thread.Yield();
}
}
}
if (x == "C" || x == "c")
Console.WriteLine("[System] PID " + pid.ToString() + " get into critical section");
}
public static void unlock(int pid)
{
ticket[pid] = 0;
count++;
Console.WriteLine("[Thread] PID " + pid.ToString() + " complete.");
}
public static void arrayInit()
{
for (int i = 0; i < threads; i++)
{
ticket[i] = 0;
entering[i] = false;
}
}
public static void simThread(int i)
{
doLock(i);
if (x == "C" || x=="c")
Console.WriteLine("[Thread] PID " + i.ToString() + " begin to process...");
//Do some thing ????
Random rnd = new Random((int)DateTime.Now.Ticks & 0x0000FFFF);
int a = rnd.Next(1,99);
int b = rnd.Next(1,99);
int c = rnd.Next(1,4);
int d = 0;
string o="";
if (c == 1)
{
d = a + b;
o="+";
}
else if (c == 2)
{
d = a * b;
o="*";
}
else if (c == 3)
{
d = a / b;
o="/";
}
else
{
d = a - b;
o="-";
}
if (x == "C" || x == "c")
Console.WriteLine("Math Result : " + a.ToString() + o + b.ToString() + "=" + d.ToString());
unlock(i);
}
[STAThread]
static void Main(string[] args)
{
arrayInit();
string choice="C";
while (choice == "C" || x == "c")
{
Console.WriteLine("Process log (C=Yes,K=No) : ");
x = Console.ReadLine();
if (x == "")
x = "C";
Console.Clear();
Console.WriteLine("----------------------------------");
Console.WriteLine("Bakery Algorithm C#");
Console.WriteLine("Number of threads : " + threads.ToString());
Console.WriteLine("Process Log...");
Console.WriteLine("----------------------------------");
Thread[] threadArray = new Thread[threads];
for (int i = 0; i < 10; i++)
{
int copy = i;
threadArray[i] = new Thread(() => simThread(copy));
if (x == "C" || x == "c")
Console.WriteLine("[System] PID " + i.ToString() + " created");
threadArray[i].Start();
}
Console.ReadLine();
Console.WriteLine("----------------------------------");
Console.WriteLine("Complete processed " + count.ToString() + " threads !");
count = 0;
Console.WriteLine("----------------------------------");
Console.WriteLine("You want to restart (Yes=C or No=K)");
choice = Console.ReadLine();
if (choice == "")
choice = "C";
}
}
}
}
The result are here :
2*2=4
2*2=4 << duplicated
3*2=6
4*2=8
4*6=24
4*2=8 << duplicated
.... and continue with duplicate values ( random position ) !
Hope somebody here can help !
There's many things wrong with your code, but the most important part is that you didn't read the requirements that make Lamport's bakery work:
Lamport's bakery algorithm assumes a sequential consistency memory model.
You will be hard-pressed to find a modern computer that has sequential consistency.
So even if your implementation was correct with respect to those constraints, it would still be wrong on pretty much any computer that runs .NET. To make this work on a modern CPU and in .NET, you'll need to insert memory barriers to prevent instruction reordering and introduce cache refreshing to make sure each CPU core sees the same values... and by then you're probably better off using different synchronization primitives altogether.
Now, fixing these kinds of algorithms tends to be rather hard - multi-threading is hard on its own, doing lock-less multi-threading just pushes this to absurd territory. So let me just address some points:
1) You can't just use new Random() and expect statistically random numbers from that. Random has an internal state that's by default initialized to the current OS tick - that means that creating 10 Randoms in a row and then doing Next on each of those is pretty likely to produce exactly the same "random" numbers.
One way of handling that gracefully would be to have a thread-local field:
ThreadLocal<Random> rnd
= new ThreadLocal<Random>(() => new Random(Guid.NewGuid().GetHashCode()));
Each of your threads can then safely do rnd.Value.Next(...) and get reliable numbers without locking.
However, since the whole point of this excercise is to allow shared access to mutable state, a solution more in line with the task would be to use a single shared Random field instead (created only once, before starting the threads). Since the Bakery algorithm is supposed to make sure you can safely use shared stuff in the critical section, this should be safe, if implemented correctly :)
2) To actually make the Bakery part work, you need to enforce the only proper instruction ordering.
This is hard. Seriously.
I'm not actually sure how to do this safely.
The best way to start is to insert an explicit memory barrier before and after each read and write of shared state. Then you can go one by one and remove those that aren't necessary. Of course, you should only need this in the doLock and unlock methods - the rest of simThread should be single-threaded.
For a short sample:
Thread.MemoryBarrier();
entering[pid] = true;
Thread.MemoryBarrier();
int max = 0;
for (int i = 0; i < threads; i++)
{
if (ticket[i] > ticket[max]) { max = i; }
}
Thread.MemoryBarrier();
ticket[pid] = 1+max;
Thread.MemoryBarrier();
entering[pid] = false;
Thread.MemoryBarrier();
So, which one of those is it safe to remove? I have no idea. I'd have to use a lot of mental power to make sure this is safe. Heck, I'm not sure if it's safe as is - do I need to rewrite the for cycle too? Are ticket[i] and ticket[max] going to be fresh enough for the algorithm to work? I know some are definitely needed, but I'm not sure which can safely be left out.
I'm pretty sure this will be slower than using a simple lock, though. For any production code, steer clear away from code like this - "smart" code usually gets you in trouble, even if everyone in your team understands it well. It's kind of hard finding those kinds of experts, and most of those wouldn't touch lock-less code like that with a meter-long stick :)
You must create a different random number for each thread (more details)
so try this code in your main method:
for (int i = 0; i < 10; i++)
{
int temp = i;
threadArray[i] = new Thread(() => simThread(temp));
Console.WriteLine("[He Thong] PID " + i.ToString() + " duoc khoi tao");
threadArray[i].Start();
Thread.Sleep(20);
}
and the following code in you threads:
Random rand = new Random((int) DateTime.Now.Ticks & 0x0000FFFF);
now you can ensure you produce different random number for each thread.
Try:
Random rnd = new Random(Environment.TickCount / (i + 1));
This will give different seeds to each RNG.
I'm playing with stuff here and am having trouble with something.
I have an input; it can be either a number or a letter. I have to check whether it's a number or a letter. So I used an if for that. If the input is a number, my code should create an int. If it's a letter, it should create a different int. But I can't use the integer later on for some reason. Any way to solve that?
Console.WriteLine("Length (ms)");
string I = Console.ReadLine();
int I2 = Int32.Parse(I);
Console.WriteLine("Height: r for random");
string L = Console.ReadLine();
//So it asks for an input,for which I here want to check what it is
if (L != "r")
{
int He = Int32.Parse(L);
}
else
{
Random Hi = new Random();
int He = Hi.Next(1, 50);
}
//----------------------I want to use the ints in here
while(true)
{
Random R = new Random();
Random R2 = new Random();
int H = R2.Next(1,He);
int rH = H * 100;
Console.WriteLine("Height is {0}",H);
Console.Beep(rH,I2);
You need to adjust the scope of int He to take it outside of the conditional blocks.
int He;
if (L != "r")
{
He = Int32.Parse(L);
}
else
{
Random Hi = new Random();
He = Hi.Next(1, 50);
}
You could also use the conditional operator in this example to make the code look like which might be preferable as a matter of style.
int He = L != "r" ? Int32.Parse(L) : (new Random()).Next(1, 50);
One thing that is notable, about both the above, versions is that Int32.Parse could raise a number of exceptions based on the format of the string L which you probably want to handle either using try - catch statements or by using the TryParse method
I have been playing around and wrote this little piece of code. I am trying to flip a coin defined number of times and then count how many tails and heads I am getting. So here it is:
private void Start_Click(object sender, EventArgs e)
{
int headss = 0;
int tailss = 0;
int random2, g;
string i = textBox1.Text;
int input2, input;
bool NumberCheck = int.TryParse(i, out input2);
if (textBox1.Text == String.Empty) // check for empty string, when true
MessageBox.Show("Enter a valid number between 0 and 100000.");
else // check for empty string, when false
if (!NumberCheck) // number check, when false
{
textBox1.Text = String.Empty;
MessageBox.Show("Enter a valid number between 0 and 100000.");
}
else
{
input = Convert.ToInt32(textBox1.Text);
for (g = 0; g < input; g++)
{
Random random = new Random();
random2 = random.Next(2);
if (random2 == 0)
{
headss++;
}
else if (random2 == 1)
{
tailss++;
}
}
}
heads.Text = Convert.ToString(headss);
tails.Text = Convert.ToString(tailss);
}
The problem is that I keep getting problems while displaying the content. It's not even close to display they right result. Any ideas?
EDIT. Solution: move following line 3 lines up :D
Random random = new Random();
Instead of
for (g = 0; g < input; g++)
{
Random random = new Random();
random2 = random.Next(2);
}
Declare a single Random for use throughout:
private Random randomGenerator = new Random();
private void Start_Click(object sender, EventArgs e)
{
// ...
for (g = 0; g < input; g++)
{
random2 = randomGenerator.Next(2);
}
// ...
}
You should use only one Random object to generate good (as good as default Random does) random sequence.
The default constructor for random take the systmem time as seed. Therefore, if you generate lots of them in a short amount of time they will all generate the same sequence of random numbers. Pull the random object out of the loop and this effect will not occur.
With RandomGenerator. This code will count how many times coin has been flipped. It will end with 3 consecutive HEADS.
private RandomGenerator rgen = new RandomGenerator ();
public void run () {
int value = 0;
int total = 0;
while (value != 3) {
String coinFlip = rgen.nextBoolean() ? "HEADS" : "TAILS";
println (coinFlip);
if (coinFlip == "HEADS") {
value+=1;
} else {
value=0;
}
total +=1;
}
println ("It took "+total+" flips to get 3 consecutive heads");
}