Array method Random number display - c#

So I am trying to make an array that call a method to randomize 100 numbers from -100 to 100
And display the Average Negative number. I keep staring at it and I cant find the error or a solution maybe I am tired but if anybody could help me I would be very thankful.
private void button1_Click(object sender, EventArgs e)
{
int[] P = new int[100];
Random rand = new Random();
float enAvg = AvgNeg(P);
textBox1.Text = (enAvg).ToString("");
}
static float AvgNeg(int[] array)
{
float sum = 0;
int counter = 0;
for (int i = 0; i < array.Length; i++)
{
if (array[i] < 0)
{
sum += array[i];
counter++;
}
}
float avg = sum / counter;
return avg;
}

You can do this in three lines:
Random r = new Random();
int[] num = Enumerable.Range(0, 100).Select(x => r.Next(-100, 101)).ToArray();
double avg = num.Where(n => n < 0).Average();

The problem is because all your values is zero (0), so, your counter variable is zero (0).
You can't divide by zero. So the float value of avg is NaN.
Start counter with value 1.
int counter = 1;
or verify if counter is zero before divide:
if(counter == 0)
return 0;
else
{
float avg = sum / counter;
return avg;
}

Related

C# user-input size of

I want to be able to create an array with random integers where the size of it is the user's choice and I can transfer the printed out array into a different textbox.
i tried
int listamount; //stores the number
if (int.TryParse(LStextbox.Text, out listamount) && LStextbox.Text.Length > 0)
{
//int.tryparse converts the string into a integer
//text.lentgh > 0 makes sure the box will not be left blank
}
else
{
}
int min = 0;
int max = 100; //i want to make the max an indefinite number, is that posible?
int num = listamount;
Random r = new Random();
int[] ar;
ar = new int[num];
for (i = 0; int =< num - 1; i++)
{
ar[i] = r.Next(min, max);
}
Ypu can use below approach:
You can achieve max int by using Int32.MaxValue statement.
By the way you have some mistakes with in the for loop, I have corrected them.
int listamount; //stores the number
if (int.TryParse(LStextbox.Text, out listamount) && LStextbox.Text.Length > 0)
{
//int.tryparse converts the string into a integer
//text.lentgh > 0 makes sure the box will not be left blank
}
else
{
}
int min = 0;
int max = Int32.MaxValue; //i want to make the max an indefinite number, is that posible?
int num = listamount;
Random r = new Random();
int[] ar;
ar = new int[num];
for (int i = 0; i <= num - 1; i++)
{
ar[i] = r.Next(min, max);
}
foreach(int y in ar)
Console.WriteLine(y);

How to generate a unique random number in a range without repeating a number in C# [duplicate]

