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