-
Notifications
You must be signed in to change notification settings - Fork 905
/
Copy pathCombinatorics.cs
490 lines (432 loc) · 21.9 KB
/
Combinatorics.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
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
// <copyright file="Combinatorics.cs" company="Math.NET">
// Math.NET Numerics, part of the Math.NET Project
// http://numerics.mathdotnet.com
// http://github.com/mathnet/mathnet-numerics
//
// Copyright (c) 2009-2015 Math.NET
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
// </copyright>
using System;
using System.Collections.Generic;
using System.Linq;
using MathNet.Numerics.Properties;
using MathNet.Numerics.Random;
namespace MathNet.Numerics
{
/// <summary>
/// Enumerative Combinatorics and Counting.
/// </summary>
public static class Combinatorics
{
/// <summary>
/// Count the number of possible variations without repetition.
/// The order matters and each object can be chosen only once.
/// </summary>
/// <param name="n">Number of elements in the set.</param>
/// <param name="k">Number of elements to choose from the set. Each element is chosen at most once.</param>
/// <returns>Maximum number of distinct variations.</returns>
public static double Variations(int n, int k)
{
if (k < 0 || n < 0 || k > n)
{
return 0;
}
return Math.Floor(
0.5 + Math.Exp(
SpecialFunctions.FactorialLn(n)
- SpecialFunctions.FactorialLn(n - k)));
}
/// <summary>
/// Count the number of possible variations with repetition.
/// The order matters and each object can be chosen more than once.
/// </summary>
/// <param name="n">Number of elements in the set.</param>
/// <param name="k">Number of elements to choose from the set. Each element is chosen 0, 1 or multiple times.</param>
/// <returns>Maximum number of distinct variations with repetition.</returns>
public static double VariationsWithRepetition(int n, int k)
{
if (k < 0 || n < 0)
{
return 0;
}
return Math.Pow(n, k);
}
/// <summary>
/// Count the number of possible combinations without repetition.
/// The order does not matter and each object can be chosen only once.
/// </summary>
/// <param name="n">Number of elements in the set.</param>
/// <param name="k">Number of elements to choose from the set. Each element is chosen at most once.</param>
/// <returns>Maximum number of combinations.</returns>
public static double Combinations(int n, int k)
{
return SpecialFunctions.Binomial(n, k);
}
/// <summary>
/// Count the number of possible combinations with repetition.
/// The order does not matter and an object can be chosen more than once.
/// </summary>
/// <param name="n">Number of elements in the set.</param>
/// <param name="k">Number of elements to choose from the set. Each element is chosen 0, 1 or multiple times.</param>
/// <returns>Maximum number of combinations with repetition.</returns>
public static double CombinationsWithRepetition(int n, int k)
{
if (k < 0 || n < 0 || (n == 0 && k > 0))
{
return 0;
}
if (n == 0 && k == 0)
{
return 1;
}
return Math.Floor(
0.5 + Math.Exp(
SpecialFunctions.FactorialLn(n + k - 1)
- SpecialFunctions.FactorialLn(k)
- SpecialFunctions.FactorialLn(n - 1)));
}
/// <summary>
/// Count the number of possible permutations (without repetition).
/// </summary>
/// <param name="n">Number of (distinguishable) elements in the set.</param>
/// <returns>Maximum number of permutations without repetition.</returns>
public static double Permutations(int n)
{
return SpecialFunctions.Factorial(n);
}
/// <summary>
/// Generate a random permutation, without repetition, by generating the index numbers 0 to N-1 and shuffle them randomly.
/// Implemented using Fisher-Yates Shuffling.
/// </summary>
/// <returns>An array of length <c>N</c> that contains (in any order) the integers of the interval <c>[0, N)</c>.</returns>
/// <param name="n">Number of (distinguishable) elements in the set.</param>
/// <param name="randomSource">The random number generator to use. Optional; the default random source will be used if null.</param>
public static int[] GeneratePermutation(int n, System.Random randomSource = null)
{
if (n < 0) throw new ArgumentOutOfRangeException(nameof(n), Resources.ArgumentNotNegative);
int[] indices = new int[n];
for (int i = 0; i < indices.Length; i++)
{
indices[i] = i;
}
SelectPermutationInplace(indices, randomSource);
return indices;
}
/// <summary>
/// Select a random permutation, without repetition, from a data array by reordering the provided array in-place.
/// Implemented using Fisher-Yates Shuffling. The provided data array will be modified.
/// </summary>
/// <param name="data">The data array to be reordered. The array will be modified by this routine.</param>
/// <param name="randomSource">The random number generator to use. Optional; the default random source will be used if null.</param>
public static void SelectPermutationInplace<T>(T[] data, System.Random randomSource = null)
{
var random = randomSource ?? SystemRandomSource.Default;
// Fisher-Yates Shuffling
for (int i = data.Length - 1; i > 0; i--)
{
int swapIndex = random.Next(i + 1);
T swap = data[i];
data[i] = data[swapIndex];
data[swapIndex] = swap;
}
}
/// <summary>
/// Select a random permutation from a data sequence by returning the provided data in random order.
/// Implemented using Fisher-Yates Shuffling.
/// </summary>
/// <param name="data">The data elements to be reordered.</param>
/// <param name="randomSource">The random number generator to use. Optional; the default random source will be used if null.</param>
public static IEnumerable<T> SelectPermutation<T>(this IEnumerable<T> data, System.Random randomSource = null)
{
var random = randomSource ?? SystemRandomSource.Default;
T[] array = data.ToArray();
// Fisher-Yates Shuffling
for (int i = array.Length - 1; i >= 0; i--)
{
int k = random.Next(i + 1);
yield return array[k];
array[k] = array[i];
}
}
/// <summary>
/// Generate a random combination, without repetition, by randomly selecting some of N elements.
/// </summary>
/// <param name="n">Number of elements in the set.</param>
/// <param name="randomSource">The random number generator to use. Optional; the default random source will be used if null.</param>
/// <returns>Boolean mask array of length <c>N</c>, for each item true if it is selected.</returns>
public static bool[] GenerateCombination(int n, System.Random randomSource = null)
{
if (n < 0) throw new ArgumentOutOfRangeException(nameof(n), Resources.ArgumentNotNegative);
var random = randomSource ?? SystemRandomSource.Default;
bool[] mask = new bool[n];
for (int i = 0; i < mask.Length; i++)
{
mask[i] = random.NextBoolean();
}
return mask;
}
/// <summary>
/// Generate a random combination, without repetition, by randomly selecting k of N elements.
/// </summary>
/// <param name="n">Number of elements in the set.</param>
/// <param name="k">Number of elements to choose from the set. Each element is chosen at most once.</param>
/// <param name="randomSource">The random number generator to use. Optional; the default random source will be used if null.</param>
/// <returns>Boolean mask array of length <c>N</c>, for each item true if it is selected.</returns>
public static bool[] GenerateCombination(int n, int k, System.Random randomSource = null)
{
if (n < 0) throw new ArgumentOutOfRangeException(nameof(n), Resources.ArgumentNotNegative);
if (k < 0) throw new ArgumentOutOfRangeException(nameof(k), Resources.ArgumentNotNegative);
if (k > n) throw new ArgumentOutOfRangeException(nameof(k), string.Format(Resources.ArgumentOutOfRangeSmallerEqual, "k", "n"));
var random = randomSource ?? SystemRandomSource.Default;
bool[] mask = new bool[n];
if (k*3 < n)
{
// just pick and try
int selectionCount = 0;
while (selectionCount < k)
{
int index = random.Next(n);
if (!mask[index])
{
mask[index] = true;
selectionCount++;
}
}
return mask;
}
// based on permutation
int[] permutation = GeneratePermutation(n, random);
for (int i = 0; i < k; i++)
{
mask[permutation[i]] = true;
}
return mask;
}
/// <summary>
/// Select a random combination, without repetition, from a data sequence by selecting k elements in original order.
/// </summary>
/// <param name="data">The data source to choose from.</param>
/// <param name="elementsToChoose">Number of elements (k) to choose from the data set. Each element is chosen at most once.</param>
/// <param name="randomSource">The random number generator to use. Optional; the default random source will be used if null.</param>
/// <returns>The chosen combination, in the original order.</returns>
public static IEnumerable<T> SelectCombination<T>(this IEnumerable<T> data, int elementsToChoose, System.Random randomSource = null)
{
T[] array = data as T[] ?? data.ToArray();
if (elementsToChoose < 0) throw new ArgumentOutOfRangeException(nameof(elementsToChoose), Resources.ArgumentNotNegative);
if (elementsToChoose > array.Length) throw new ArgumentOutOfRangeException(nameof(elementsToChoose), string.Format(Resources.ArgumentOutOfRangeSmallerEqual, "elementsToChoose", "data.Count"));
bool[] mask = GenerateCombination(array.Length, elementsToChoose, randomSource);
for (int i = 0; i < mask.Length; i++)
{
if (mask[i])
{
yield return array[i];
}
}
}
/// <summary>
/// Generates a random combination, with repetition, by randomly selecting k of N elements.
/// </summary>
/// <param name="n">Number of elements in the set.</param>
/// <param name="k">Number of elements to choose from the set. Elements can be chosen more than once.</param>
/// <param name="randomSource">The random number generator to use. Optional; the default random source will be used if null.</param>
/// <returns>Integer mask array of length <c>N</c>, for each item the number of times it was selected.</returns>
public static int[] GenerateCombinationWithRepetition(int n, int k, System.Random randomSource = null)
{
if (n < 0) throw new ArgumentOutOfRangeException(nameof(n), Resources.ArgumentNotNegative);
if (k < 0) throw new ArgumentOutOfRangeException(nameof(k), Resources.ArgumentNotNegative);
var random = randomSource ?? SystemRandomSource.Default;
int[] mask = new int[n];
for (int i = 0; i < k; i++)
{
mask[random.Next(n)]++;
}
return mask;
}
/// <summary>
/// Select a random combination, with repetition, from a data sequence by selecting k elements in original order.
/// </summary>
/// <param name="data">The data source to choose from.</param>
/// <param name="elementsToChoose">Number of elements (k) to choose from the data set. Elements can be chosen more than once.</param>
/// <param name="randomSource">The random number generator to use. Optional; the default random source will be used if null.</param>
/// <returns>The chosen combination with repetition, in the original order.</returns>
public static IEnumerable<T> SelectCombinationWithRepetition<T>(this IEnumerable<T> data, int elementsToChoose, System.Random randomSource = null)
{
if (elementsToChoose < 0) throw new ArgumentOutOfRangeException(nameof(elementsToChoose), Resources.ArgumentNotNegative);
T[] array = data as T[] ?? data.ToArray();
int[] mask = GenerateCombinationWithRepetition(array.Length, elementsToChoose, randomSource);
for (int i = 0; i < mask.Length; i++)
{
for (int j = 0; j < mask[i]; j++)
{
yield return array[i];
}
}
}
/// <summary>
/// Generate a random variation, without repetition, by randomly selecting k of n elements with order.
/// Implemented using partial Fisher-Yates Shuffling.
/// </summary>
/// <param name="n">Number of elements in the set.</param>
/// <param name="k">Number of elements to choose from the set. Each element is chosen at most once.</param>
/// <param name="randomSource">The random number generator to use. Optional; the default random source will be used if null.</param>
/// <returns>An array of length <c>K</c> that contains the indices of the selections as integers of the interval <c>[0, N)</c>.</returns>
public static int[] GenerateVariation(int n, int k, System.Random randomSource = null)
{
if (n < 0) throw new ArgumentOutOfRangeException(nameof(n), Resources.ArgumentNotNegative);
if (k < 0) throw new ArgumentOutOfRangeException(nameof(k), Resources.ArgumentNotNegative);
if (k > n) throw new ArgumentOutOfRangeException(nameof(k), string.Format(Resources.ArgumentOutOfRangeSmallerEqual, "k", "n"));
var random = randomSource ?? SystemRandomSource.Default;
int[] indices = new int[n];
for (int i = 0; i < indices.Length; i++)
{
indices[i] = i;
}
// Partial Fisher-Yates Shuffling
int[] selection = new int[k];
for (int i = 0, j = indices.Length - 1; i < selection.Length; i++, j--)
{
int swapIndex = random.Next(j + 1);
selection[i] = indices[swapIndex];
indices[swapIndex] = indices[j];
}
return selection;
}
/// <summary>
/// Select a random variation, without repetition, from a data sequence by randomly selecting k elements in random order.
/// Implemented using partial Fisher-Yates Shuffling.
/// </summary>
/// <param name="data">The data source to choose from.</param>
/// <param name="elementsToChoose">Number of elements (k) to choose from the set. Each element is chosen at most once.</param>
/// <param name="randomSource">The random number generator to use. Optional; the default random source will be used if null.</param>
/// <returns>The chosen variation, in random order.</returns>
public static IEnumerable<T> SelectVariation<T>(this IEnumerable<T> data, int elementsToChoose, System.Random randomSource = null)
{
var random = randomSource ?? SystemRandomSource.Default;
T[] array = data.ToArray();
if (elementsToChoose < 0) throw new ArgumentOutOfRangeException(nameof(elementsToChoose), Resources.ArgumentNotNegative);
if (elementsToChoose > array.Length) throw new ArgumentOutOfRangeException(nameof(elementsToChoose), string.Format(Resources.ArgumentOutOfRangeSmallerEqual, "elementsToChoose", "data.Count"));
// Partial Fisher-Yates Shuffling
for (int i = array.Length - 1; i >= array.Length - elementsToChoose; i--)
{
int swapIndex = random.Next(i + 1);
yield return array[swapIndex];
array[swapIndex] = array[i];
}
}
/// <summary>
/// Generate a random variation, with repetition, by randomly selecting k of n elements with order.
/// </summary>
/// <param name="n">Number of elements in the set.</param>
/// <param name="k">Number of elements to choose from the set. Elements can be chosen more than once.</param>
/// <param name="randomSource">The random number generator to use. Optional; the default random source will be used if null.</param>
/// <returns>An array of length <c>K</c> that contains the indices of the selections as integers of the interval <c>[0, N)</c>.</returns>
public static int[] GenerateVariationWithRepetition(int n, int k, System.Random randomSource = null)
{
if (n < 0) throw new ArgumentOutOfRangeException(nameof(n), Resources.ArgumentNotNegative);
if (k < 0) throw new ArgumentOutOfRangeException(nameof(k), Resources.ArgumentNotNegative);
var random = randomSource ?? SystemRandomSource.Default;
int[] ret = new int[k];
random.NextInt32s(ret, 0, n);
return ret;
}
/// <summary>
/// Select a random variation, with repetition, from a data sequence by randomly selecting k elements in random order.
/// </summary>
/// <param name="data">The data source to choose from.</param>
/// <param name="elementsToChoose">Number of elements (k) to choose from the data set. Elements can be chosen more than once.</param>
/// <param name="randomSource">The random number generator to use. Optional; the default random source will be used if null.</param>
/// <returns>The chosen variation with repetition, in random order.</returns>
public static IEnumerable<T> SelectVariationWithRepetition<T>(this IEnumerable<T> data, int elementsToChoose, System.Random randomSource = null)
{
if (elementsToChoose < 0) throw new ArgumentOutOfRangeException(nameof(elementsToChoose), Resources.ArgumentNotNegative);
T[] array = data as T[] ?? data.ToArray();
int[] indices = GenerateVariationWithRepetition(array.Length, elementsToChoose, randomSource);
for (int i = 0; i < indices.Length; i++)
{
yield return array[indices[i]];
}
}
/// <summary>
/// Test if two lists are equal
/// </summary>
/// <returns><c>true</c>, if equal was unordereded, <c>false</c> otherwise.</returns>
/// <param name="a">The first list to compare.</param>
/// <param name="b">The second list to compare.</param>
/// <typeparam name="T">The 1st type parameter.</typeparam>
public static bool UnorderedEqual<T>(ICollection<T> a, ICollection<T> b)
{
// Require that the counts are equal
if (a.Count != b.Count)
{
return false;
}
// Initialize new Dictionary of the type
Dictionary<T, int> d = new Dictionary<T, int>();
// Add each key's frequency from collection A to the Dictionary
foreach (T item in a)
{
int c;
if (d.TryGetValue(item, out c))
{
d[item] = c + 1;
}
else
{
d.Add(item, 1);
}
}
// Add each key's frequency from collection B to the Dictionary
// Return early if we detect a mismatch
foreach (T item in b)
{
int c;
if (d.TryGetValue(item, out c))
{
if (c == 0)
{
return false;
}
else
{
d[item] = c - 1;
}
}
else
{
// Not in dictionary
return false;
}
}
// Verify that all frequencies are zero
foreach (int v in d.Values)
{
if (v != 0)
{
return false;
}
}
// We know the collections are equal
return true;
}
}
}