This question already has answers here:
Random number generator with no duplicates
(12 answers)
Closed 2 years ago.
Hi everyone I am trying to generate 6 different numbers on the same line in c# but the problem that i face is some of the numbers are repeating on the same line.Here is my code to
var rand = new Random();
List<int> listNumbers = new List<int>();
int numbers = rand.Next(1,49);
for (int i= 0 ; i < 6 ;i++)
{
listNumbers.Add(numbers);
numbers = rand.Next(1,49);
}
somewhere my output is
17 23 23 31 33 48
Check each number that you generate against the previous numbers:
List<int> listNumbers = new List<int>();
int number;
for (int i = 0; i < 6; i++)
{
do {
number = rand.Next(1, 49);
} while (listNumbers.Contains(number));
listNumbers.Add(number);
}
Another approach is to create a list of possible numbers, and remove numbers that you pick from the list:
List<int> possible = Enumerable.Range(1, 48).ToList();
List<int> listNumbers = new List<int>();
for (int i = 0; i < 6; i++)
{
int index = rand.Next(0, possible.Count);
listNumbers.Add(possible[index]);
possible.RemoveAt(index);
}
listNumbers.AddRange(Enumerable.Range(1, 48)
.OrderBy(i => rand.Next())
.Take(6))
Create a HashSet and generate a unique random numbers
public List<int> GetRandomNumber(int from,int to,int numberOfElement)
{
var random = new Random();
HashSet<int> numbers = new HashSet<int>();
while (numbers.Count < numberOfElement)
{
numbers.Add(random.Next(from, to));
}
return numbers.ToList();
}
Make it a while loop and add the integers to a hashset. Stop the loop when you have six integers.
Instead of using a List, you should use an HashSet. The HashSet<> prohibites multiple identical values. And the Add method returns a bool that indicates if the element was added to the list, Please find the example code below.
public static IEnumerable<int> GetRandomNumbers(int count)
{
HashSet<int> randomNumbers = new HashSet<int>();
for (int i = 0; i < count; i++)
while (!randomNumbers.Add(random.Next()));
return randomNumbers;
}
I've switched your for loop with a do...while loop and set the stopping condition on the list count being smaller then 6.
This might not be the best solution but it's the closest to your original code.
List<int> listNumbers = new List<int>();
do
{
int numbers = rand.Next(1,49);
if(!listNumbers.Contains(number)) {
listNumbers.Add(numbers);
}
} while (listNumbers.Count < 6)
The best approach (CPU time-wise) for such tasks is creating an array of all possible numbers and taking 6 items from it while removing the item you just took from the array.
Example:
const int min = 1, max = 49;
List<int> listNumbers = new List<int>();
int[] numbers = new int[max - min + 1];
int i, len = max - min + 1, number;
for (i = min; i < max; i++) numbers[i - min] = i;
for (i = 0; i < 6; i++) {
number = rand.Next(0, len - 1);
listNumbers.Add(numbers[number]);
if (number != (len - 1)) numbers[number] = numbers[len - 1];
len--;
}
If you are not worried about the min, max, and range then you can use this.
var nexnumber = Guid.NewGuid().GetHashCode();
if (nexnumber < 0)
{
nexnumber *= -1;
}
What you do is to generate a random number each time in the loop. There is a chance of course that the next random number may be the same as the previous one. Just add one check that the current random number is not present in the sequence. You can use a while loop like: while (currentRandom not in listNumbers): generateNewRandomNumber
Paste the below in the class as a new method
public int randomNumber()
{
var random = new Random();
int randomNumber = random.Next(10000, 99999);
return randomNumber;
}
And use the below anywhere in the tests wherever required
var RandNum = randomNumber();
driver.FindElement(By.CssSelector("[class='test']")).SendKeys(**RandNum**);
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
int[] que = new int[6];
int x, y, z;
Random ran = new Random();
for ( x = 0; x < 6; x++)
{
que[x] = ran.Next(1,49);
for (y = x; y >= 0; y--)
{
if (x == y)
{
continue;
}
if (que[x] == que[y])
{
que[x] = ran.Next(1,49);
y = x;
}
}
}
listBox1.Items.Clear();
for (z = 0; z < 6; z++)
{
listBox1.Items.Add(que[z].ToString());
}
}
}

random function for final project in tic tac toe

I don't understand why the messagebox keeps displaying 0. For each sequence there is a direction. The purpose of the random function is to find the best point to start a new sequence. There seems to be a problem with my howfree function, I can't understand what the problem is, please help me.
public int howfree(int x, int y)
{
int freenum = 0;
int counter = 0;
foreach (GameForm.direction dirs in (GameForm.direction[]) Enum.GetValues(typeof(GameForm.direction)))
{
for (int j = 0; j < 5; j++)
{
y += Directions[(int)dirs, 0];
x += Directions[(int)dirs, 1];
if ( InBoard(y, x) && cells[y,x].cellType == Type.EMPTY)
{
counter++;
}
else
break;
}
if (counter == 5)
{
freenum++;
}
counter = 0;
}
return freenum;
}
///////////////////////////////////////////////////////////////////////////////
public Cell Randomize()
{
int row=0;
int col=0;
Random random = new Random();
int rand = 0;
//bool Found = false;
int max = 0;
int fff=0;
List<Cell> Options = new List<Cell>();
foreach (Cell CCC in cells)
{
fff=howfree(CCC.row,CCC.col);
if (fff > max)
max = fff;
}
foreach (Cell c in cells)
{
if (howfree(c.row, c.col) == max)
{
Options.Add(new Cell(c.row, c.col));
}
}
// while (!Found)
// {
rand = (int)random.NextDouble() * (Options.Count - 1);
//row = random.Next() * (Settings.Rows);
//col = random.Next() * (Settings.Cols);
MessageBox.Show(rand.ToString());
row = Options[rand].row;
col = Options[rand].col;
//}
return new Cell(row, col);
}
Why not use the overload that's designed for integers?
rand = random.Next(Options.Count);
From the MSDN documentation:
Returns a nonnegative random integer that is less than the specified maximum.
You're doing it wrong.
rand = (int)random.NextDouble() * (Options.Count - 1);
Random.NextDouble() will produce number between 0 and less than 1.0.
That means it can get up to 0.999 (You get my point) but will never be 1.
When you use explicit int cast on a fraction less bigger than 0 and less than 1 you will always get 0.
You should have done it like this:
rand = (int)(random.NextDouble() * (Options.Count - 1));
So now it will int cast after the count of options.

