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();
Related
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 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}");
}
}
}
}
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());
}
}
}
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);
}
}
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);
}