Array of random numbers in C# / .NET framework - c#

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.

Related

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!

How do I replace an array element within an if statement? C#

This is the second version of this code I've gone through as the first version ran too quickly for the Random function to work properly. I'm trying to make sure none of the randomly generated numbers are the same and if they are replace them in the array but it's not letting me call the array. Can someone tell me what I'm doing wrong?
using System;
using System.Timers;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp4
{
class Program
{
public static Timer aTimer;
static void Main(string[] args)
{
//Create three different random integers and store them
Random rnd = new Random();
int RandA = rnd.Next(0, 26);
int RandB = rnd.Next(0, 26);
int RandC = rnd.Next(0, 26);
//Turn those three variables into an array
int[] RandArray = { RandA, RandB, RandC };
//Make sure there are no duplicates
if (RandArray[0] == RandArray[1])
{
int RandArray[0] = rnd.Next(0, 26);
}
if (RandArray[1] == RandArray[2])
{
int RandArray[1] = rnd.Next(0, 26);
}
if (RandArray[2] == RandArray[0])
{
int RandArray[2] = rnd.Next(0, 26);
}
//Print out all three values seperately
for (int i = 0; i < 3; i++)
{
Console.WriteLine("Value of: {1}", i, RandArray[i]);
continue;
}
Console.ReadKey();
}
}
}
Well, I would potentially alter your approach.
public static class Randomizer
{
private static const generator = new Random();
public static int Generate(int minimum, int maximum) => generator.Next(minimum, maximum);
}
Then I would do the following:
public static class BuildRandom
{
public IEnumerable<int> FillCollection(int capacity)
{
for(int index = 0; index < capacity; index++)
yield return Randomizer.Generate(0, 26);
}
public static int GetRandomNumber() => Randomizer.Generate(0, 26);
}
Then I would simply do the following.
// Build Collection
var randomized = BuildRandom.FillCollection(5);
// Remove Duplicates
var filter = randomized.Distinct();
while(filter.Count != randomized.Count)
{
var value = BuildRandom.GetRandomNumber();
if(!filter.Any(number => number == value))
filter.Concat(new { value });
}
int RandArray[0] = is a syntax error. Try RandArray[0] =

C# Random Number Generator Error

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 };
}

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];
}
}
}

Cannot convert from int to system.collections.generic.icomparer<int>

New to C# Just wondering what the error is, can't understand the error. No need to correct, just want to know the mistake.
ERROR:
The best overloaded method match for 'Systems.Collections.Generic.List.BinarySearch(int,System.Collections.Generic.Icomparer)' has some invalid arguments
Argument1: Cannot convert from system.collections.generic.list to int
Argument2: Cannot convert from int to system.collections.generic.icomparer
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;enter code here
using System.Windows.Forms;
namespace LotoNumbers
{
public partial class FrmLotto : Form
{
// declare class level variables
List<int> player = new List<int>(7);
List<int> computer = new List<int>(6);
public FrmLotto()
{
InitializeComponent();
}
// event method to generate player's numbers
private void btnPlayer_Click(object sender, EventArgs e)
{
// declare and initalize local variables
string display = "";
// reset the winning number label before generating the player's numbers
lblComputerNumber.Text = "00 00 00 00 00 00";
// generate unique random numbers
GenerateRandomNumbers(player);
player.Sort();
// build display string
display = BuildDisplayString(player);
// display winning number in label
lblPlayerNumber.Text = display;
}
// method to generate computer's random numbers (the 'winning numbers')
// and determine how many winning numbers
private void btnComputer_Click(object sender, EventArgs e)
{
// declare and initalize local variables
int winCount = 0;
string display = "";
// generate unique random numbers
GenerateRandomNumbers(computer);
// sort the array in ascending order
computer.Sort();
// build display string
display = BuildDisplayString(computer);
// display winning number in label
lblComputerNumber.Text = display;
// determine if this number matches any of the players numbers
winCount = CompareTwoList(player, computer);
// display the total winning numbers
lblMatching.Text = winCount.ToString("D2");
}
private void GenerateRandomNumbers(List<int> numberList)
{
Random lucky = new Random();
// generate unique random numbers
for (int index = 0; index < numberList.Capacity; index++)
{
int temp = lucky.Next(1, 50);
if (numberList.IndexOf(temp) < 0)
{
numberList.Add(temp);
}
else
{
index--;
}
}
}
private string BuildDisplayString(List<int> numberList)
{
// declare method variable
string display = " ";
// loop through the array and build a display string
foreach (int number in numberList)
display += number.ToString("D2") + " ";
// return display string
return display;
}
private int CompareTwoList(List<int> list1, List<int> list2)
{
// declare method variable
int numberMatching = 0;
// loop through each element in the first array looking for a match in the second array
foreach (int value in list1)
{
if (player.BinarySearch(list2, value) >= 0)
numberMatching++; // a matching value is found
}
return numberMatching;
}
}
}
It looks like you want:
if (list2.BinarySearch(value) >= 0)
numberMatching++; // a matching value is found
You are calling List<int>.BinarySearch(int, IComparer<int>) at the moment. Since value is an int you are getting a type error.
Note you can also do:
int numberMatching = list2.Intersect(list1).Count();
There is no overload for List<int>.BinarySearch() which accepts a List<int> and int as the parameters. See MSDN
You need to use player.BinarySearch(value)

Categories

Resources