C# Random Number Generator Error - c#

I am new to C# and random number generators, but need to code a simulator for a course I am taking. I am having difficulty with my for loop and my user-defined variables. I am coding in Visual Studio and need the user to select a number from a list (or input the number as text), but for the program to read it as an integer, not a string, and then use this integer as the number of times to generate a random number.
I will need to assign a probability distribution to this random number generator later, but right now I just need the thing to run! I am getting an error that it cannot covert int to string (or visa versa depending on how I code it). As well as getting an error that my local variable i is unassigned. I have looked at others codes for similar generators and I cannot see a difference in my for loop. Please help! Below is the form space C# code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace GenerateProfile
{
public partial class Form1 : Form
{
int N;
public Form1()
{
InitializeComponent();
}
private void ChooseN_SelectedIndexChanged(object sender, EventArgs e)
{
N = ChooseN;
}
private void SBtn_Click(object sender, EventArgs e)
{
Random rnd = new Random();
int num = rnd.Next(0, 100);
pi.Text = num.ToString();
for (int i; <= N; i++)
{
num = rnd.Next(0, 100);
pi.Text = pi.Text + num.ToString();
}
}
private void ClBtn_Click(object sender, EventArgs e)
{
Close();
}
}
}

I figured it out myself. I was not reading in ChooseN correctly. This fixed it.
private void Gen_Click(object sender, EventArgs e)
{
MessageBox.Show("N=", this.txtN.Text);
N = Convert.ToInt32(txtN.Text);
Random rnd = new Random();
int num = rnd.Next(-1, 1);
pitxt.Text = num.ToString();
int[] = { num };
for (int i = 1; i <= N; i++)
{
num = rnd.Next(-1, 1);
pitxt.Text = pitxt.Text + "," + num.ToString();
int[] = { int[], num };
}

Related

Array of random numbers in C# / .NET framework

I am trying to create a lottery program that would generate random numbers between 1 - 35. These numbers need to be unique as well, they can not be the same. With C#, running on the .NET framework.
I have been trying to get it to work, but I keep getting errors and I don't understand why. I have been googling and looking at videos - still I don't get what I am doing wrong.
This is my code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace help
{
public partial class Form1 : Form
{
// The array
TextBox[] TextBoxArray;
// the counter on how many times u pressed btn
private int counter = 1;
public Form1()
{
InitializeComponent();
this.StartPosition = FormStartPosition.CenterScreen;
// The text boxes name 1 - 7
//TextBoxArray = new TextBox[] { Nr1, Nr2, Nr3, Nr4, Nr5, Nr6, Nr7 };
}
private void button1_Click(object sender, EventArgs e)
{
NrOfPull.Text = counter.ToString();
counter++;
// Keep getting an error
// Error CS0443 Syntax error; value
// they are talking about the Parse(TextBoxArray[].Text);
int number = int.Parse(TextBoxArray[].Text);
// Loop through
Random rand = new Random();
for (int i = 0; i < number; i++)
{
// Generate a alotter by turn
int storedNumber;
int[] randomLottoRow = new int[7];
for (int row = 0; row < 7; row++)
{
do
{
storedNumber = rand.Next(1, 35);
}
while (randomLottoRow.Contains(storedNumber));
randomLottoRow[row] = storedNumber;
}}
/*
* This will only let me generate numbers.. but wanna use Parse...
Random generator = new Random();
for (int x = 0; x < 7; x++)
{
TextBoxArray[x].Text = generator.Next(1, 35).ToString();
Console.WriteLine(TextBoxArray[x].Text = generator.Next(1, 35).ToString());
}
*/
}
}
}
Would love to get feedback on what I am doing wrong Thank you so much :)
This is one way of generating random sequences of numbers:
using System.Linq;
public static class Ex
{
static readonly Random rng = new Random();
/// <summary>
/// Randoms the sequence.
/// </summary>
/// <param name="maxValue">The maximum number in drawing.</param>
/// <param name="count">The number of numbers drawn.</param>
public static int[] Lottery(int maxValue, int count)
{
return Enumerable.Range(1, maxValue+1)
.OrderBy((x)=>rng.NextDouble())
.Take(count).ToArray();
}
}
static class Program
{
static void Main(string[] args)
{
var seq = Ex.Lottery(35, 8);
// draw 8 numbers ranging between 1-35
Console.WriteLine(string.Join(",", seq));
// 14,24,1,3,25,5,31,30
}
}
Here you go:
private TextBox[] TextBoxArray;
private Random rand = new Random();
public Form1()
{
InitializeComponent();
TextBoxArray = new TextBox[] { Nr1, Nr2, Nr3, Nr4, Nr5, Nr6, Nr7 };
}
private void button1_Click(object sender, EventArgs e)
{
int[] picks = Enumerable.Range(1, 35).OrderBy(x => rand.NextDouble()).Take(7).ToArray();
for(int i=0; i<picks.Count(); i++)
{
TextBoxArray[i].Text = picks[i].ToString();
}
}
This uses the same approach as John Alexiou for generating the random lottery pick numbers, but then also shows you how to put those numbers into your TextBoxes.

