How do I make random numbers follow certain custom rules? - c#

I am trying to make a random Trinomial generator and I want the 2 random numbers to follow the trinomial rules (num1+num2=b)(num1*num2=c)
string a = "x²";
int b = new Random().Next(-50, 50);
int c = new Random().Next(-50, 50);
Console.WriteLine(a,b,c);
while (true)
{
int num1 = int.Parse(Console.ReadLine());
int num2 = int.Parse(Console.ReadLine());
if ((num1 + num2 == b) && (num1 * num2 == c))
{
Console.WriteLine("Correct.");
break;
}
else
{
Console.WriteLine("Wrong. Try again");
}
}
I expect the numbers to be written down but they aren't. Also, I don't know how to make the random numbers follow these rules. PS - The random numbers are always the same, how do I change that?

Try this:
string a = "x²";
var randomGenerator = new Random();
int b = randomGenerator.Next(-50, 50);
int c = randomGenerator.Next(-50, 50);
Console.WriteLine("{0},{1},{2}", a, b, c);
bool isRunning = true;
while (isRunning)
{
int num1 = int.Parse(Console.ReadLine());
int num2 = int.Parse(Console.ReadLine());
if ((num1 + num2 == b) && (num1 * num2 == c))
{
Console.WriteLine("Correct.");
isRunning = false;
}
else
{
Console.WriteLine("Wrong. Try again");
}
}
Console.ReadLine();
Explanation:
First of all the Random problem. Random generates numbers not really in a random way but calculates them. So since it is an algorithm it would work the same every try. To counter that, random seeds itself with the current time which then changes the output of the algorithm. In your case you create 2 random objects, but they will be generated so fast, that both actually seed with the same time, therefore calculating the same "random" numbers. That's why in my solution, we only create one Random object.
Second: If you just want to write one string to the console, jus concat the string and pass it as one parameter.

Here's my attempt at Charles' suggestion:
var rand = new Random();
string a = "x²";
int num1 = rand.Next(-50, 50);
int num2 = rand.Next(-50, 50);
int b = num1 + num2;
int c = num1 * num2;
Console.WriteLine($"{a}, {b}, {c}");
while (true)
{
int guess1 = int.Parse(Console.ReadLine());
int guess2 = int.Parse(Console.ReadLine());
if (guess1 == num1 && guess2 == num2)
{
break;
}
Console.WriteLine("Wrong. Try again");
}
Console.WriteLine("Correct.");
I've simplified the logic at the end a bit, but it should work the same.

Related

Using correct number in calculation c#

