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);
Related
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());
}
}
}
If i have 478523698 as an integer number, how to find 2nd lowest number only with if conditions wihout converting it to string, this question was asked in interview. I got the output by converting Integer to array like this
`
int integer=478523698;
//converting integer to array
string s,numbers = integer.ToString();
char[] num = numbers.ToCharArray();
int L=num.Length;
int[] intArray = new int[L];
for (int i = 0; i <L; i++)
{
s = num[i].ToString();
intArray[i] = Convert.ToInt32(s);
}
//code for getting 2nd lowest number
int min1=intArray[0];
int min2=0;
if (min2 < min1)
{
min1 = intArray[1];
min2 = intArray[0];
}
for(var i=0;i<=intArray.Length-1;i++){
if (intArray[i] < min1)
{
min2 = min1;
min1 = intArray[i];
}
else if (intArray[i] < min2)
{
min2 = intArray[i];
}
}
Console.Write("Second Lowest Number is {0} ",min2); `
I think you can do this without converting to string, and with a simple loop and conditions like the following:
int inputInteger = 478523698;
int numberSample = inputInteger;
int lowest = int.MaxValue, secondlowest = int.MaxValue;
while (numberSample != 0)
{
int digit = numberSample % 10;
numberSample = numberSample / 10;
if (digit < secondlowest && digit!=lowest)
{
secondlowest = digit;
}
if (secondlowest < lowest)
{
int temp = secondlowest;
secondlowest = lowest;
lowest = temp;
}
}
if (secondlowest == int.MaxValue)
{
Console.WriteLine("There is no second lowest number");
}
else
{
Console.WriteLine("Lowest digit in {0} is {1} and second lowest digit is {2}", inputInteger,lowest,secondlowest);
}
Working example, you can see that above code will print the output as Lowest digit in 478523698 is 2 and the second-lowest digit is 3, if you initialize inputInteger with 222 means the output will be There is no second-lowest number
I'm sure this can be simplified but it works...
class Program
{
static void Main(string[] args)
{
var number = 478523698;
var numberList = new List<int>();
for (var i = 1; i <= number; i *= 10)
{
var currentNumber = number / i % 10;
numberList.Add(currentNumber);
}
Console.WriteLine(numberList.OrderBy(x => x).Skip(1).FirstOrDefault());
Console.Read();
}
}
I'm really struggling to find a way to put 10 int numbers ( from 1 to 10) twice in a 20-position array on a random position in C#.Everything I have already tried takes too much time and makes my programme run really slow.
Ok here's the code I have already tried but doesn't really work well.
for (int j = 1; j <= 10; j++)
{
k = 0;
while (k < 2)
{
rnd = new Random();
numb = rnd.Next(1, 20);
//w = numbers[numb].ToString(); not actually working as well
if (numbers[numb] == '\0')
{
numbers[numb] = j;
k++;
}
}
}
So what I'm really trying to do here,is to put all the int numbers from 1 to 10
twice in this 20-position array on random position.Sorry for not posting my code before,but I was from my phone and it was really late.For example:
[1,3,7,9,5,3,4,10,7,8,8,2,1,4,5,6,10,9,2,6]
Try something like this:
int[] array = new int[20];
Random rand = new Random();
for (int i = 0; i < 20; i++)
{
int num = rand.Next(1, 10);
int pos = rand.Next(0, 19);
while (array[pos] != 0)
{
if (pos == 19)
pos = 0;
else
pos++;
}
array[pos] = num;
}
or if you want the positions to be random, but not the numbers and exactly two of each number, try this:
int[] array = new int[20];
Random rand = new Random();
for (int i = 1; i <= 10; i++)
{
int num = i;
int pos1 = rand.Next(0, 19);
while (array[pos1] != 0)
{
if (pos1 == 19)
pos1 = 0;
else
pos1++;
}
array[pos1] = num;
int pos2 = rand.Next(0, 19);
while (array[pos2] != 0)
{
if (pos2 == 19)
pos2 = 0;
else
pos2++;
}
array[pos2] = num;
}
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.
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;
}