-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathIdGenerator.cs
59 lines (51 loc) · 1.41 KB
/
IdGenerator.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
using System;
using System.Collections.Generic;
namespace StarVoteServer
{
public class IdGenerator
{
public static string NextVoterId(IList<string> existing = null)
{
var idGenerator = new IdGenerator();
if (existing != null)
{
idGenerator.Preload(existing);
}
return idGenerator.NextId();
}
private const int IdLength = 6;
private const string _alphabet = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789"; // excludes I O 0 1
private Random _rand = new Random();
private HashSet<string> _generated = new HashSet<string>();
public void Preload(IList<string> idValues)
{
foreach (var value in idValues)
{
_generated.Add(value);
}
}
public string NextId()
{
string id;
do
{
id = NextWord();
} while (_generated.Contains(id));
return id;
}
private string NextWord()
{
string word = "";
while (word.Length < IdLength)
{
word += NextLetter();
}
return word;
}
private string NextLetter()
{
var index = _rand.Next(0, _alphabet.Length);
return _alphabet.Substring(index, 1);
}
}
}