Random Usage

sometimes, we hope to generate some random infor to manipulate our data structor. we can use random class to achieve this goal.

the refer link in MSDN,Random

example source

using System;
using System.Text;
using System.Windows.Media; namespace MVVM_Template_Project.Auxiliary.Helpers
{
/// <summary>
/// This class should provide you with plenty of random method to get random things.
/// Benefit: no need to create a `Random rand = new Randow();` everywhere in your code.
/// </summary>
public static class Random_Helper
{
private static readonly Random RandomSeed = new Random(); /// <summary>
/// Generates a random string with the given length
/// </summary>
/// <param name="size">Size of the string</param>
/// <param name="lowerCase">If true, generate lowercase string</param>
/// <returns>Random string</returns>
public static string RandomString(int size, bool lowerCase)
{
// StringBuilder is faster than using strings (+=)
var randStr = new StringBuilder(size); // Ascii start position (65 = A / 97 = a)
var start = (lowerCase) ? 97 : 65; // Add random chars
for (var i = 0; i < size; i++)
randStr.Append((char) (26*RandomSeed.NextDouble() + start)); return randStr.ToString();
} /// <summary>
/// Number between min (inclusive) and max (exclusive)
/// </summary>
/// <param name="min">Inclusive</param>
/// <param name="max">Exclusive</param>
/// <returns></returns>
public static int RandomInt(int min, int max)
{
return RandomSeed.Next(min, max);
} /// <summary>
/// Double between 0 (inclusive) and 1 (exclusive)
/// </summary>
public static double RandomDouble()
{
return RandomSeed.NextDouble();
} /// <summary>
/// Return a random number between min (inc) and max (exc), with 'digits'
/// numbers after the decimal point.
/// </summary>
/// <param name="min">Lowest number (inclusive)</param>
/// <param name="max">Highest number (exclusive)</param>
/// <param name="digits">Precision after decimal point</param>
public static double RandomNumber(int min, int max, int digits)
{
var range = max-min;
var str_format = "{0:F"+digits+"}";
// To avoid having to get an int and then add a random double ...
var rand_dou = Double.Parse(string.Format(str_format, min + range * RandomSeed.NextDouble())); // If for some random reason the rounding of the double is equal to max, we just call
// the method again and return the value.
// This can *theoretically* get into an infinite loop if it happens every time, but
// this scenario is highly unlikely :0
return (rand_dou<max) ? rand_dou : RandomNumber(min,max, digits) ; /*
* Another option will be:
* return Math.Round(RandomSeed.Next(min, max - 1) + RandomSeed.NextDouble(), digits);
*/
} /// <summary>
/// Random true/false.
/// </summary>
public static bool RandomBool()
{
return (RandomSeed.NextDouble() > 0.5);
} /// <summary>
/// Random phone nmuber. Starts with 1234 and has extra 6 random digts.
/// </summary>
public static string RandomPhone()
{
string mold = "1234-{0}-{1}";
return string.Format(mold, RandomInt(0, 1000).ToString().PadLeft(3, '0'), RandomInt(0, 1000).ToString().PadLeft(3, '0'));
} /// <summary>
/// Will return a random date between 1/1/1900 and Now.
/// </summary>
public static DateTime RandomDate()
{
return RandomDate(new DateTime(1900, 1, 1), DateTime.Now);
} /// <summary>
/// Will return a random date between given dates.
/// </summary>
/// <param name="from">lower bound date</param>
/// <param name="to">higher bound date</param>
/// <returns></returns>
public static DateTime RandomDate(DateTime from, DateTime to)
{
var range = new TimeSpan(to.Ticks - from.Ticks);
return from + new TimeSpan((long) (range.Ticks*RandomSeed.NextDouble()));
} /// <summary>
/// Random color (RGB)
/// </summary>
public static Color RandomColor()
{
return Color.FromRgb((byte) RandomSeed.Next(255), (byte) RandomSeed.Next(255), (byte) RandomSeed.Next(255));
} /// <summary>
/// Random weather. Note that valid values are 0-5 (inclusive), and so the
/// default might happen.
/// </summary>
/// <returns></returns>
public static string RandomWeather()
{
int rand = RandomInt(0, 6);
string weather;
switch (rand)
{
case 0:
weather = "Gloomy day";
break;
case 1:
weather = "Rainy day";
break;
case 2:
weather = "Foggy day";
break;
case 3:
weather = "Sunny day";
break;
case 4:
weather = "Rainy with a chance of meatballs";
break;
default:
weather = "I'm stuck in my cubicle coding. No weather for you! Come back, 1 YEAR!";
break;
}
return weather;
} #region Random names private static readonly string[] ListOfMaleFirstNames =
{
"Verna", "Almeta",
"Melvina", "Digna", "Dortha", "Ione", "Sonya", "Shiela", "Shonna",
"Tania", "Susanne", "Ellie", "Felice", "Caitlyn", "Bethel", "Kamilah",
"Camila", "Stefanie", "Daysi", "Brittaney", "Lavonda", "Janice",
"Tiny", "Peg", "Kaila", "Janay", "Inga", "Melissa", "Delila", "Patience",
"Delma", "Ressie", "Nenita", "Casimira", "Theda", "Ethel", "Christinia",
"Nyla", "Letha", "Lea", "Cindy", "Nancy", "Jazmine", "Vanita", "Larhonda",
"Tai", "Charise", "Latoria", "Shanti", "Kyla"
};
private static readonly int MaleFirstNamesCount = ListOfMaleFirstNames.Length; private static readonly string[] ListOfFemaleFirstNames =
{
"Verna", "Almeta",
"Melvina", "Digna", "Dortha", "Ione", "Sonya", "Shiela", "Shonna",
"Tania", "Susanne", "Ellie", "Felice", "Caitlyn", "Bethel", "Kamilah",
"Camila", "Stefanie", "Daysi", "Brittaney", "Lavonda", "Janice",
"Tiny", "Peg", "Kaila", "Janay", "Inga", "Melissa", "Delila", "Patience",
"Delma", "Ressie", "Nenita", "Casimira", "Theda", "Ethel", "Christinia",
"Nyla", "Letha", "Lea", "Cindy", "Nancy", "Jazmine", "Vanita", "Larhonda",
"Tai", "Charise", "Latoria", "Shanti", "Kyla"
};
private static readonly int FemaleFirstNamesCount = ListOfFemaleFirstNames.Length; private static readonly string[] ListOfLastNames =
{
"Smith", "Jones", "Williams", "Brown", "Wilson", "Taylor", "Morton", "White",
"Martin", "Anderson", "Thompson", "Nguyen", "Thomas", "Walker", "Harris",
"Lee", "Ryan", "Robinson", "Kelly", "King", "González", "Rodríguez",
"Hernández", "Pérez", "García", "Martín", "Santana", "Díaz", "Suárez",
"Sánchez", "Smith", "Brown", "Lee", "Wilson", "Martin", "Patel", "Taylor",
"Wong", "Campbell", "Williams", "Kim", "Lee", "Park", "Choi", "Jeong",
"Kang", "Cho", "Yoon", "Jang", "Lim"
};
private static readonly int LastNamesCount = ListOfLastNames.Length; #endregion
/// <summary>
/// Return a random name. Might be male/female and with a diverse last name range.
/// </summary>
/// <param name="aMale">If true will return male name</param>
/// <param name="aFemale">If true will return female name</param>
/// <returns>If both param are true or null, random name. Otherwise, male or female
/// name depending on the param that is true</returns>
public static string RandomName(bool? aMale=null, bool? aFemale=null)
{
string first;
// Not specified, select at random
if ((aMale == null && aFemale == null) ||
(aMale == true && aFemale == true))
{
var gender = RandomBool();
first = (gender) ? ListOfMaleFirstNames[RandomInt(0, MaleFirstNamesCount)]
: ListOfFemaleFirstNames[RandomInt(0, FemaleFirstNamesCount)];
}
else if (aMale == true)
first = ListOfMaleFirstNames[RandomInt(0, MaleFirstNamesCount)];
else
first = ListOfFemaleFirstNames[RandomInt(0, FemaleFirstNamesCount)]; string last = ListOfLastNames[RandomInt(0, LastNamesCount)];
return string.Format("{0} {1}", first, last);
} }
}

c# Random Class usage的更多相关文章

  1. UUID(uuid)js 生成

    全局唯一标识符(GUID,Globally Unique Identifier)也称作 UUID(Universally Unique IDentifier) . GUID是一种由算法生成的二进制长度 ...

  2. javascript 生成UUID

    代码一: /*! Math.uuid.js (v1.4) http://www.broofa.com mailto:robert@broofa.com Copyright (c) 2010 Rober ...

  3. 【OpenCV】漫水填充

    漫水填充:也就是用一定颜色填充联通区域,通过设置可连通像素的上下限以及连通方式来达到不同的填充效果;漫水填充经常被用来标记或分离图像的一部分以便对其进行进一步处理或分析,也可以用来从输入图像获取掩码区 ...

  4. 简单了解uuid

    1.含义 UUID-Universally Unique IDentifiers,翻译过来就是“全局唯一标志符”. UUID到底是什么? UUID是一个标帜你系统中的存储设备的字符串,其目的是帮助使用 ...

  5. Shell脚本实现乱序排列文件内容的多种方法(洗牌问题)

    洗牌问题:洗一副扑克,有什么好办法?既能洗得均匀,又能洗得快?即相对于一个文件来说怎样高效率的实现乱序排列? ChinaUnix 确实是 Shell 高手云集的地方,只要你想得到的问题,到那里基本上都 ...

  6. (转)Image Segmentation with Tensorflow using CNNs and Conditional Random Fields

    Daniil's blog Machine Learning and Computer Vision artisan. About/ Blog/ Image Segmentation with Ten ...

  7. python的random模块

    As an example of subclassing, the random module provides the WichmannHill class that implements an a ...

  8. USB HID usage table

    This usage table lets usbhidctl decode the HID data correctly for the APC RS/XS1000's. This work was ...

  9. Prefer ThreadLocalRandom over Random

    Java 7 has introduced a new random number generator - ThreadLocalRandom Normally to generate Random ...

随机推荐

  1. Linux下的”锁“事儿

    原由 之所以写这篇文章当然还是在面试中涉及了对本文标题的相关问题-互斥锁和自旋锁的区别.听到这个问题的时候,我是比较忐忑的.互斥锁我还能简单说一些,但是对于自旋锁的了解几乎为零.为此,将总结Linux ...

  2. Loadrunner:error -86401 Failed to connceted xxx.xxx.xxx.xxx:25问题解决

    [转自:http://www.51testing.com/html/00/130600-3578408.html]windows 2003上安装的LoadRunner11做为负载机在SMTP协议压测时 ...

  3. 在Apache下发布ASP.NET程序

    为什么要在apache下发布ASP.NET,看这篇文章您一定有自己的原因. 我是因为XP系统里面同时装IIS 和 AppServer会有问题. 步骤: 1.环境搭建,这个不废话,我安装的是.NET2. ...

  4. MBR解析

    先推广一下QQ群:61618925.欢迎各位爱好编程的朋友加入. 一.程序界面 二.关键部分代码: 1.数据结构定义 #define MBRSIZE 512 #define BOOTRECORDSIZ ...

  5. iOS播放动态GIF图片

    <转> 图片分为静态和动态两种,图片的格式有很多种,在开发中比较常见的是.png和.jpg的静态图片,但有的时候在App中需要播放动态图片,比如.gif格式的小表情头像,在IOS中并没有提 ...

  6. 必须会的SQL语句(六)查询

    1.基础的查询     1)重命名列     select name as '姓名' from 表名       2)定义常量列     select 是否 ='是' from 表名       3) ...

  7. 移植u-boot.2012.04.01

    /*************************************************** *u-boot版本:u-boot2012.04.01 *gcc版本:arm-linux-gcc ...

  8. input 文本框和 img 验证码对齐问题

    input 文本框和 img 验证码对齐问题 在网页制作中,常将 input 和 img 放在同一行,img标签总是比input高出一个头,非常难看. CCS实现input和img水平对齐的方法 同时 ...

  9. JS正则表达式使用方法及示例

    1.定义正则表达式: a.普通方式:var reg=/表达式/附加参数 附件参数: g:代表可以进行全局匹配.i:代表不区分大小写匹配.m:代表可以进行多行匹配. 上面三个参数,可以任意组合,代表复合 ...

  10. php时间转换unix时间戳

    本文介绍了php编程中unix时间戳转换的小例子,有关php时间转换.php时间戳的实例代码,有需要的朋友参考下. 第一部分,php 时间转换unix 时间戳实现代码. 复制代码代码示例: <? ...