-
Notifications
You must be signed in to change notification settings - Fork 0
/
randomList.cs
77 lines (69 loc) · 2.25 KB
/
randomList.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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
/*
* Based on "Fisher–Yates shuffle" algorithm https://en.wikipedia.org/wiki/Fisher–Yates_shuffle
* */
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace RandomListApplication
{
class RandomList
{
private Int32 i, rand;
private List<String> randList;
private String sel;
public String getRand()
{
var size = this.size();
Int32 min = this.i;
Int32 max = size;
if (min<max)
{
Random rObj = new Random();
this.rand = rObj.Next(min, max);
this.sel = this.randList[this.rand];
this.randList[this.rand] = this.randList[this.i];//shuffling value with "random key" & "current iterated key" within the range of pending iterations
this.randList[this.i] = this.sel;//shuffling value with "current iterated key" & "random key" within the range of pending iterations
this.i++;
}
else
{
this.reset();//Reset again. As, the reservoir is empty
this.sel = this.getRand();
}
return this.sel;
}
public void reset()
{
this.i = 0;
this.rand = 0;
this.sel = "";
}
public Int32 size()
{
return this.randList.Count;
}
public RandomList(List<String> randList)
{
this.randList = randList.ToList();//Copying instead of reference.
}
}
class ExecuteRandomList
{
static void Main(string[] args)
{
List<String> randList = new List<String>();
randList.Add("a");
randList.Add("b");
randList.Add("c");
RandomList randomList = new RandomList(randList);
//Console.WriteLine(string.Join(",", randList));
Console.WriteLine("Random 1: "+randomList.getRand());
Console.WriteLine("Random 2: " + randomList.getRand());
Console.WriteLine("Random 3: " + randomList.getRand());
Console.WriteLine("Random 4: " + randomList.getRand());
Console.ReadKey();
}
}
}