I want to generate an example of a valid input by Regex pattern. I'm programming with C# .Net . Like this:
//this emthod doesn't exists, its an example of funcionality that I want.
Regex.GenerateInputExample("^[0-9]{15}$");
So, this example gives-me a possible value, like 000000000000000. How to do this?
So, this problem would take some time to solve, since the functionality is not built in. I'll give a general way to solve it:
Using an ascii (or unicode) chart find out the character codes that correspond to the characters you are using for your regex (65 =A, 69 = D, etc)
Create a random function with those bounds. Multiple bounds would take a little more trickery (A-Z =26, 0-9 = 10, so a random number from 0- 35)
Random random = new Random();
int randomNumber = random.Next(65, 70); // this generates a random number including the bounds of 65-69)
char temp = (char)random;
Next you would take the randomly generated characters and add them together into a string.
int lowerBound = 65, upperBound =69;
int length = 6;
char temp;
int randomNumber;
string result= "";
Random rand = new Random();
for (int a = 0; a <= length; a++)
{
randomNumber = rand.Next(lowerBound, upperBound);
temp = (char)randomNumber;
result = result + temp;
} //result is the indirect regex generated string
Indirectly giving you a regex generated string.
The next step is parsing information out of a regex. I've provided a simple case below that will not work for every regex, due to regex complexity.
Regex bob = new Regex("[A-Z]");
int lowerBound = Convert.ToInt32(bob.ToString()[1]);
int upperBound = Convert.ToInt32(bob.ToString()[3]);
int length = 6; //length of the string to be generated
char temp;
int randomNumber;
string result= "";
Random rand = new Random();
for (int a = 0; a <= length; a++)
{
randomNumber = rand.Next(lowerBound, upperBound);
temp = (char)randomNumber;
result = result + temp;
}
( This process could be streamlined into class and utilized etc)
Related
I'm kinda new to array and I made a char array (with 174 things in it) but I don't know how to output it in a randomize way. I'm trying to make a secured code for my system. I wanted to output 13 char from that 174 char array into a textbox, but I don't think I get the logic. Thank you in advance! Here is the code that only outputs 1 char per button click:
Random rnd = new Random();
int randomnum = rnd.Next(0, 174);
for (int x = 0; x <= 13; x++)
{
textBox11.Text = chararray[randomnum];
}
Your code is almost there, but there are a few issues:
You need to append the new character to the end of the string as apposed to just setting the Text value directly. You can do this easily with += instead of =.
You need to pick a different random character for each iteration of the loop, so move your call to .Next inside the for.
Putting this together you'd have something like this:
Random rnd = new Random();
for (int x = 0; x <= 13; x++)
{
int randomnum = rnd.Next(0, 174);
textBox11.Text += chararray[randomnum];
}
Note however, that if this is for the purpose of security, using Random isn't great. You should probably use something like the RNGCryptoServiceProvider. For example:
using (var rng = new RNGCryptoServiceProvider())
{
byte[] password = new byte[10];
rng.GetBytes(password);
textBox11.Text = Convert.ToBase64String(password).Remove(13);
}
I've attached a screenshot of this code working. I had a small typo
This will change the seed for random
int seed = 1;
Create an instance of Random, we don't need to recreate it every time we need to use it
Random r = new Random(seed);
This only initializes the characters
char[] _myChars = new char[170];
for(var i = 0; i < _myChars.Length; i++)
{
_myChars[i] = (char)(i%26 + 65);
}
This is the query you're looking for, it will query the characters and order them by a random order with r.Next()
var output = _myChars.OrderBy(o => r.Next()).Take(13).ToList();
This is only for displaying the output, you would want to use the output in your textbox
for(var i = 0; i < output.Count; i++)
{
Console.WriteLine(output[i]);
}
Console.ReadLine();
I'm using C# and I need to generate a random 10 digit number. So far, I've only had luck finding examples indicating min maximum value. How would i go about generating a random number that is 10 digits, which can begin with 0, (initially, I was hoping for random.Next(1000000000,9999999999) but I doubt this is what I want).
My code looks like this right now:
[WebMethod]
public string GenerateNumber()
{
Random random = new Random();
return random.Next(?);
}
**Update ended up doing like so,
[WebMethod]
public string GenerateNumber()
{
Random random = new Random();
string r = "";
int i;
for (i = 1; i < 11; i++)
{
r += random.Next(0, 9).ToString();
}
return r;
}
Use this to create random digits with any specified length
public string RandomDigits(int length)
{
var random = new Random();
string s = string.Empty;
for (int i = 0; i < length; i++)
s = String.Concat(s, random.Next(10).ToString());
return s;
}
try (though not absolutely exact)
Random R = new Random();
return ((long)R.Next (0, 100000 ) * (long)R.Next (0, 100000 )).ToString ().PadLeft (10, '0');
To get the any digit number without any loop, use Random.Next with the appropriate limits [100...00, 9999...99].
private static readonly Random _rdm = new Random();
private string PinGenerator(int digits)
{
if (digits <= 1) return "";
var _min = (int)Math.Pow(10, digits - 1);
var _max = (int)Math.Pow(10, digits) - 1;
return _rdm.Next(_min, _max).ToString();
}
This function calculated the lower and the upper bounds of the nth digits number.
To generate the 10 digit number use it like this:
PinGenerator(10)
If you want ten digits but you allow beginning with a 0 then it sounds like you want to generate a string, not a long integer.
Generate a 10-character string in which each character is randomly selected from '0'..'9'.
private void button1_Click(object sender, EventArgs e)
{
Random rand = new Random();
long randnum2 = (long)(rand.NextDouble() * 9000000000) + 1000000000;
MessageBox.Show(randnum2.ToString());
}
I came up with this method because I dont want to use the Random method :
public static string generate_Digits(int length)
{
var rndDigits = new System.Text.StringBuilder().Insert(0, "0123456789", length).ToString().ToCharArray();
return string.Join("", rndDigits.OrderBy(o => Guid.NewGuid()).Take(length));
}
hope this helps.
// ten digits
public string CreateRandomNumber
{
get
{
//returns 10 digit random number (Ticks returns 16 digit unique number, substring it to 10)
return DateTime.UtcNow.Ticks.ToString().Substring(8);
}
}
(1000000000,9999999999) is not random - you're mandating that it cannot begin with a 1, so you've already cut your target base by 10%.
Random is a double, so if you want a integer, multiply it by 1,000,000,000, then drop the figures after the decimal place.
private static Random random = new Random((int)DateTime.Now.Ticks);//thanks to McAden
public long LongBetween(long maxValue, long minValue)
{
return (long)Math.Round(random.NextDouble() * (maxValue - minValue - 1)) + minValue;
}
I tried to write a fast one:
private int GetNDigitsRandomNumber(int digits)
{
var min = 1;
for (int i = 0; i < digits-1; i++)
{
min *= 10;
}
var max = min * 10;
return _rnd.Next(min, max);
}
Here is a simple solution using format string:
string r = $"{random.Next(100000):00000}{random.Next(100000):00000}";
Random 10 digit number (with possible leading zeros) is produced as union of two random 5 digit numbers. Format string "00000" means leading zeros will be appended if number is shorter than 5 digits (e.g. 1 will be formatted as "00001").
For more about the "0" custom format specifier please see the documentation.
Random random = new Random();
string randomNumber = string.Join(string.Empty, Enumerable.Range(0, 10).Select(number => random.Next(0, 9).ToString()));
To generate a random 10 digit number in C#
Random RndNum = new Random();
int RnNum = RndNum.Next(1000000000,9999999999);
I am trying to do string manipulation. Here's my C# code :
static void Main(string[] args)
{
string input;
string output;
int length;
Console.WriteLine("input = ");
input = Console.ReadLine();
length = input.Length;
if ((input != "") || (length != 0))
{
Random randem = new Random();
int i = -1; //because I do not want the first number to be replaced by the random number
char[] characters = input.ToCharArray();
while (i < length)
{
int num = randem.Next(0, 9);
char num1 = Convert.ToChar(num);
i = i + 2; //so that every next character will be replaced by random number.. :D
characters[i] = num1; //*error* here
}
output = new string(characters);
Console.WriteLine(output);
}
For example:
User input : "i_love_to_eat_fish"
Desired output : "i2l4v1_9o5e8t7f8s2"
notice that the only unchanged character in
the char[] characters is : "i l v _ o e t f s". (desired output from the program)
I've already tried using this code, but still,
keep getting error at characters[i] = num1;
Am I on the right track?
I'm guessing the error you get is IndexOutOfRangeException this is because of the i = i + 2;. The while makes sure that i is less than length, but then adding 2 could result in it being more. Just add a check that it isn't beyond the length.
i = i + 2;
if(i < length)
characters[i] = num1;
Or just change to a for loop.
Random randem = new Random();
char[] characters = input.ToCharArray();
for(int i = 1; i < length; i += 2)
{
int num = randem.Next(1, 10); // max value is exclusive
char num1 = num.ToString()[0];
characters[i] = num1;
}
output = new string(characters);
Console.WriteLine(output);
Also as Shar1er80 points out you're currently converting the digit to the char that has the same ASCII value, and not the the actual characters that represent the digit. The digits 0-9 are represented by the the values 48-57. You can change the call to Random.Next to be:
int num = randem.Next(48, 58); // The upper bound is exclusive, not inclusive
char num1 = (char)num;
Or as Shar1er80 does it
int num = randem.Next(0,10) // Assumming you want digits 0-9
char num1 = num.ToString[0];
Also note that the max value for Random.Next is exclusive, so if you want to include the possibility of using a 9 you have to use an upper bound that is 1 greater than the greatest value you want.
Whenever you reach i = 17 you add 2 to i . That makes i = 19 with length of input equal to 18 that causes out of range exception.
The error you are getting is IndexOutOfTheRangeException, which explains everthing in itself.
It means that index you are feeding to array in the loop is going beyond its length-1 (as arrays have 0-based indexing)
So when you do i+2, you need to check if i+2 is not exceeding i.length-1 at any point of time; which does in your loop.
In general just check if you are supplying indexes between 0 and Array.Length-1
its because you start at index -1, and characters doesn't contain an index of -1.
EDIT: Sorry no the corrct answer is it must be while(i < length - 2)
Change this line
char num1 = Convert.ToChar(num);
To
char num1 = num.ToString()[0];
Then... Put
characters[i] = num1;
In an if block
if (i < length)
characters[i] = num1;
I've been playing around / researching ways to randomize the order of chars in a string. I frankly just don't understand how to do it. I've searched through the C# documentation and a handful of websites. I found one particular way of randomizing the order of chars in a string but I don't understand how it works. I've also read that the Random class isn't truly random, which would explain why the results are so similar.
How exactly does the current method I'm using function (especially the OrderBy() method).
Is there a better way to do this?
Current code
string baseList = "abcdefghijklmnopqrstuvwxyz";
Random random = new Random();
string[] randLists = new string[baseList.Length];
for (int i = 0; i < baseList.Length; i++)
{
randLists[i] = new string(baseList.ToCharArray().OrderBy(s => (random.Next(2) % 2) == 0).ToArray());
Console.WriteLine(randLists[i]);
}
Console.Read();
This is my attempt at randomizing but it doesn't function at all:
*string bL = "abcdefghijklmnopqrstuvwxyz";
string[] rL = new string[bL.Length];
Random randomizer = new Random();
for (int i = 0; i < bL.Length; i++)
{
rL = new string(bL.ToCharArray().OrderBy(c => (randomizer.Next(0, 25)).ToString()));
}*
Thanks in advance for any assistance. I'll continue researching in the meantime.
Although the code that you found is short, it does not make a nicely distributed shuffle of the original string: the randomizer is likely to give you the same numbers in the process of generating a shuffle, increasing a probability that the corresponding characters would remain in the same order relative to each other as in your original string.
One solution to this problem is using Fisher–Yates shuffle. It is easy to implement (you need to stay away from common implementation errors, though).
Since string is immutable, you would need to shuffle an array of characters, and then make a string from it.
To add to the suggestion of the Fisher-Yates shuffle, here's a code sample, just ignore the test assertion, just trying to debug and make sure it's random enough.
[TestMethod]
public void RandomizeText()
{
string baseList = "abcdefghijklmnopqrstuvwxyz";
char[] result = baseList.ToCharArray();
Shuffle<char>(result);
var final = string.Join("", result);
final.Should().NotMatch(baseList);
}
public void Shuffle<T>(T[] array)
{
var random = new Random();
for (int x = 0; x < 100; x++)
{
for (int i = array.Length; i > 1; i--)
{
// Pick random element to swap.
int j = random.Next(i); // 0 <= j <= i-1
// Swap.
T tmp = array[j];
array[j] = array[i - 1];
array[i - 1] = tmp;
}
}
}
Another example...
static void Main(string[] args)
{
string baseList = "abcdefghijklmnopqrstuvwxyz";
Console.WriteLine(baseList);
string shuffled = Shuffle(baseList);
Console.WriteLine(shuffled);
Console.ReadLine();
}
static Random R = new Random();
static string Shuffle(string list)
{
int index;
List<char> chars = new List<char>(list);
StringBuilder sb = new StringBuilder();
while (chars.Count > 0)
{
index = R.Next(chars.Count);
sb.Append(chars[index]);
chars.RemoveAt(index);
}
return sb.ToString();
}
I'm looking for some succinct, modern C# code to generate a random double number between 1.41421 and 3.14159. where the number should be [0-9]{1}.[0-9]{5} format.
I'm thinking some solution that utilizes Enumerable.Range somehow may make this more succinct.
You can easily define a method that returns a random number between two values:
private static readonly Random random = new Random();
private static double RandomNumberBetween(double minValue, double maxValue)
{
var next = random.NextDouble();
return minValue + (next * (maxValue - minValue));
}
You can then call this method with your desired values:
RandomNumberBetween(1.41421, 3.14159)
Use something like this.
Random random = new Random()
int r = random.Next(141421, 314160); //+1 as end is excluded.
Double result = (Double)r / 100000.00;
Random r = new Random();
var number = r.Next(141421, 314160) / 100000M;
Also you can't force decimal number to match your pattern. E.g. if you have 1.5 number it will not match 1.50000 format. So, you should format result as string:
string formattedNumber = number.ToString("0.00000");
I used this. I hope this helps.
Random Rnd = new Random();
double RndNum = (double)(Rnd.Next(Convert.ToInt32(LatRandMin.Value), Convert.ToInt32(LatRandMax.Value)))/1000000;
Check out the following link for ready-made implementations that should help:
MathNet.Numerics, Random Numbers and Probability Distributions
The extensive distributions are especially of interest, built on top of the Random Number Generators (MersenneTwister, etc.) directly derived from System.Random, all providing handy extension methods (e.g. NextFullRangeInt32, NextFullRangeInt64, NextDecimal, etc.). You can, of course, just use the default SystemRandomSource, which is simply System.Random embellished with the extension methods.
Oh, and you can create your RNG instances as thread safe if you need it.
Very handy indeed!
here my solution, it's not pretty but it works well
Random rnd = new Random();
double num = Convert.ToDouble(rnd.Next(1, 15) + "." + rnd.Next(1, 100));
Console.WriteLine(num);
Console.ReadKey();
JMH BJHBJHHJJ const int SIZE = 1;
int nnOfTosses,
headCount = 0, tailCount = 0;
Random tossResult = new Random();
do
{
Console.Write("Enter integer number (>=2) coin tosses or 0 to Exit: ");
if (!int.TryParse(Console.ReadLine(), out nnOfTosses))
{
Console.Write("Invalid input");
}
else
{
//***//////////////////
// To assign a random number to each element
const int ROWS = 3;
double[] scores = new double[ROWS];
Random rn = new Random();
// Populate 2D array with random values
for (int row = 0; row < ROWS; row++)
{
scores[row] = rn.NextDouble();
}
//***//////////////////////////
for (int i = 0; i < nnOfTosses; i++)
{
double[] tossResult = new double[i];
tossResult[i]= tossResult.nextDouble();
}
Console.Write("Number of Coin Tosses = " + nnOfTosses);
Console.Write("Fraction of Heads = ");
Console.Write("Fraction of Tails = ");
Console.Write("Longest run is ");
}
} while (nnOfTosses != 0);
Console.ReadLine();