I can't get this simple calculation right

I have a very small windows form application that calculates the storage cost for a warehouse depending on the amount of deliveries per year and presents the result in form of a chart.
It's doing what it's supposed to do, but there is just one little flaw.
There is 13 columns in the first bit and then there is 12 every other time.
I want it to always be 12.
I've been trying to reorder some lines of code, it looks like it's all ok, I'm probably just missing one line of code but can't figure it out
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace StorageCost
{
public partial class Form1 : Form
{
public static int throughPot = 52000;
public static int weekly = 1000;
public static int weeklyPalletCost = 180;
public static int deliveries = 2;
public int storageCost;
public static int x = 0;
public static int currentPot = throughPot / deliveries;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
Calculate();
}
private void Calculate()
{
currentPot = throughPot / deliveries;
storageCost = 0;
x = 0;
chart1.Series[0].Points[0].YValues[0] = currentPot + 4000;
for (int i = 1; i < 51; i++)
{
currentPot -= weekly;
if (x>= 51 / deliveries)
{
x = 0;
currentPot = throughPot / deliveries;
}
chart1.Series[0].Points[i].YValues[0] = currentPot + 4000;
storageCost += currentPot * weeklyPalletCost;
x++;
}
cost.Text = "Total storage cost: £" + storageCost / 100;
chart1.ChartAreas[0].RecalculateAxesScale();
chart1.Update();
}
private void deliveriesUpDown_ValueChanged(object sender, EventArgs e)
{
deliveries = (int)deliveriesUpDown.Value;
Calculate();
}
}
}
this is the full code.
all I need basically is to get the same result in the beginning as from 13th column onwards
any help will be much appreciated.
thanks in advance.
It was because the first column was done outside of the for loop!
after commenting this out
//currentPot = throughPot / deliveries;
//storageCost = 0;
//x = 0;
//chart1.Series[0].Points[0].YValues[0] = currentPot + 4000;
and changing the loop to for (int i = 0; i < 51; i++)
I got it to work as expected.
Thanks #Grimm
I didn't know about this F11, F10 thing. This helped me a lot!

Using the Bubble Sort Algorithm on Windows Form C# to sort random numbers?

I am suppose to be writing a C# program in visual studios windows forms application that needs to implement the following functionalities:
Create 1,000 random numbers between 1 and 5000
Use the bubble sort algorithm and sort the 1000 numbers
This is the code that I have so far:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace Prog7
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void btnGenerate_Click(object sender, EventArgs e)
{
Random num = new Random();
string line = Environment.NewLine;
int nbr = num.Next(0, 5001);
textNumbers.Text = nbr.ToString();
for(int i = 1; i <= 1000; i++)
{
nbr = num.Next(0, 5001);
textNumbers.Text = textNumbers.Text + line + nbr.ToString();
}
}
private void SortBtn_Click(object sender, EventArgs e)
{
bool inorder = false;
while (!inorder)
{
inorder = true;
for (int i = 1; i <= 1000; i++)
{
if (swap(ref i, ref i + 1))
inorder = false;
}
}
for (int i = 1; i <= 1000; i++)
{
nbr = num.Next(0, 5001);
SortBox.Text = SortBox.Text + line + nbr.ToString();
}
}
private bool swap(ref int top, ref int bottom)
{
int temp;
if (top <= bottom)
return false;
temp = top;
top = bottom;
bottom = temp;
return true;
}
}
}
My original plan was to have the form have a button for generating the numbers and a button for sorting the numbers with two textboxes to list down the numbers.The code in my btnGenerate_Click works fine for generating the 1000 different numbers. But I am having a difficulty figuring out how I can input the bubble sort algorithm into this program. I looked up many examples online on what to do but many of the examples involve a array list which im not using. The program I have right now for SortBtn_Click obviously doesnt work. If anyone can give me suggestion on how to make it work or a easier way to create this program please let me know! I appreciate all the help anyone is willing to provide.
You can follow below steps to fix your issue:
Instead of creating new random number in SortBtn_Click function, use text present in textNumber textbox.
In SortBtn_Click function, First check textNumber is null or empty. If the string is null or empty, then throw an error.
In else part, split string and convert it into integer array.
you can split string using following code.
string[] strArr = textNumber.Text.split(Environment.NewLine);
Now convert string array into integer array.
int[] intArr = Array.ConvertAll(strArr, Int32.Parse);
Now apply bubble sort on intArr variable, store result in SortBox.Text text field
Note: As #JohnG mentioned about variables used in btnGenerate_Click (num, line, nbr) goes out of scope when execution leaves btnGenerate_click function. So you can not use those variables into other function. If you want to use those variables then declare that variables in class scope(Global declaration)