A user enters two prime numbers which are then multiplied together, and another calculation of (a-1) * (b-1) is completed (a and b being the prime numbers entered). a function to checks the numbers entered, if the numbers are NOT prime, the user will be asked to re-enter the numbers. However, when I test this, I've noticed that if the user inputs a number which ISN'T prime, and then re-enters a prime number, the calculations are based on the number which ISN'T prime. E.g. if the user enters 2 and 4, since 4 isn't prime they are asked to enter another number, e.g 3, the calculations will be based on the numbers 2 and 4.
How can I correct this so it takes the valid prime number and not the invalid number originally entered?
namespace example
{
class Program
{
class Co_P
{
static void coprime(ref int c, int calculation)
{
if (gcd(c, calculation) == 1)
Console.WriteLine("it's Co-Prime");
else
do
{
Console.WriteLine("it isn't Co-Prime");
Console.WriteLine("Enter a Co-Prime");
c = int.Parse(Console.ReadLine());
coprime(ref c, calculation);
} while (gcd(c, calculation) != 1);
}
static int Prime_a(int a) //check a is prime
{
if (a <= 1) return 0;
for (int i = 2; i <= a / 2; i++)
{
if (a % i == 0)
{
return 0; //not prime
}
}
return 1;
}
static void result(int a) //outputs if a is prime/or not
{
if (Prime_a(a) != 0)
{
Console.WriteLine(a + " is a prime number");
}
else do
{
Console.WriteLine(a + " isn't prime number");
Console.WriteLine();
Console.WriteLine("Please make sure you enter a prime number");
a = int.Parse(Console.ReadLine());
} while (Prime_a(a) == 0);
}
static int Prime_b(int b)
{
if (b <= 1) return 0;
for (int i = 2; i <= b / 2; i++)
{
if (b % i == 0)
{
return 0;
}
}
return 1;
}
static void resultb(int b)
{
int result = Prime_b(b);
if (Prime_b(b) != 0)
{
Console.WriteLine(b + " is a prime number");
}
else do
{
Console.WriteLine(b + " is not a prime number");
Console.WriteLine("Please make sure you enter a prime number");
b = int.Parse(Console.ReadLine());
} while (Prime_b(b) == 0);
}
static void Main(string[] args)
{
int a;
Console.WriteLine("Enter a prime number for a");
a = int.Parse(Console.ReadLine());
Console.WriteLine();
result(a);
Console.WriteLine();
int b;
Console.WriteLine("Enter a prime number for b");
b = int.Parse(Console.ReadLine());
Console.WriteLine();
resultb(b);
Console.WriteLine();
int total = a * b;
Console.WriteLine("The total of the prime numbers is = " + total);
int calculation = (a - 1) * (b - 1); //calculation
Console.WriteLine();
Console.WriteLine("The result = " + calculation);
Console.WriteLine();
}
}
}
You should extend result and resultb function so it returns new prompted valid number
static int result(int a) {
var result = Prime_a(a);
if (result != 0)
...code...
return result
}
Also don't forget to reassign those values
...code...
a = result(a);
...code...
b = resultb(b);
int b;
Console.WriteLine("Enter a prime number for b");
b = int.Parse(Console.ReadLine());
Console.WriteLine();
resultb(b);
Console.WriteLine();
In line resultb(b); you are passing int to method resultb. int is a value type, or in other words, passing int to a method means passing its value to a method, where copy of that value is created. In this case a copy of b is created in method resultb. Every further change on b inside method resultb is made on copy and original stays the same.
In resultb method pass parameter by reference by adding ref keyword. Instead
static void resultb(int b)
{
// code
}
method will look like this
static void resultb(ref int b)
{
// code
}
You will call the method this way
resultb(ref b);
Here's the portion of code.
int b;
Console.WriteLine("Enter a prime number for b");
b = int.Parse(Console.ReadLine());
Console.WriteLine();
resultb(ref b);
Console.WriteLine();
Now every change on passed b inside method resultb will reflect on the original.
You should do the same for method result(int a).

How to display 2 values in a textbox?

I am trying to display two random generated numbers in a text-box using visual studio.
This is what I have so far...
int RandomNumber(int min = 0, int max = 100)
{
Random random = new Random();
return random.Next(min, max);
}
int RandomNumber2(int min = 0, int max = 100)
{
Random random = new Random();
return random.Next(min, max);
}
txtQuestion.Enabled = true;
string num1 = Convert.ToString(RandomNumber());
string num2 = Convert.ToString(RandomNumber2());
txtQuestion.Text = ("{0} + {1} = ?", num1, num2);
However, the last line comes up with the error " cannot implicitly convert type '(string, string num1, string num2)' to 'string' "
How am I supposed to output these randomly generated numbers in the textbox?
Hi below is the edited code that works to how I needed it. Thanks for all the help :)
Random random1 = new Random();
I called the above function globally so I can refer to it every time I need a new random number. And below is how I used it in my function to call for two different random numbers and display them in a text-box.
int randomNumber1 = random1.Next(0, 10);
int randomNumber2 = random1.Next(0, 10);
string num1 = Convert.ToString(randomNumber1);
string num2 = Convert.ToString(randomNumber2);
txtQuestion.Text = string.Format ("{0} + {1} = ?", num1, num2);
As #John said, you are using a ValueTuple.
You can learn more about ValueTuple here or on the msdn. But the link I gave shows almost the same code as you wrote.
What you want to do is either to use string.Format :
txtQuestion.Text = string.Format("{0} + {1} = ?", num1, num2);
Or more concise with string interpolation :
txtQuestion.Text = $"{num1} + {num2} = ?";
And show the answer like this :
Random random = new Random();
int nextRandom() => random.Next(0, 100);
int num1 = nextRandom();
int num2 = nextRandom();
txtQuestion.Text = $"{num1} + {num2} = {num1 + num2}";
// If you have a method that computes the result you can also call it inside
txtQuestion.Text = $"{num1} + {num2} = {SomeFunction(num1, num2)}";
To fix your random issue, you must create a random instance only once.
class MyClass
{
// Use the same instance of Random.
private Random _random = new Random();
public int RandomNumber()
{
return _random.Next(0, 100);
}
public void DisplayText()
{
int num1 = RandomNumber();
int num2 = RandomNumber();
txtQuestion.Text = $"{num1} + {num2} = {num1 + num2}";
}
}

How to write a program in c# that outputs 2 numbers and they must not be equal?

