-
Notifications
You must be signed in to change notification settings - Fork 1.4k
/
Copy pathPrimesList.cs
236 lines (202 loc) · 7.11 KB
/
PrimesList.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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
using System;
using System.Linq;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Text;
namespace DataStructures.Common
{
/// <summary>
/// Provides a list of the first 10,000 primes.
/// This class is a singleton, and read the primes from the file @"Data\PrimesList_10K.csv".
/// </summary>
public sealed class PrimesList
{
//
// Singleton implementation with an attempted thread-safety using double-check locking
// internal datastorage singleton container
private static PrimesList _instance;
// lock for thread-safety laziness
private static readonly object Mutex = new object();
//
// INSTANCE VARIABLES
private readonly static List<int> _primes = new List<int>();
// Picked the HashPrime to be (101) because it is prime, and if the ‘hashSize - 1’ is not a multiple of this HashPrime, which is
// enforced in _getUpperBoundPrime, then expand function has the potential of being every value from 1 to hashSize - 1.
// The choice is largely arbitrary.
public const int HASH_PRIME = 101;
/// <summary>
/// Empty private constructor.
/// </summary>
private PrimesList() { }
/// <summary>
/// Returns the singleton instance of this class.
/// </summary>
public static PrimesList Instance
{
get
{
if (_instance == null)
{
lock (Mutex)
{
if (_instance == null)
{
_initializeData();
_instance = new PrimesList();
}
}
}
return _instance;
}
}
/// <summary>
/// Initializes the primes document path and list.
/// </summary>
private static void _initializeData()
{
string[] lines = _readResource("DataStructures.Data.PrimesDocument_10K.csv");
foreach (var line in lines)
{
// Split the line by commas and convert the collection to a list.
var numbersAsStrings = line.Split(',').ToList<string>();
// defensive check against empty strings.
numbersAsStrings.RemoveAll(item => string.IsNullOrEmpty(item) == true);
if (numbersAsStrings.Count > 0)
{
try
{
// cast them into integers and add them to the primes list
var numbers = numbersAsStrings.Select(item => Convert.ToInt32(item)).ToList<int>();
_primes.AddRange(numbers);
}
catch (Exception e)
{
throw new Exception(line.Replace("\r","{\\r}").Replace("\n", "{\\n}"), e);
}
}
}
}
/// <summary>
/// Return count of primes.
/// </summary>
public int Count
{
get { return _primes.Count; }
}
/// <summary>
/// Returns prime number at the specified index.
/// </summary>
public int this[int index]
{
get
{
if (index < 0 || index >= _primes.Count)
throw new ArgumentOutOfRangeException();
return _primes[index];
}
}
/// <summary>
/// Checks if a number is a Prime Number.
/// </summary>
public bool IsPrime(int candidate)
{
if ((candidate & 1) != 0)
{
int limit = (int)Math.Sqrt(candidate);
for (int divisor = 3; divisor <= limit; divisor += 2)
{
if ((candidate % divisor) == 0)
return false;
}
return true;
}
return (candidate == 2);
}
/// <summary>
/// Returns the next biggest prime number.
/// </summary>
/// <param name="number"></param>
/// <returns></returns>
public int GetNextPrime(int number)
{
if (number < 0)
throw new ArgumentException("Number should be greater than or equal to 0.");
for (int i = 0; i < _primes.Count; i++)
{
if (_primes[i] >= number)
return _primes[i];
}
// Outside of our predefined table. Compute the prime the hard way.
for (int i = (number | 1); i < Int32.MaxValue; i += 2)
{
if (IsPrime(i) && ((i - 1) % HASH_PRIME != 0))
return i;
}
return number;
}
/// <summary>
/// Returns the next minimum prime number.
/// </summary>
public int GetPreviousPrime(int number)
{
if (number < 0)
throw new ArgumentException("Number should be greater than or equal to 0.");
for (int i = 0; i < _primes.Count; i++)
{
if (_primes[i] >= number)
return _primes[i];
}
// Outside of our predefined table. Compute the prime the hard way.
for (int i = (number | 1); i < Int32.MaxValue; i += 2)
{
if (IsPrime(i) && ((i - 1) % HASH_PRIME != 0))
return i;
}
return number;
}
/// <summary>
/// Returns the list of primes
/// </summary>
public List<int> GetAll
{
get { return _primes; }
}
/// <summary>
/// Copy the primes list to an array, starting from a specified index.
/// </summary>
public void CopyTo(int[] array, int index = 0)
{
if (array == null)
array = new int[_primes.Count];
if (array.Length <= index)
throw new ArgumentOutOfRangeException();
int count = array.Length - index;
int arrayIndex = index;
if (count - _primes.Count > 0)
count = _primes.Count;
for (int i = 0; i < count; i++)
{
array[arrayIndex] = _primes[i];
arrayIndex++;
}
}
/// <summary>
/// Reads an embedded resource as a text file.
/// </summary>
/// <returns></returns>
private static string[] _readResource(string resourceName)
{
try
{
using (var stream = typeof(PrimesList).GetTypeInfo().Assembly.GetManifestResourceStream(resourceName))
using (var reader = new StreamReader(stream ?? throw new InvalidOperationException("Failed to read resource"), Encoding.UTF8))
return reader.ReadToEnd().Split('\n');
}
catch (Exception ex)
{
throw new Exception($"Failed to read resource {resourceName}", ex);
}
}
}
}