How do you pass a function to itself a variable number of times to form an "n level method call"?

Suppose we have the bare bones C# code for random number generation.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace theBlindPainterTester
{
public partial class Form1 : Form
{
Random randomNumber = new Random();
public Form1()
{
InitializeComponent();
}
private void button_Click(object sender, EventArgs e)
{
randomNumber.Next(1, 6);
}
}
}
We could easily call Next() on itself to set the upper bound.
randomNumber.Next(1, randomNumber.Next(1, 6));
This could be referred to as a two level method call, a "random number between 1 and (a random number between 1 and 5)." Similarly we could write a three level method call.
randomNumber.Next(1, randomNumber.Next(1, randomNumber.Next(1, 6)));
How can we do this for N levels, where N is a variable not known until run time? I've attempted to mold out the logic using a recursive method, but it seems you would need to call Next() on every iteration for that to work, which requires immediate knowledge of parameters. Perhaps I'm just not thinking about it the correct way.
r = 6;
for (int k = 0; k < N; k++)
r = randomNumber.Next(1, r);
Wouldn't this work?
private int Generate(int Counter)
{
if (Counter>0)
return randomnumber.Next(1, Generate(Counter-1));
else
return randomnumber.Next(1, 6);
}

Using an array to substitute 10 random ints with corresponding strings

I have created a very basic magic 8 ball programme as a learning exercise.
Currently it is outputting a random number between 0 - 9 every time i click the button.
I now want to finish off by substituting each of these numbers with a small description such as "the outlook looks good" or "there is a slim chance" etc etc.
I believe I need to use an array here however am not sure what kind of array I need and where the code needs to be nested.
Can anyone point me in the right direction.
Code so far...
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace Magic8ball
{
public partial class Form1 : Form
{
private static int randomNumber;
private const int rangeNumberMin = 0;
private const int rangeNumberMax = 9;
public Form1()
{
InitializeComponent();
randomNumber = GenerateNumber(rangeNumberMin, rangeNumberMax);
}
private int GenerateNumber(int min, int max)
{
Random random = new Random();
return random.Next(min, max);
}
private void Ask_Click(object sender, EventArgs e)
{
int rn = randomNumber;
if (textBox1.Text.Trim().Length == 0)
{
MessageBox.Show("Please ask a question first", "No question was asked?");
}
else
{
MessageBox.Show("Number is" +" " + rn, "your answer...");
textBox1.Text="";
randomNumber = GenerateNumber(rangeNumberMin, rangeNumberMax);
}
}
}
}
Just a regular array belonging to the class is probably the way to go. Since your random number starts from 0 you can use it as the array index messages[randomNumber];
public partial class Form1 : Form
{
private static int randomNumber;
private const int rangeNumberMin = 0;
private const int rangeNumberMax = 9;
private readonly string[] messages =
{
"I don't think so",
"Maybe",
"I don't think so",
"Maybe",
"I don't think so",
"Maybe",
"I don't think so",
"Maybe",
"I don't think so",
"Yes",
};
public Form1()
{
InitializeComponent();
randomNumber = GenerateNumber(rangeNumberMin, rangeNumberMax);
}
private int GenerateNumber(int min, int max)
{
Random random = new Random();
return random.Next(min, max);
}
private void Ask_Click(object sender, EventArgs e)
{
int rn = randomNumber;
if (textBox1.Text.Trim().Length == 0)
{
MessageBox.Show("Please ask a question first", "No question was asked?");
}
else
{
MessageBox.Show("Number is" +" " + rn, "your answer...");
randomNumber = GenerateNumber(rangeNumberMin, rangeNumberMax);
textBox1.Text = messages[randomNumber];
}
}
}

Categories

Resources