Generating random numbers from giving numbers in c# - c#

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);
}

Related

How to assign a new value from Method's Array to the Variable?

My main goal is to create a Method, where it is possible to enter a number, out of which a Method will choose some other numbers (according to the purpose) and combine them in Array.
I need this Array and its value to be flexible, so I decided to create a new variable, that is within the scope for both Container() and Main() methods. Then I assigned a value from Container() to optainer, but it didn't work (foreach doesn't display all numbers from Container(), only the first one). Where is my problem?
static int[] optainer;
static void Container()
{
uint numb = uint.Parse(Console.ReadLine());
for (int i = 1000000; i >= 1; i--)
{
if (numb % i == 0)
{
optainer = new int[] { i };
}
}
}
static void Main(string[] args)
{
Console.WriteLine("Enter num. from 1 to 1 000 000");
Container();
foreach (int iw in optainer)
{
Console.WriteLine(iw);
}
// Expected: few numbers according to the condition; Real result: 1
```
You have always only one element in optainer,
this line is the error
optainer = new int[] { i }; you create always a new array with only one item and the last is always 1.
you can change in this way
static List<int> optainer = new List<int>();
static void Main(string[] args)
{
Console.WriteLine("Enter num. from 1 to 1 000 000");
Container();
foreach (int iw in optainer)
{
Console.WriteLine(iw);
}
}
static void Container()
{
uint numb = uint.Parse(Console.ReadLine());
for (int i = 1000000; i >= 1; i--)
{
if (numb % i == 0)
{
optainer.Add(i);
}
}
}
I'm sure there's a sexier way to do this, but try this:
static void Container()
{
uint numb = uint.Parse(Console.ReadLine());
for (int i = 1000000; i >= 1; i--)
{
if (numb % i == 0)
{
int size = optainer.Length + 1;
Array.Resize(ref optainer, size);
optainer[size - 1] = i;
}
}
}
Everytime you write
optainer = new int[] { i };
you create a new list(you overwrite the old one) you would have to append
to the array. Therefore you would need to know the size of the array.
To save memory you should use something more dynamic like lists.
Here is an explanation how to add a value:
Adding values to a C# array

C#: How to assign random int values to variables?

I have made a dice class that includes a method which uses random.next to determine a random int value from 1-6.
Fairdice.cs:
class FairDice
{
//defining variable and property
private Random rnd;
public int Current { get; private set; }
public FairDice()
{
rnd = new Random(Guid.NewGuid().GetHashCode());
Current = 0;
}
public int FRoll()
{
Current = rnd.Next(1, 7);
return Current;
}
RollDice.cs that features a loop for printing.
static class RollDice
{
public static void Roll(this int count, Action action)
{
for (int i = 0; i < count; i++)
{
action();
}
}
}
Program.cs includes this code, which prints out 5 random values between 1-6:
FairDice fd = new FairDice();
5.Roll(() => Console.WriteLine("Dice: " + fd.FRoll()));
Problem: I wish to assign the random values in each variable and store and save them in either a list or array for future use.
clarification:
lets say it prints out the numbers: 1, 2, 3, 4, 5 - i then wish to assign each value a variable: a = 1, b = 2, ... f = 5.
and/or simply store the values in an array {1, 2, 3, 4, 5}
Is there any way to do this?
If you want to store the values returned by calling FRoll then you could do something like this:
FairDice fd = new FairDice();
var numbers = new List<int>();
5.Roll(() => numbers.Add(fd.FRoll())); // Append the values to the list as we generate them
var firstNumberRolled = numbers[0]; // Access the values later
Console.WriteLine($"The first number rolled was {firstNumberRolled}");
Once the throw results are into an array you can extract assign variables as necessary.
class FairDice
{
private static int _seed;
private static ThreadLocal<Random> threadLocal = new ThreadLocal<Random>
(() => new Random(Interlocked.Increment(ref _seed)));
static FairDice()
{
_seed = Environment.TickCount;
}
private static Random Rng { get { return threadLocal.Value; } }
public int Roll()
{
return Rng.Next(1, 6);
}
}
static class RollDice
{
public static int[] Roll(this int count, FairDice dice)
{
int[] values = new int[count];
for (int i = 0; i < count; i++)
{
values[i] = dice.Roll();
}
return values;
}
}
class Program
{
static void Main(string[] args)
{
FairDice fd = new FairDice();
int[] values = 5.Roll(fd);
Console.WriteLine(String.Join(",", values.Select(x => x.ToString()).ToArray()));
}
}
add this to FairDice (lines with '*'):
class FairDice
* private int[] returnedValues;
public int FRoll()
{
Current = rnd.Next(1, 7);
* returnedValues[Current]++;
return Current;
}
*public void GetreturnedValues()
* {
* for (int i = 1; i < 7; i++)
* {
* Console.WriteLine("{0}: {1}", i, returnedValues[i]);
* }
* }
After this adding d.GetreturnedValues(); to you Program.cs will show how many time the different values where thrown.

C# Am I doing "Bays & Durham Randomization by Shuffling" correctly?

I tried to improvise a random number generator by using the "Bays & Durham Randomization by Shuffling" algorithm. I followed a tutorial online and made this code:
public int[] GenerateRandomSequence_Improved(int n, int min, int max)
{
int[] seq = new int[n];
for(int i = 0; i < n; i++)
{
int rand = GenerateNextRandomNumber(min, max);
rand = min + rand % (max + 1 - min);
seq[i] = rand;
}
return seq;
}
I wanna know if I did it correctly or not..
EDIT: This is the code for the GenerateNextRandomNumber method
public int GenerateNextRandomNumber(int min, int max)
{
return cSharpRNG.Next(min,max);
}
According to Knuth TAOCP Vol. 2 p. 34 Algorithm B, the proper algorithm is the following,
public class BaysDurham
{
private readonly int[] t;
private int y; // auxiliary variable
// Knuth TAOCP Vol. 2 p. 34 Algorithm B
public BaysDurham(int k)
{
t = new int[k];
for (int i = 0; i < k; i++)
{
t[i] = rand.Next();
}
y = rand.Next();
}
public int Next()
{
var i = (int)((t.Length * (long) y) / int.MaxValue); // mitigates the bias
y = t[i];
t[i] = rand.Next();
return y;
}
private readonly Random rand = new Random();
}
I let you adapt the range of the output, but just know that the formula you use with the modulo introduce significant bias and makes the distribution non-uniform please look at this.
Here is what I believe proper implementation of the Bays-Durham shuffling. Warning wrt bias in indexing due to modulo operation is right though.
.NET Core 2.2, x64 Win10
using System;
using System.Diagnostics;
namespace BaysDurhamShuffling
{
public class BaysDurhamRNG
{
public int[] _table;
public int _xnext;
public Random _rng = null;
public BaysDurhamRNG(int n, int seed = 312357) {
Debug.Assert(n > 1);
_rng = new Random(seed);
_table = new int [n];
for(int k = 0; k != n; ++k) {
_table[k] = _rng.Next();
}
_xnext = _rng.Next();
}
public int next() {
var x = _xnext; // store return value
var j = _xnext % _table.Length; // form the index j into the table
_xnext = _table[j]; // get jth element of table and to copy it to the output stream on next call
_table[j] = _rng.Next(); // replace jth element of table with next random value from input stream
return x; // return what was stored in next value
}
}
class Program
{
static void Main(string[] args)
{
var rng = new BaysDurhamRNG (16, 12345);
for(int k = 0; k != 30; ++k) {
var x = rng.next();
Console.WriteLine($"RV = {x}");
}
}
}
}

Creating a reverse ordered array

I am currently trying to create an array and display it reverse or descending order. It currently displays a list of numbers but sometimes it does not follow the correct descending order. I believe the issues is in the if statement in between the two for loops, each time I am comparing a random number between 1-101 with the first number in your array. Instead of doing it that way, How can I compare the numbers in the array with each other? Or any suggestion in proving my reverse order array generator?
CODE
namespace reverseArray
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
long operations = 0;
int size;
int max;
int[] createArray;
int[] sortArray;
int[] copyArray;
public void ReverseOrder()
{
size = Convert.ToInt32(textBoxSize.Text);
max = Convert.ToInt32(textBoxMax.Text);
createArray = new int[size];
copyArray = new int[size];
sortArray = new int[size];
createArray[size - 1] = 1;
for (int i = size - 1; i > 0; i--)
{
createArray[i - 1] = createArray[i] + r.Next(1, max);
}
for (int i = size - 1; i > 0; i--)
{
if (r.Next(1, 101) < createArray[0])
{
for (int x = size - 1; x > 0; x--)
{
createArray[x] = r.Next(1, createArray[0]);
}
}
}
}
private void buttonCreateArray_Click(object sender, EventArgs e)
{
ReverseOrder();
}
}
}
No need to implement your own algorithm to sort or reverse an array.
Use Array.Sort and/or Array.Reverse.
To sort in descending order, first sort then reverse the array.
Use LINQ
using System.Linq;
namespace reverseArray
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
long operations = 0;
int size;
int max;
int[] createArray;
int[] orderedArray;
int[] orderedByDescendingArray;
public int[] CreateArray(int size, int max)
{
var result = new int[size];
Random r = new Random();
for(int i; i<size; i++)
{
result[i] = r.Next(max);
}
return result;
}
private void buttonCreateArray_Click(object sender, EventArgs e)
{
size = Convert.ToInt32(textBoxSize.Text);
max = Convert.ToInt32(textBoxMax.Text);
createArray = CreateArray(size, max);
orderedArray = array.OrderBy(a => a);
orderedByDescendingArray = array.OrderByDescending(a => a);
}
}
}
//P.S. Code may contain errors coz I typed it directly here.
Consder using built methods for sorting like Array.Sort and Enumerable.OrderBy. They have variants that take comaprer to customize sorting.
no need to use logic to create reverse order array. In C# has default method to reverse it. so used that and you can get output ..
string fullOrder= Console.ReadLine();
char[] charArray= fullOrder.ToCharArray();
Array.Reverse(charArray);
Console.WriteLine(charArray);
Console.ReadLine();

How to load elements into array using for loop? C#

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);
}
}

Categories

Resources