I need to write a program that outputs 2 numbers, but they must not be equal.
This is the code I came up with but it's wrong, sometimes it still outputs the same numbers.
Can somebody help me to solve this problem?
Thanks.
The code:
string a = null;
string b = null;
bool same = false;
Random rn = new Random();
for (int j = 0; j < 2; j++)
{
a = rn.Next(1, 3).ToString();
if (a == b)
{
same = true;
while (same == true)
{
if (a == b)
{
a = rn.Next(1, 3).ToString();
}
else
{
same = false;
}
}
Console.WriteLine("Second number is: " + a);
}
else
{
Console.WriteLine(" First number is: " + a);
b = a;
}
}
Console.ReadLine();
This should work:
string a = null;
string b = null;
Random rn = new Random();
a = rn.Next(1, 3).ToString();
do {
b = rn.Next(1, 3).ToString();
}while ( a==b)
Console.WriteLine("Second number is: " + b)
Console.WriteLine(" First number is: " + a);
Surely you must have more requirements than you've listed (otherwise just pick a random for one of them and add one to it for the second number), but something like this springs to mind:
Random rnd = new Random();
// Pick two random numbers between 1 and 2, inclusive
int first = rnd.Next(1, 3);
int second = rnd.Next(1, 3);
// Continue to pick a second number as long as it's equal to the first one
while (first == second)
{
second = rnd.Next(1, 3);
}
// Output the results
Console.WriteLine($"First number is: {first}");
Console.WriteLine($"Second number is: {second}");
Console.ReadLine();

Validating multiple fields

I used Visual Studio to create an application that features 3 fields where 3 numbers can be added together. Now, I need to validate all 3 fields so that negative numbers cannot be added. If a negative number is entered, each field has also to return a unique message like: "please enter a positive first number."
I figured out how to do that for one field, but how do I set it up for all 3 fields to not accept negative numbers (and display a unique message)?
Here is what I have:
{
int num = int.Parse(txtNum1.Text);
if (num <0)
{
MessageBox.Show("Please enter a positive first number");
}
else
{
int num1 = int.Parse(txtNum1.Text);
int num2 = int.Parse(txtNum2.Text);
int num3 = int.Parse(txtNum3.Text);
int sum = num1 + num2 + num3;
txtResult.Text = sum.ToString();
}
Hopefully this makes sense.
This might help you
int num = 0;
bool atLeastOneisNegative = false;
foreach (Control x in this.Controls)
{
if (x is TextBox)
{
num = 0;
num = int.Parse(((TextBox)x).Text);
if(num < 0)
{
atLeastOneisNegative = true;
MessageBox.Show("Please enter a positive first number");
}
}
}
if(!atLeastOneisNegative)
{
int num1 = int.Parse(txtNum1.Text);
int num2 = int.Parse(txtNum2.Text);
int num3 = int.Parse(txtNum3.Text);
int sum = num1 + num2 + num3;
txtResult.Text = sum.ToString();
}
Whereas the question is not stating whether you are using WPF or WinForms. But the logic might help you to achieve to iterate all your TextBoxes and see the value is Positive.
It can be easier with NumericUpDown control or handling the TextBox.Validating event, but anyway:
int i1, i2, i3;
if (!int.TryParse(txtNum1.Text, out i1) || i1 < 0) { MessageBox.Show("Please enter a positive first number" ); return; }
if (!int.TryParse(txtNum2.Text, out i2) || i2 < 0) { MessageBox.Show("Please enter a positive second number"); return; }
if (!int.TryParse(txtNum3.Text, out i3) || i3 < 0) { MessageBox.Show("Please enter a positive third number" ); return; }
int sum = i1 + i2 + i3;
txtResult.Text = sum.ToString();

I'm having an issue calculating the Greatest common divisor [C# with VS 2012]

I have to write 2 different numbers in two textboxes, and with a button calculate the GCD, but when I run it, the button does nothing.
int x = Convert.ToInt16(txtNum1.Text);
int y = Convert.ToInt16(txtNum2.Text);
int num1, num2;
int residuo;
if (x < y)
{
num1 = y;
num2 = x;
}
else
{
num1 = x;
num2 = y;
}
do
{
residuo = num1 % num2;
if (residuo == 0)
{
txtMCD.Text = num2.ToString();
}
else
{
num1 = num2;
num2 = residuo;
}
} while (residuo == 0);
X and y are both numbers writen in the textboxes, I use num1 and num2 to save the value of x and y in order that num1 is the higher, and num2 the lesser. Any ideas?
Your termination condition is incorrect. It should be while (residuo != 0). As it is, you either terminate the loop after one iteration, or you are in an infinte loop.

Categories

Resources