This question already has answers here:
Making an array of random ints
(2 answers)
Closed last month.
I have just started to learn coding and was hoping someone with a little more skill would help me out a bit.
Here is the code and when i run it the displayarray is coming up as just zeros and then the sum of the array is also zero I just cant grasp why thats happening so it would be awesome if someone could help me out.
namespace random_array_2._0
{
class Program
{
static void Main(string[] args)
{
int[] array;
int sum = 0;
int arraySum;
array = CreateArray();
DisplayArray(array);
arraySum = SumTheArray(array, sum);
}
static int[] CreateArray()
{
Random Array = new Random();
for (int i = 0; i < 10; i++)
{
Console.WriteLine(Array.Next(1, 100));
}
return new int[10];
}
static void DisplayArray(int[] array)
{
Console.WriteLine();
Console.WriteLine("Sorted array in ASC order");
Array.Sort(array);
foreach (int i in array)
{
Console.Write(i + " ");
}
}
static int SumTheArray (int[] array, int sum)
{
for (int i = 0; i < array.Length; i++)
{
sum += array[i];
}
Console.WriteLine($"all together equals to: {sum}");
Console.ReadKey();
return sum;
}
}
}
Your CreateArray function is printing 10 random numbers and then returning a new array. The default value for int is 0, so this array contains 10 zeros.
You should first create the array and then populate it with random values:
static int[] CreateArray()
{
Random Array = new Random();
var a = new int[10];
for (int i = 0; i < a.Length; i++)
{
a[i] = Array.Next(1, 100);
}
return a;
}
There you go:
static int[] CreateArray()
{
Random randomNumberGenerator = new Random();
int[] array = new int[10];
for (int i = 0; i < array.Length; i++)
{
int randomNumber = randomNumberGenerator.Next(1, 100);
array[i] = randomNumber;
}
return array;
}
My advise to you is to stop using Console.WriteLine statements and start using the debugger. Console.WriteLine often lies; the debugger tends to never lie.
Your CreateArray function is not storing anything into Array, and it's returning an array with 10 zeroes (default value when none in given).
Try with
static int[] CreateArray()
{
Random rnd = new Random();
int[] Array = new int[10];
for (int i = 0; i < 10; i++)
{
Array[i] = rnd.Next(1, 100);
}
return Array;
}
Related
Goal
A C# program that picks a random number from 1 to 6 and stores it
Question
Which way to store: the entire sequence or an array of 6 elements with increments to the n-1 index for every hit of n?
Code
using System;
namespace DiceProbabilityCalc
{
class Program
{
static void Main(string[] args)
{
Random rnd = new Random();
int[] instanceCount = new int[1000];
for (int i = 0; i < 999; i++)
{
int num = rnd.Next(1, 7);
}
}
}
}
Thanks to #PeterSmith and #Martheen for solving the question in the comments: The array instanceCount can be used to store the number of instances instead of the entire sequence. This is the resulting code.
using System;
namespace DiceProbabilityCalc
{
class Program
{
static void Main(string[] args)
{
Random rnd = new Random();
int[] instanceCount = new int[6];
for (int i = 0; i < 999; i++)
{
int num = rnd.Next(1, 7);
instanceCount[num - 1]++;
}
for (int j = 0; j < instanceCount.Length; j++)
{
Console.WriteLine(instanceCount[j]);
}
}
}
}
I am making a lottery game that asks the user for 10 numbers and then check it against random numbers that i have created in an array. I need to compare the two but I am not allowed to use the contains method.
I think I need to use a foreach loop to compare the arrays but really I am at a loss of what to do. I have been piecing it together from the little I know and would like to know if I am on the right track.
Is a foreach loop the correct way to compare the two arrays?
This is my code so far.
using System;
namespace lotto2
{
class Program
{
static void Main(string[] args)
{
//an array named "input" to hold the users' 10 guesses
int[] inputs = new int[10];
//an array named "lotNum" to hold 10 random numbers
int[] lotNums = new int[10];
//a for loop to loop over the inputs array. each loop will ask the user for a number
Console.WriteLine("Enter your 10 lottery numbers one at a time. The numbers must be between 1 and 25.");
for (int i = 0; i < inputs.Length; i++)
{
inputs[i] = Convert.ToInt32(Console.ReadLine());
}
//a random number generator
Random ranNum = new Random();
//loop to call the random generator 10 times and store 10 random numbers in the "lotNum" array
for (int i = 0; i < 10; i++)
{
lotNums[i] = ranNum.Next(1, 26); //chooses random numbers between 1 and 25
}
//writes out the randomly generated lotto numbers
Console.Write("\nThe lottery numbers are: ");
for (int i = 0; i < 10; i++)
{
Console.Write("{0} ", lotNums[i]);
}
//loop for checking users inputs against random generated numbers..
//foreach loop maybe?
foreach (var input in lotNums)
{
}
//print out if there are any matches, which numbers matched
//declared integer for the correct numbers the user guessed
int correct;
//end progam
Console.WriteLine("\n\nPress any key to end the program:");
Console.ReadKey();
}
}
}
Here's a program that correctly does what you want. It even ensures that you don't have duplicate lotto numbers.
void Main()
{
const int count = 10;
const int max = 25;
//an array named "input" to hold the users' 10 guesses
int[] inputs = new int[count];
//a for loop to loop over the inputs array. each loop will ask the user for a number
Console.WriteLine("Enter your {0} lottery numbers one at a time. The numbers must be between 1 and {1}.", count, max);
for (int i = 0; i < inputs.Length; i++)
{
inputs[i] = Convert.ToInt32(Console.ReadLine());
}
//a random number generator
Random ranNum = new Random();
//an array named "allNums" to hold all the random numbers
int[] allNums = new int[max];
for (int i = 0; i < allNums.Length; i++)
{
allNums[i] = i + 1;
}
//shuffle
for (int i = 0; i < allNums.Length; i++)
{
int j = ranNum.Next(0, allNums.Length);
int temporary = allNums[j];
allNums[j] = allNums[i];
allNums[i] = temporary;
}
//an array named "lotNum" to hold 10 random numbers
int[] lotNums = new int[count];
Array.Copy(allNums, lotNums, lotNums.Length);
//writes out the randomly generated lotto numbers
Console.Write("\nThe lottery numbers are: ");
for (int i = 0; i < lotNums.Length; i++)
{
Console.Write("{0} ", lotNums[i]);
}
int correct = 0;
Console.Write("\nThe correct numbers are: ");
for (int i = 0; i < lotNums.Length; i++)
{
for (int j = 0; j < inputs.Length; j++)
{
if (lotNums[i] == inputs[j])
{
Console.Write("{0} ", lotNums[i]);
correct++;
};
}
}
Console.Write("\nYou got {0} correct. ", correct);
Console.WriteLine("\n\nPress any key to end the program:");
Console.ReadLine();
}
You're on the right way.
My implementation would be:
foreach (var input in inputs)
{
for (int i = 0; i < lotNums.Length; i++){
if(input == lotNums[i]){
Console.WriteLine(lotNums[i]);
}
}
}
This will compare every number of the input array with the lottery array.
I'm printing every match, but you can set a variable to True if it finds a match or add every matching number into an array if you need it.
This is what I have tried.I hope it makes sense?
static void LottoMethod(int[] randNums,int[] userNums)
{
Console.WriteLine("Guess 10 numbers");
for(int i = 0; i <= userNums.Length-1; i++)
{
userNums[i] = Int32.Parse( Console.ReadLine());
}
Console.WriteLine("The numbers you entered: ");
foreach(int k in userNums)
{
Console.Write(k+" ");
}
//generate 10 numbers randomly
Random rnds = new Random();
for(int k = 0; k <= randNums.Length - 1; k++)
{
randNums[k] = rnds.Next(1, 26);
}
Console.WriteLine("Random Numbers");
foreach(int i in randNums)
{
Console.Write(i + " ");
}
int correctNums = 0;
//Check if random numbers correspond with entered numbers
try
{
for(int i = 0; i <= randNums.Length-1; i++)
{
for(int j = 0; j <= userNums.Length-1; j++)
{
if (randNums[i] == userNums[j])
{
correctNums++;
}
}
}
Console.WriteLine($"There are {correctNums} numbers ");
}
catch(Exception e) {
throw new Exception(e.ToString());
}
}
You have to calculate intersection of two sequences. You have three options:
Double foreach loop. This is something to avoid as it has time complexity O(m*n). It it not a problem for 10 items, but we should make programs that scale.
Using hash join. You can use HashSet for this and it would be my preferred method. But as it inherently implies using Contains, it is not the option here.
Merging sorted sequences. This would be the way to go here.
The program is rather self explanatory, it produces and intersects two random sequences.
static Random rnd = new Random((int)DateTime.Now.Ticks);
static int[] GetRandomArray(int arrSize, int minNumber, int maxNumber)
{
int[] tmpArr = new int[maxNumber - minNumber + 1];
for (int i = 0; i < tmpArr.Length; ++i)
{
tmpArr[i] = i + minNumber; // fill with 1, 2, 3, 4,...
}
int[] ret = new int[arrSize];
for (int i = 0; i < ret.Length; ++i)
{
int index = rnd.Next(tmpArr.Length - i); //choose random position
ret[i] = tmpArr[index];
tmpArr[index] = tmpArr[tmpArr.Length - 1 - i]; //fill last of the sequence into used position
}
return ret;
}
static IEnumerable<int> GetMatches(int[] a, int[] b)
{
Array.Sort(a);
Array.Sort(b);
for (int i = 0, j = 0; i < a.Length && j < b.Length;)
{
if (a[i] == b[j])
{
yield return a[i];
++i;
++j;
}
else if (a[i] > b[j])
{
++j;
}
else
{
++i;
}
}
}
static void Main(string[] args)
{
var a = GetRandomArray(5, 3, 7);
var b = GetRandomArray(10, 1, 25);
Console.WriteLine("A: " + string.Join(", ", a));
Console.WriteLine("B: " + string.Join(", ", b));
Console.WriteLine("Matches: " + string.Join(", ", GetMatches(a, b)));
Console.ReadKey();
}
The result is something like:
A: 7, 4, 6, 3, 5
B: 17, 1, 8, 14, 11, 22, 3, 20, 4, 25
Matches: 3, 4
You can think about what would happen if one or both of the sequences contain duplicities.
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());
}
}
}
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
int n;
Console.WriteLine("Please enter a positive integer for the array size"); // asking the user for the int n
n = Int32.Parse(Console.ReadLine());
int[] array = new int[n]; // declaring the array
int[] newarray = new int[n];
Random rand = new Random();
for (int i = 0; i < array.Length; i++)
{
array[i] = i + 1;
}
for (int y = 0; y < newarray.Length; y++)
{
int caseSwitch = 1;
switch (caseSwitch)
{
case 1:
newarray[y] = array[rand.Next(n)];
goto case 2;
case 2:
for (int z = y+1; z > 0; z--)
{
if (newarray[y] == newarray[z-1])
goto case 1;
}
break;
}
}
for (int x=0;x<newarray.Length;x++)
{
Console.Write(" {0}", newarray[x]);
}
Console.ReadLine();
This is the code i have started with but its not displaying any values, is it not filling the array? I'm new to this so any help would be much appreciated
I think your approach is extremely overly complicated for this. You should take a step back, think about what it is that you wish to accomplish, plan it out first, then start programming.
What you want to do is sort your array with a random sort order.
Create a new IComparer that returns the comparison randomly:
public class RandomComparer<T> : IComparer<T> {
private static Random random = new Random();
public int Compare(T a, T b) {
return random.Next(2) == 0 ? 1 : -1;
}
}
Now, sort your array:
int[] array = {
1, 2, 3, 4, 5,
6, 7, 8, 9, 10
};
Array.Sort<int>(array, new RandomComparer<int>());
for (int i = 0; i < array.Length; i++)
Console.WriteLine(array[i]);
It's really that simple. See this demonstration at IDEOne.com
It seems to get into an infinite loop. Try changing this bit:
case 2:
for (int z = y; z > 0; z--)
{
if (newarray[y] == newarray[z-1])
goto case 1;
}
break;
The reason you're not seeing any output is because the code isn't running to completion - it ends up bouncing between case 1 and 2 because
if (newarray[y] == newarray[z - 1])
is always true.
My recommendation would be to debug (i.e. step through) your code so you can really see why this is the case, then you'll be able to fix the code yourself :)
You can do it like this:
...
n = Int32.Parse(Console.ReadLine());
// Initial array filled with 1..n values
int[] data = Enumerable.Range(1, n).ToArray();
// data array indice to show, initially 0..n-1
List<int> indice = Enumerable.Range(0, n - 1).ToList();
Random gen = new Random();
for (int i = 0; i < n; ++i) {
if (i != 0)
Console.Write(' ');
index = gen.Next(indice.Count);
Console.Write(data[indice[index]]);
// Index has been shown, let's remove it since we're not going to show it again
indice.RemoveAt(index);
}
...
What you are trying to do is to generate a random permutation. You could try the following:
var rand = new Random();
var left = Enumerable.Range(1, n).ToList();
for(int i=0; i<n; ++i)
{
int j = rand.Next(n-i);
Console.Out.WriteLine(left[j]);
left[j].RemoveAt(j);
}
This is the simplest way to do it using a random comparison.
class Program
{
static Random rnd=new Random();
static void Main(string[] args)
{
int[] array= { 1, 2, 3, 4, 5, 6 };
int[] newarray=new int[array.Length];
array.CopyTo(newarray, 0);
Array.Sort(newarray, (i, j) => rnd.NextDouble()<0.5?-1:1);
// newarray is now randomly ordered
}
}
You can randomly switch the values :
int n;
Console.WriteLine("Please enter a positive integer for the array size"); // asking the user for the int n
n = Int32.Parse(Console.ReadLine());
int[] array = new int[n]; // declaring the array
int[] newarray = new int[n];
Random rand = new Random();
for (int i = 0; i < array.Length; i++)
{
array[i] = i + 1;
newarray[i] = i + 1;
}
for (int y = 0; y < newarray.Length; y++)
{
int r = rand.Next(n);
int tmp = newarray[y];
newarray[y] = newarray[r];
newarray[r] = tmp;
}
for (int x=0;x<newarray.Length;x++)
{
Console.Write(" {0}", newarray[x]);
}
Console.ReadLine();
use following code
int[] array = new int[n];
int[] randomPosition = new int[n];
Enumerable.Range(0, n ).ToList().ForEach(o => array[o] = o+1);
Random r = new Random();
Enumerable.Range(0, n).ToList().ForEach(o => randomPosition[o] = r.Next(0, n - 1));
foreach (var m in randomPosition)
{
var randomNumber = array[m];
//write randomnumber
}
I'm a newbie, shifted from iOS to WP7.
I'm generating a random number series, which I want to store into an array. In iOS it was like this
for(int i=0; i < num; i++) {
int rand = arc4random_uniform(70);
if([rand_array containsObject:[NSNumber numberWithInt:rand]]) {
i--;
}
I've searched, googled but thought this is the place where I can ask a question. Kindly help me.
int min = 1;
int max = 4;
int num = 3;
Random r = new Random();
Int[] ar ;
ar = new Int[num]; // Creates array with 3 palces {ar[0],ar[1],ar[2])
for(i = 0;i =< num - 1;i++) {
ar[i] = r.Next(min,max); // generate random number between 1-4 (include 1 & 4)
}
I think this is should work (or I didnt understand you).
Good luck=]
Enumerable.Range(1, 70) generates numbers from 1 to 70.
Then we shuffle them like a deck of cards.
int[] randomNumbers = Enumerable.Range(1, 70).Shuffle(new Random()).ToArray();
This needs to be in a separate class in the same folder.
public static IEnumerable<T> Shuffle<T>(this IEnumerable<T> source, Random random)
{
T[] list = source.ToArray();
int count = list.Length;
while (count > 1)
{
int index = random.Next(count--);
yield return list[index];
list[index] = list[count];
}
yield return list[0];
}
Is this what you wanted?
i don't see the sense in your code. I would use a List.
for(int i=0; i < num; i++)
{
int rand = arc4random_uniform(70);//hope you know what you did here, I don't
if(yourList.Contains(rand))
i--;
else
yourList.Add(rand);
}
if the list doesn't contain the random number, it will add it, otherwise it will just repeat.
In C# do something like this:
List<int> numbers = new List<int>();
for ( int i = 0; i < num, i++ ) {
int rand = GetARandomNumber();
if ( !numbers.Contains( rand ) ) {
numbers.Add( rand );
} else {
i--;
}
}
You'd also probably do well to convert this to a while loop:
List<int> numbers = new List<int>();
while ( numbers.Count < num ) {
int rand = GetARandomNumber();
if ( !numbers.Contains( rand ) ) {
numbers.Add( rand );
}
}
It's simple, really! A direct port of your code would look something like:
List<int> rand_array = new List<int>();
for(int i = 0; i < num; i++)
{
int rand = RandomHelper.GetInt(0, 70);
if(rand_array.Contains(rand))
{
i--;
continue;
}
rand_array.Add(rand);
}
To generate random numbers in C# there is a class aptly called "Random". You only really need to use one instance of the Random class to generate numbers, so if you wanted something like this:
static class RandomHelper
{
static Random rng = new Random(); // Seed it if you need the same sequence of random numbers
public static int GetInt(int min, int max)
{
return rng.Next(min, max);
}
}