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);
}
}
Related
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;
}
I am looking for a way to sort a List as fast as possible as this will happen trillions of times.
The loop generates decimal values and then the string will be put into a "sortedLIST". Here I want the lowest decimal value to be at top of the list and the highest decimal value at the bottom of the list.
In this scenario. How can we do this as fast as possible?
Thank you!
void sortfunction()
{
//The decimal values will actually dynamically be calculated in this loop in reality
List<String> sortedLIST = new List<String>();
Random random = new Random();
double rand = 0;
double num = 0;
String str = "";
for (int i = 0; i < 500000; i++)
{
rand = random.Next(0, 99);
num = rand / 100;
str = num + "|hello1|hello2|hello3";
//Is it possible to sort the values on the FLY here directly somehow with the LOWEST at the top.
//So insert them at the correct index right away somehow or if there is faster approach?
sortedLIST.Add(str);
}
}
As I mentioned in the comments, you don't need to add the string prefix to every item, you can just add it when you take something out of the list. This means you can store the list as a list of int rather than string.
As you know the number of items you are creating you can pre-size the list when creating it to avoid reallocations when populating it. Once it's populated you can call Sort which swithces between quick sort, heap sort and insertion sort depending on the number of items in the list.
Here's the code:
void sortfunction()
{
const int numberOfItems = 500000;
var sortedList = new List<double>(numberOfItems);
Random random = new Random();
for (int i = 0; i < numberOfItems; i++)
{
var rand = random.Next(0, 99);
var num = rand / 100d;
sortedList.Add(num);
}
sortedList.Sort();
}
Using System.Linq you can quickly sort a List through the use of OrderBy(IEnumerable, Func) . It is quick, especially whenit comes to int or string comparisons.
List.OrderBy(a=> a);
Use recursion with a Merge Sort algorithm:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Merge_sort
{
class Program
{
static void Main(string[] args)
{
List<int> unsorted = new List<int>();
List<int> sorted;
Random random = new Random();
Console.WriteLine("Original array elements:" );
for(int i = 0; i< 10;i++){
unsorted.Add(random.Next(0,100));
Console.Write(unsorted[i]+" ");
}
Console.WriteLine();
sorted = MergeSort(unsorted);
Console.WriteLine("Sorted array elements: ");
foreach (int x in sorted)
{
Console.Write(x+" ");
}
Console.Write("\n");
}
private static List<int> MergeSort(List<int> unsorted)
{
if (unsorted.Count <= 1)
return unsorted;
List<int> left = new List<int>();
List<int> right = new List<int>();
int middle = unsorted.Count / 2;
for (int i = 0; i < middle;i++) //Dividing the unsorted list
{
left.Add(unsorted[i]);
}
for (int i = middle; i < unsorted.Count; i++)
{
right.Add(unsorted[i]);
}
left = MergeSort(left);
right = MergeSort(right);
return Merge(left, right);
}
private static List<int> Merge(List<int> left, List<int> right)
{
List<int> result = new List<int>();
while(left.Count > 0 || right.Count>0)
{
if (left.Count > 0 && right.Count > 0)
{
if (left.First() <= right.First()) //Comparing First two elements to see which is smaller
{
result.Add(left.First());
left.Remove(left.First()); //Rest of the list minus the first element
}
else
{
result.Add(right.First());
right.Remove(right.First());
}
}
else if(left.Count>0)
{
result.Add(left.First());
left.Remove(left.First());
}
else if (right.Count > 0)
{
result.Add(right.First());
right.Remove(right.First());
}
}
return result;
}
}
}
source:
https://www.w3resource.com/csharp-exercises/searching-and-sorting-algorithm/searching-and-sorting-algorithm-exercise-7.php
I need to generate 10 different numbers(integers). My problem is that the first and last number has to be the same. How can I make a code for this logic?
The numbers are later used to populate a polar chart.
Random random = new Random();
int randomNumber = random.Next(5, 16);
int firstRand = 0;
firstRand = randomNumber;
if(indataInt2 == 0)
{
firstRand = randomNumber;
}
else if(indataInt2 >= 360 && firstRand != randomNumber)
{
randomNumber = firstRand;
}
Something like this should do the job
List<int> randomNumber = new List<int>();
Random random = new Random();
for (int i = 0; i < 9; i++)
{
randomNumber.Add(random.Next());
}
randomNumber.Add(randomNumber[0]);
First things first, when using the Random class you can provide a seed in
which will specify how the number is generated. Therefore I provided
a seed for you. This seed is always changing so the random number will
always be different. Remember, Random isn't Random, Random(Seed)
is Random! The list in which you are looking for is named 'Numbers'.
Hopefully this code can help you:
using System.Collections.Generic;
using System;
namespace Degubbing
{
class DebugProgram
{
static void Main(string[] args)
{
List<int> Numbers = new List<int> { };
int Seed = DateTime.Now.Millisecond;
Random Generator = new Random(Seed);
for (int i = 0; i < 10; i++)
{
int RandomNum = Generator.Next(10000000, 20000000);
string Result = RandomNum.ToString();
Result = Result.Remove(Result.Length - 1);
Result = Result + Result[0];
Console.WriteLine(Result);
}
Console.ReadKey();
}
}
}
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());
}
}
}
User enters numbers to 10 textbox and i sent them to an array. Now i want to generate random numbers from this array. What can i do?
Something like this:
public class Randomizer<T>
{
private readonly Random _random = new Random();
private readonly IList<T> _numbers;
public Randomizer(IList<T> numbers)
{
_numbers = numbers;
}
public T Next()
{
int idx = _random.Next(0, _numbers.Count);
return _numbers[idx];
}
}
Usage:
var r = new Randomizer<int>(new int[] { 10, 20, 30, 40, 50 });
for (int i = 0; i < 100; i++)
Console.Write(r.Next() + " ");
Or do you want to shuffle the array?
[Edit]
To shuffle the array, you can use the Fisher–Yates shuffle shown in this post:
// https://stackoverflow.com/questions/108819/110570#110570
public class Shuffler
{
private Random rnd = new Random();
public void Shuffle<T>(IList<T> array)
{
int n = array.Count;
while (n > 1)
{
int k = rnd.Next(n);
n--;
T temp = array[n];
array[n] = array[k];
array[k] = temp;
}
}
}
If you want the interface to be same as the Randomizer class above, you can modify it to use the Shuffler class:
public class Randomizer<T>
{
private readonly Shuffler _shuffler = new Shuffler();
private readonly IList<T> _numbers;
public Randomizer(IList<T> numbers)
{
_numbers = new List<T>(numbers);
_shuffler.Shuffle(_numbers);
}
volatile int idx = 0;
public T Next()
{
if (idx >= _numbers.Count)
{
_shuffler.Shuffle(_numbers);
idx = 0;
}
return _numbers[idx++];
}
}
Note that the code is not thread safe, so some locking should be implemented if Next method might be called simultaneously from multiple threads.
Seed the standard System.Random class with a value from the array? If you need your random numbers to depend on ALL array items, then just XOR them all.
public static Random BuildSeededRandom(int[] data)
{
if ( data == null || data.Length < 1 )
return new Random();
int xor = 0;
foreach ( var i in data )
xor ^= i;
return new Random(xor);
}