Method return error

Hi I am getting an error at return avg; saying return key must not be followed by object expression if anyone could help me with my problem I be very thankful.
static void Pos(int[] array)
{
Random rand = new Random();
float sum = 0;
int counter = 0;
for (int i = 0; i < array.Length; i++)
{
array[i] = rand.Next(-100, 100);
if(sum >= 0)
{
sum += array[i];
counter++;
}
float avg = sum / counter;
return avg; <<< error?
}
}
You cannot return anthing since your return type is void
Change this static void Pos(int[] array) to static float Pos(int[] array)
And also you may get "not all code path returns";
Do this:
static float Pos(int[] array)
{
Random rand = new Random();
float sum = 0;
int counter = 0;
float avg;
for (int i = 0; i < array.Length; i++)
{
array[i] = rand.Next(-100, 100);
if(sum >= 0)
{
sum += array[i];
counter++;
}
avg = sum / counter;
}
return avg;
}
You're using a void which doesn't allow you to return anything.
Your method's return type is void, and you are returning a value from it.
Do it like this:
static float Pos(int[] array)
{
Random rand = new Random();
float sum = 0;
int counter = 0;
float avg = 0;
for (int i = 0; i < array.Length; i++)
{
array[i] = rand.Next(-100, 100);
if(sum >= 0)
{
sum += array[i];
counter++;
}
avg = sum / counter;
}
return avg;
}
When you set the return type to void, it means you don't want the method to return anything.

2D-array display error

How am I supposed to display my 2D array? Or the average sum of my array? It won't let me.
The code is supposed to display a 2D array, add all those numbers, calculate the average and display the average.
// It gives me a richTextBox error. I tried to change 'float' to 'void' - gives
// me a return error.
//
// It says the object require non static field?
richTextBox1.AppendText(array[ i, j] + " ");
richTextBox1.AppendText(" "+ sum.ToString());
return avg; // <<< Error here
static float Avg(int[,] array)
{
return (float)array.OfType<int>().Average();
richTextBox1.Clear(); // <<<<==================== Here
Random rand = new Random();
float sum = 0;
int rows = array.GetLength(0);
int cols = array.GetLength(1);
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < cols; j++)
{
int value = rand.Next(-100, 100);
array[i, j] = value;
richTextBox1.AppendText(value + " "); // <<<<<<<===== Here
if (value <= 0)
sum += value;
float avg = sum / value;
}
return avg;//<<<========here
}
richTextBox1.AppendText(" Total Average is: " + avg.ToString()); // <<<==== Here
}
private void button6_Click(object sender, EventArgs e)
{
Avg(A);
}
Try this:
static float Avg(int[,] array)
{
return (float)array.OfType<int>().Average();
}
Then you use it like this:
var array = new int [2,3] {{1,2, 3}, {4,5, 6}};
Console.WriteLine(Avg(array));
Update - for jagged arrays
static float Avg(int[][] array)
{
return (float)array.SelectMany(a => a).Average();
}
void Main()
{
int[][] array =
{
new int[] {1,2,3},
new int[] {4,5}
};
Console.WriteLine(Avg(array));
}
Update 2
if you want to do it your way try this:
private void Avg(int [,] array)
{
richTextBox1.Clear();
float sum = 0;
int rows = array.GetLength(0);
int cols = array.GetLength(1);
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < cols; j++)
{
richTextBox1.AppendText(array[i,j] + " ");
sum += array[i,j];
}
}
richTextBox1.AppendText(" Total Average is: " + (float)sum/(rows*cols));
}
Because we do not really know, what do you try to make with the Avg method. I just try to sumarize:
static float Avg: you cannot use static where you use Form instance members (like richTextBox1). Please remove 'static' or move usage of richTextBox1 just in the OnClick method.
Don't use return where you want. Everything after it will not process (if not using try/finally). If you want to use the returned value, call it on the last line after everything in method processed.
return avg: avg is not known in the current context, whether is defined in the previous closure (do you know what have your neighbour behind the closed doors?)
For the final solution, refer to Ned's answer.

Categories

Resources