Create 10 Unique numbers and save to array - c#

I am trying to generate 10 unique random numbers and save it to an array.
Here is my code, but there is run-time error, but I dunno how.
Can someone help me please ?
static void Main(string[] args)
{
int [] generatedNum = new int[10];
bool duplicated;
int tempo;
Random random = new Random();
// Create first number
generatedNum[0] = random.Next(1, 25);
for (int i = 1; i < 10; i++)
{
tempo = random.Next(0, 25);
do
{
duplicated = false;
foreach (int x in generatedNum)
{
if (x == tempo)
duplicated = true;
}
if (duplicated == true)
tempo = random.Next(0, 25);
} while (duplicated == true);
// Save unique number to array
generatedNum[i] = tempo;
}
// To check the number saved
foreach (int i in generatedNum)
{
Console.WriteLine("{0}", generatedNum[i]);
}
}

This may helps:
public List<int> GetNumber()
{
Random random = new Random();
List<int> values = new List<int>();
values.Add(random.Next(0, 25));
while (values.Count < 10)
{
int newValue;
do
{
newValue = random.Next(0, 25);
} while (values.Contains(newValue));
values.Add(newValue);
}
return values;
}

To have x unique items out of an array of y, you need a shuffle bag.
You put your numbers 1-25 in a bag, shuffle it and then take the first 10 items. You will now have 10 random items between 1 & 25.

Your last foreach loop is invalid. i is the value, not index, so you can write it directly:
// To check the number saved
foreach (int i in generatedNum)
{
Console.WriteLine("{0}", i);
}

Change
foreach (int i in generatedNum)
{
Console.WriteLine("{0}", generatedNum[i]);
}
to
for (int j=0;j<generatedNum.Length;j++)
{
Console.WriteLine("{0}", generatedNum[j]);
}

Would this work
If you are allowed to use Linq you can try something like this
You can set the range you want
Random rnd = new Random();
var randomNumbers = Enumerable.Range(1, 100)
.Select(x => new { val = x, order = rnd.Next() })
.OrderBy(i => i.order)
.Select(x => x.val)
.Take(10).ToArray();

static void Main(string[] args)
{
var generatedNum = new List<int>();
var random = new Random();
while (generatedNum.Count < 10)
{
var tempo = random.Next(0, 25);
if (generatedNum.Contains(tempo)) continue;
generatedNum.Add(tempo);
}
foreach (var i in generatedNum)
{
Console.WriteLine("{0}", i);
}
}
And you problem was here no?
// To check the number saved
foreach (int i in generatedNum)
{
Console.WriteLine("{0}", generatedNum[i]);
}

