Skip to content

Instantly share code, notes, and snippets.

@subena22jf
Last active July 8, 2021 14:11
Show Gist options
  • Save subena22jf/c7bb027ea99127944981 to your computer and use it in GitHub Desktop.
Save subena22jf/c7bb027ea99127944981 to your computer and use it in GitHub Desktop.
c# Random with long values
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace System.Maths
{
public class Random
{
public int index;
public void init()
{
System.Random rd = new System.Random();
}
public int Next(int Min, int Max)
{
System.Random rd = new System.Random();
return rd.Next(Min, Max);
}
public long Next(long min,long max)
{
System.Random rd = new System.Random();
if (max <= min)
throw new ArgumentOutOfRangeException("max", "max must be > min!");
ulong uRange = (ulong)(max - min);
ulong ulongRand;
do
{
byte[] buf = new byte[8];
rd.NextBytes(buf);
ulongRand = (ulong)BitConverter.ToInt64(buf, 0);
} while (ulongRand > ulong.MaxValue - ((ulong.MaxValue % uRange) + 1) % uRange);
return (long)(ulongRand % uRange) + min;
}
public long Next(long max)
{
return Next(0, max);
}
public int Next(int Max)
{
System.Random rd = new System.Random();
return rd.Next(Max);
}
public byte NextBytes(byte[] buffer)
{
Random rnd = new Random();
return rnd.NextBytes(buffer);
}
public double NextDouble()
{
System.Random rd = new System.Random();
return rd.NextDouble();
}
public string RandomString(int size, bool lowerCase)
{
StringBuilder builder = new StringBuilder();
System.Random random = new System.Random();
char ch;
for (int i = 0; i < size; i++)
{
ch = Convert.ToChar(Convert.ToInt32(Math.Floor(26 * random.NextDouble() + 65)));
builder.Append(ch);
}
if (lowerCase)
return builder.ToString().ToLower();
return builder.ToString();
}
public object NextArrayList(ArrayList Arrays){
System.Random rd = new System.Random();
int rand = rd.Next(0, Arrays.Count);
var value = Arrays[rand];
}
public IEnumerable<T> Randomize<T>(this IEnumerable<T> source)
{
System.Random rnd = new System.Random();
return source.OrderBy<T, int>((item) => rnd.Next());
}
}
}
@subena22jf
Copy link
Author

Update for

public string RandomString(int size, bool lowerCase)
{
StringBuilder builder = new StringBuilder();
Random random = new Random();
char ch;
for (int i = 0; i < size; i++)
{
ch = Convert.ToChar(Convert.ToInt32(Math.Floor(26 * random.NextDouble() + 65)));
builder.Append(ch);
}
if (lowerCase)
return builder.ToString().ToLower();
return builder.ToString();
}

Download dll file: http://www.mediafire.com/?txvmiowihzao4m4

@subena22jf
Copy link
Author

add Random with ArrayList

public object NextArrayList(ArrayList Arrays){
System.Random rd = new System.Random();
int rand = rd.Next(0, Arrays.Count);
var value = Arrays[rand];
}

Download dll file: http://www.mediafire.com/?txvmiowihzao4m4

@subena22jf
Copy link
Author

add Randomize

public IEnumerable Randomize(this IEnumerable source)
{
System.Random rnd = new System.Random();
return source.OrderBy<T, int>((item) => rnd.Next());
}

Download dll file: http://www.mediafire.com/?txvmiowihzao4m4

@subena22jf
Copy link
Author

Add random hex number

public string NextHex(){
System.Random random=new System.Random();
byte[] buffer = new byte[digits / 2];
random.NextBytes(buffer);
string result = String.Concat(buffer.Select(x => x.ToString("X2")).ToArray());
if (digits % 2 == 0)
return result;
return result + random.Next(16).ToString("X");
}

File lib: Updating...

@subena22jf
Copy link
Author

Hio...add random string with filter

So here we have two methods; one for Unicode and one for ASCII. My thought was that when generating a simple password for US English keyboards, I’d just use a simple ASCII generator using characters available on the keyboard. For for the rest of you folks who don’t have a US English keyboard, maybe there are some options to generate a random string with a custom range filter.

public string GetRandomUnicodeString(int length, int maxValue, Predicate valueFilter)
{
byte[] seedBuff = new byte[4];
byte[] charBuff;

RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
rng.GetBytes(seedBuff); // The array is now filled with cryptographically strong random bytes.

using (MemoryStream ms = new MemoryStream())
{
    using (StreamWriter sw = new StreamWriter(ms, new UTF8Encoding(false, false)))
    {
        var random = new System.Random(BitConverter.ToInt32(seedBuff, 0));

        for (int i = 0; i < length; i++)
        {
            int temp = random.Next(maxValue); //should we cap? 

            while (!valueFilter(temp))
                temp = random.Next(maxValue);

            sw.Write((char)temp);
        }
    }
    charBuff = ms.ToArray();
}
return new System.Text.UTF8Encoding(false, false).GetString(charBuff);

}

public string GetRandomASCIIString(int length)
{
return GetRandomUnicodeString(length, 0x7E, o => o >= 0x21 && o <= 0x7E);
//return GetRandomUnicodeString(length, 126, o => o >= 33 && o <= 126); //could use integers instead
}

when using the Unicode method, you have to specify a max value; otherwise, the random generator will choke if you want a small range of numbers when randomizing a pool of 65,535 values. So the cap will help performance. The filter expression should filter out the random results so you only get the characters you want.

The ASCII method is a pretty simple example of how this works. I want a max value of 126, and I want characters in the range of 33 through 126. I used hex (because the Windows character map uses hex).

Thanks Nathan Bridgewater for this share

@c0d3rpr0
Copy link

Hello,
This source code is helpful to me. Thanks for sharing.

John

@c0d3rpr0
Copy link

Do you have Skype name? I have some questions need to clarify.
Thank you

John

@subena22jf
Copy link
Author

hopefully help you,
Skype name is my username: subena22jf

@ifarbod
Copy link

ifarbod commented Mar 4, 2016

Very useful 👍

@bolosky
Copy link

bolosky commented Apr 17, 2020

What's the licensing on this? It's just what I need, I just want to make sure that it's OK for me to use. I'm putting in research code (not something that would ever be sold), but for a commercial company (Microsoft).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment