C#按照相應(yīng)邏輯生成指定位數(shù)的隨機數(shù)
當(dāng)前位置:點晴教程→知識管理交流
→『 技術(shù)文檔交流 』
1
//生成23位的隨機數(shù) public class RandomHash 2 { 3 public static System.Collections.Generic.Dictionary<string, HashSet<string>> Hashtable = new Dictionary<string, HashSet<string>>(); 4 5 /// <summary> 6 /// Check digit(模10) 7 /// </summary> 8 /// <param name="num"></param> 9 /// <returns></returns> 10 public static string Genchecknum(string num) 11 { 12 string result = string.Empty; 13 try 14 { 15 if (num.Length == 22) 16 { 17 int sum = 0; 18 for (int i = 0; i < 22; i++) 19 { 20 int dit = 0; 21 //is Odd 22 if (Convert.ToBoolean(i % 2)) 23 { 24 dit = int.Parse(num.Substring(i, 1)) * 2; 25 if (dit > 9) 26 dit = dit - 9; 27 } 28 else 29 { 30 dit = int.Parse(num.Substring(i, 1)); 31 } 32 sum = sum + dit; 33 } 34 double doublesum = Math.Ceiling(Convert.ToDouble(sum) / 10) * 10; 35 result = (doublesum - sum).ToString(); 36 } 37 } 38 catch 39 { 40 } 41 return result; 42 } 43 44 public static string GenRandom(string acct, string country, string type, string tranName) 45 { 46 string refnum = string.Empty; 47 Random random = new Random(); 48 DateTime dt = DateTime.Now; 49 string acctnum = string.Empty; 50 string prefix = string.Empty; 51 string fieldType = string.Empty; 52 string binNum = string.Empty; 53 try 54 { 55 prefix = "7"; 56 acctnum = binNum == null ? acct.Substring(0, 6) : binNum; 57 } 58 catch (Exception ex) 59 { 60 throw ex; 61 } 62 string ID = dt.ToString("yyyyMMddHHmmss"); 63 { 64 if (Hashtable.ContainsKey(ID)) 65 { 66 bool isnotunique = true; 67 int runnum = 0; 68 do 69 { 70 string ran = random.Next(99999).ToString("00000"); 71 //refNum 由站位數(shù)字prefix + acct賬號的前6位 + 年份的最后一位數(shù)字 + 當(dāng)天是當(dāng)年的第多少天 + 當(dāng)前的HHmmss + 五位的隨機數(shù), 以及 校驗生成的一位數(shù)字 72 refnum = prefix + acctnum + dt.Year.ToString().Substring(3, 1) + dt.DayOfYear.ToString("000") + dt.ToString("HHmmss") + ran; 73 74 string checknum = Genchecknum(refnum); 75 refnum = refnum + checknum; 76 //插入非重的Refnum到Hashtable中去,確保同一秒種生成的RefNum不出現(xiàn)重復(fù) 77 if (!Hashtable[ID].Contains(refnum)) 78 { 79 isnotunique = false; 80 Hashtable[ID].Add(refnum); 81 } 82 //循環(huán)再獲取新的Refnum 83 runnum++; 84 if (runnum > 50000) 85 { 86 dt = DateTime.Now; 87 ID = dt.ToString("yyyyMMddHHmmss"); 88 } 89 } while (isnotunique); 90 91 } 92 else 93 { 94 Hashtable.Clear(); 95 string ran = random.Next(99999).ToString("00000"); 96 refnum = prefix + acctnum + dt.Year.ToString().Substring(3, 1) + dt.DayOfYear.ToString("000") + dt.ToString("HHmmss") + ran; 97 98 string checknum = Genchecknum(refnum); 99 refnum = refnum + checknum; 100 HashSet<string> hs = new HashSet<string>(); 101 hs.Add(refnum); 102 Hashtable.Add(ID, hs); 103 } 104 } 105 return refnum; 106 } 107 } 該文章在 2021/1/29 17:43:14 編輯過 |
關(guān)鍵字查詢
相關(guān)文章
正在查詢... |