/*try this,i used an arraylist to store the digits
using System;
using System.Collections;
public class SamplesArrayList
{
public static void Main()
{
// Creates and initializes a new ArrayList.
ArrayList values = new ArrayList();
Random random = new Random();
values.Add(random.Next(0, 25));
while (values.Count < 10)
{
int newValue;
do
{
newValue = random.Next(0, 25);
} while (values.Contains(newValue));
values.Add(newValue);
}
PrintValues(values);
}
public static void PrintValues(IEnumerable myList)
{
foreach (Object obj in myList)
Console.Write(" {0}", obj);
Console.WriteLine(myList);
}
}

Related

Creating an array of 10 elements and assigning them by counting randomly

Creating an array of 10 elements and assigning them by counting randomly, assigning a new number if the same numbers are repeated
I tried to use the contains method but it didn't appear in the list after the array, I used the exists method but it didn't work either, what kind of way should I follow? thanks
static void Main(string[] args)
{
Random Rnd = new Random();
int[] Numbers = new int[10];
for (int i = 0; i < Numbers.Length; i++)
{
int rast = Rnd.Next(10);
bool b = Array.Exists(Numbers, element => element == rast);
if (!b)
{
i--;
}
else { Numbers[i] = rast; }
}
foreach (int item in Numbers)
{
Console.WriteLine(item);
}
}
It appears that you want the numbers from 0 to 9 in an array in random order. If that is so:
var rng = new Random();
var numbers = Enumerable.Range(0, 10).OrderBy(n => rng.NextDouble()).ToArray();
You're close, but there are two issues in your algorithm:
if (!b) should be if (b)
Rnd.Next(1,10) gets numbers between 1 and 9 so you will never get a 10 and the algorithm will never finish.
After fixing these two your program will work.
Anyway, here's a version that uses .Contains
Random Rnd = new Random();
int[] Numbers = new int[10];
for (int i = 0; i < Numbers.Length; i++)
{
// + 1 because the range of return values includes minValue but not maxValue.
int r = Rnd.Next(minValue: 1, maxValue: Numbers.Length + 1);
while(Numbers.Contains(r))
{
r = Rnd.Next(minValue: 1, maxValue: Numbers.Length + 1);
}
Numbers[i] = r;
}
Console.WriteLine(string.Join(",", Numbers));
Example output:
9,8,7,1,4,6,3,10,5,2
Here's an example. I hope this is the output you want.
public static void Main()
{
Random Rnd = new Random();
int[] Numbers = new int[10];
for (int i = 0; i < Numbers.Length; i++)
{
int rast = Rnd.Next(10);
bool b = Array.Exists(Numbers, element => element == rast);
if (!b)
{
Numbers[i] = rast;
Console.WriteLine(rast);
}
else {
i--;
}
}
}
As a result, I have found the solution, thanks to everyone who answered and showed me the way
int[] Numbers = new int[10];
int x, y;
Random ran = new Random();
for (x = 0; x < 10; x++)
{
Numbers[x] = ran.Next(1, 10);
for (y = x; y >= 0; y--)
{
if (x == y)
{
continue;
}
if (Numbers[x] == Numbers[y])
{
Numbers[x] = ran.Next(1, 10);
y = x;
}
}
Console.WriteLine(Numbers[x]);
}
when i created new project as Console .net in visual studio 2019 ,
it doesnt bring this libraries automatically ,
Because the following libraries are not attached, the codings I used before did not work, I developed another simple solution, and in this way, I realized that I had a problem due to these libraries not being attached.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
int[] Numbers= new int[10];
Random rnd = new Random();
for (int i = 0; i < Numbers.Length; i++)
{
int Num= rnd.Next(10);
if (Numbers.Contains(Num))
{
i--;
}
else
{
Console.WriteLine(Numbers[i] = Num);
}
}

Generate and store 7 random numbers in a array

I made a program to generate 7 random numbers for a lottery using a array. I have generated a random number between 1, 50 but every number shows in order and not on the same line. I would also like to store the auto generated numbers in a array to use. I am not sure how to fix this any help would be appreciated
static void AutoGenrateNumbers()
{
int temp;
int number = 0;
int[] lotto = new int[7];
Random rand = new Random();
for (int i = 0; i <= 50; i++)
{
number = 0;
temp = rand.Next(1, 50);
while (number <= i)
{
if (temp == number)
{
number = 0;
temp = rand.Next(1, 50);
}
else
{
number++;
}
}
temp = number;
Console.WriteLine($"the new lotto winning numbers are:{number}Bonus:{number}");
}
}
Is this what you need?
static void AutoGenrateNumbers()
{
int temp;
int[] lotto = new int[7];
Random rand = new Random();
for (int i = 0; i < 7; i++)
{
temp = rand.Next(1, 50);
lotto[i]= temp;
}
Console.Write($"the new lotto winning numbers are: ");
for (int i = 0; i < 6; i++)
{
Console.Write(lotto[i]+" ");
}
Console.Write($"Bonus:{lotto[6]}");
}
edit: if you want the numbers to be unique:
static void AutoGenrateNumbers()
{
int temp;
int[] lotto = new int[7];
Random rand = new Random();
for (int i = 0; i < 7; i++)
{
do
{
temp = rand.Next(1, 50);
}
while (lotto.Contains(temp));
lotto[i]= temp;
}
Console.Write($"the new lotto winning numbers are: ");
for (int i = 0; i < 6; i++)
{
Console.Write(lotto[i]+" ");
}
Console.Write($"Bonus:{lotto[6]}");
}
A better way to do this is just to generate all the numbers 1-50, shuffle them and then just take 7. Using Jon Skeet's Shuffle extension method found here:
public static IEnumerable<T> Shuffle<T>(this IEnumerable<T> source, Random rng)
{
T[] elements = source.ToArray();
for (int i = elements.Length - 1; i >= 0; i--)
{
int swapIndex = rng.Next(i + 1);
yield return elements[swapIndex];
elements[swapIndex] = elements[i];
}
}
Now your code is very simple:
static void AutoGenrateNumbers()
{
var lotto = Enumerable.Range(0, 50).Shuffle(new Random()).Take(7);
Console.WriteLine("the new lotto winning numbers are: {0}", string.Join(",", lotto));
}
Fiddle here
Just to add to the existing answers tried to do that in one LINQ statement:
static void Main(string[] args)
{
var rand = new Random();
Enumerable
.Range(1, 7)
.Aggregate(new List<int>(), (x, y) =>
{
var num = rand.Next(1, 51);
while (x.Contains(num))
{
num = rand.Next(1, 51);
}
x.Add(num);
return x;
})
.ForEach(x => Console.Write($"{x} "));
}
The result is something like:
34 24 46 27 11 17 2

Take 30 random elements from list

I have a list of strings containing loads of hashtags with texts.
ex #csharp #java ect.
each hashtag is a own string in a List. I now want to randomly always console.writeline 30 items of that list.
List
List<string> Hashtags = new List<string>();
Writeline
foreach (var x in Hashtags) {
Console.WriteLine(x);
}
Ideally i never wanna have the same hashtag in the random 30.
You should try this:
var rnd = new Random();
foreach (var x in Hashtags.OrderBy(x => rnd.Next()).Take(30))
{
Console.WriteLine(x);
}
This has O(n^2) complexity, but is easily readable.
If you want efficiency try a Fisher-Yates Shuffle, it's O(n), but less readable:
var take = 30;
var rnd = new Random();
for (var i = 0; i < (Hashtags.Count < take ? Hashtags.Count : take); i++)
{
var j = rnd.Next(Hashtags.Count);
(Hashtags[i], Hashtags[j]) = (Hashtags[j], Hashtags[i]);
}
foreach (var x in Hashtags.Take(take))
{
Console.WriteLine(x);
}
Keep in mind, though, that it's best to instantiate Random once per thread, so this would be a better way:
[ThreadStatic]
private static Random rnd = new Random();
This should do. It is efficient, as it shuffles only the required amount of items, not the whole collection. You pass how many elements you want to fetch from the array as parameter(elementCount).
private static Random randomGenerator = new Random();
static void Main()
{
var hashtags = new List<string>() { "c#", "javascript", "ef", "asp.net" };
var result = GetRandomItems<string>(hashtags, 2);
foreach (var item in result)
{
Console.WriteLine(item);
}
}
private static IEnumerable<T> GetRandomItems<T>(IEnumerable<T> collection, int elementCount)
{
var collectionCount = collection.Count();
if (elementCount > collectionCount)
{
elementCount = collectionCount;
}
var collectionCopy = collection.ToList();
var randomIndex = randomGenerator.Next(0, collectionCopy.Count);
for (var index = 0; index < elementCount; index++)
{
var tempElement = collectionCopy[index];
collectionCopy[index] = collectionCopy[randomIndex];
collectionCopy[randomIndex] = tempElement;
randomIndex = randomGenerator.Next(index + 1, collectionCopy.Count);
}
return collectionCopy.Take(elementCount);
}
Call 30 times Random.next
https://learn.microsoft.com/en-us/dotnet/api/system.random.next
var random = new Random();
//calls this n times in a loop:
Console.writeline(Hashtags[random.next(Hashtags.Count])
Got it working myself, little more verbose but hopefully easier to follow.
var random = new Random();
var uniques = Hashtags;
for (var i = 0; i < 30; i++) {
var index = random.Next(0, uniques.Count());
Console.WriteLine(uniques[index]);
uniques.RemoveAt(index);
}

Select a number randomly from 1 to 99

I want to select a random number from 1 to 99. And then select the number again but this time discard the previous number. Can someone help me.
private List<int> numbers = Enumerable.Range(0, 100).ToList();
private Random rnd = new Random();
public int GetRandomInt()
{
var index = rnd.Next(0, numbers.Length);
var number = numbers[index];
numbers.RemoveAt(index);
return number;
}
Here's what I'd do:
var rnd = new Random();
var numbers = new Stack<int>(Enumerable.Range(1, 99).OrderBy(x => rnd.Next()));
You effectively are randomizing the list of numbers and then adding them to a stack. Now you just have to do this to get each number:
var next = numbers.Pop()
You stop when numbers.Count == 0. Simple.
Here is the revised version of Khanh TO, because it is not correct:
List<int> usedNumbers = new List<int>();
Random rand = new Random(new object().GetHashCode());
int number = 0;
for (int i = 0; i < 99; i++)
{
do
{
number = 1 + rand.Next(0, 99);
} while (usedNumbers.Contains(number));
usedNumbers.Add(number);
}
I usually do it with arrays.
Whenever you create a random number just put on the array. so next time check if the number is already generated by checking in the array.
Try this
IList<int> arr = Enumerable.Range(1, 99).ToList();
int randNum;
Random rnd = new Random();
randNum = rnd.Next(1, arr.Count());
MessageBox.Show(randNum.ToString());
arr = arr.Where(x => x != randNum).ToList();
Can I go for the shortest code, without a nested loop, or removing list elements.
Code 1
class Program
{
static Random rnd=new Random();
static void Main(string[] args)
{
var list=new SortedDictionary<double, int>();
// Fill list
for (int i=1; i<=99; i++)
{
list.Add(rnd.NextDouble(), i);
}
// List Automatically random
var random_int=list.Values.ToArray();
// random_int = {45, 7, 72, .. }
}
}
Code 2
class Program
{
static Random rnd=new Random();
static void Main(string[] args)
{
var list=new int[99];
// Fill list
for (int i=1; i<=99; i++)
{
list[i-1]=i;
}
Comparison<int> any=(x, y) =>
{
var z=2*rnd.NextDouble()-1;
return z.CompareTo(0);
};
// Randomize List
Array.Sort(list, any);
// list = { 49, 59, 21, 7, 18 ...}
}
}

Sorting a List<int>

Using C# what is the best way to sort a List numerically?
my list has items 5,7,3 and I would like them sorted 3,5,7. I know some longer ways, but I would imagine linq has a quicker way?
sorry this was end of day, my mind is else where it worked, didn't see it change the first time:(
There's no need for LINQ here, just call Sort:
list.Sort();
Example code:
List<int> list = new List<int> { 5, 7, 3 };
list.Sort();
foreach (int x in list)
{
Console.WriteLine(x);
}
Result:
3
5
7
Keeping it simple is the key.
Try Below.
var values = new int[5,7,3];
values = values.OrderBy(p => p).ToList();
var values = new int[] {5,7,3};
var sortedValues = values.OrderBy(v => v).ToList(); // result 3,5,7
List<int> list = new List<int> { 5, 7, 3 };
list.Sort((x,y)=> y.CompareTo(x));
list.ForEach(action => { Console.Write(action + " "); });
Sort a list of integers descending
class Program
{
private class SortIntDescending : IComparer<int>
{
int IComparer<int>.Compare(int a, int b) //implement Compare
{
if (a > b)
return -1; //normally greater than = 1
if (a < b)
return 1; // normally smaller than = -1
else
return 0; // equal
}
}
static List<int> intlist = new List<int>(); // make a list
static void Main(string[] args)
{
intlist.Add(5); //fill the list with 5 ints
intlist.Add(3);
intlist.Add(5);
intlist.Add(15);
intlist.Add(7);
Console.WriteLine("Unsorted list :");
Printlist(intlist);
Console.WriteLine();
// intlist.Sort(); uses the default Comparer, which is ascending
intlist.Sort(new SortIntDescending()); //sort descending
Console.WriteLine("Sorted descending list :");
Printlist(intlist);
Console.ReadKey(); //wait for keydown
}
static void Printlist(List<int> L)
{
foreach (int i in L) //print on the console
{
Console.WriteLine(i);
}
}
}
Sort list of int descending you could just sort first and reverse
class Program
{
static void Main(string[] args)
{
List<int> myList = new List<int>();
myList.Add(38);
myList.Add(34);
myList.Add(35);
myList.Add(36);
myList.Add(37);
myList.Sort();
myList.Reverse();
myList.ForEach(Console.WriteLine);
}
}
double jhon = 3;
double[] numbers = new double[3];
for (int i = 0; i < 3; i++)
{
numbers[i] = double.Parse(Console.ReadLine());
}
Console.WriteLine("\n");
Array.Sort(numbers);
for (int i = 0; i < 3; i++)
{
Console.WriteLine(numbers[i]);
}
Console.ReadLine();

Categories