-
Notifications
You must be signed in to change notification settings - Fork 1
/
PermutationByte.cs
415 lines (403 loc) · 12.1 KB
/
PermutationByte.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
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using StringBuilder = System.Text.StringBuilder;
using CultureInfo = System.Globalization.CultureInfo;
using DotNetTransformer.Extensions;
using DotNetTransformer.Math.Group;
using DotNetTransformer.Math.Set;
namespace DotNetTransformer.Math.Permutation {
using P = PermutationByte;
[Serializable]
[DebuggerDisplay("{ToString()}, CycleLength = {CycleLength}")]
public struct PermutationByte : IPermutation<P>
{
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
internal readonly byte _value;
internal PermutationByte(byte value) { _value = value; }
public PermutationByte(params byte[] array) : this((IEnumerable<byte>)array) { }
public PermutationByte(IEnumerable<byte> collection) {
if(ReferenceEquals(collection, null))
throw new ArgumentNullException();
IEnumerator<byte> e = collection.GetEnumerator();
byte count = 0, digit;
_value = 0;
byte digitFlag = 0;
while(e.MoveNext()) {
if(count >= _count)
_throwArray(string.Format(
"Collection size ({2}) is out of range ({0}, {1}).",
0, _count + 1, count
));
digit = e.Current;
if(digit >= _count)
_throwArray(string.Format(
"Value \"{2}\" is out of range ({0}, {1}).",
0, _count, digit
));
if((1 << digit & digitFlag) != 0)
_throwArray(string.Format(
"Value \"{0}\" is duplicated.",
digit
));
digitFlag |= (byte)(1 << digit);
_value |= (byte)((digit ^ count) << (count << _s));
++count;
}
digit = 0;
while(((byte)(1 << digit) & digitFlag) != 0)
++digit;
if(((byte)(-1 << digit) & digitFlag) != 0)
_throwArray(string.Format(
"Value \"{0}\" is not found.",
digit
));
}
private const byte _mix = 0xE4, _mask = 3;
private const byte _s = 1, _count = 4, _len = _count << _s;
private const string _charPattern = "[0-3]";
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
public byte Value { get { return (byte)(_value ^ _mix); } }
public int this[int index] {
get {
if(index < 0 || index >= _count) return index;
return Value >> (index << _s) & _mask;
}
}
public int SwapsCount {
get {
int count = 0;
ForAllCyclesDo(_ => { }, c => { count += --c; });
return count;
}
}
public int CycleLength {
get {
int multFlag = 0;
ForAllCyclesDo(_ => { }, c => { multFlag |= 1 << --c; });
return (multFlag >> 1) + 1 - (multFlag >> 3);
}
}
public P InverseElement {
get {
byte t = Value, r = 0;
byte i = 0;
do
r |= (byte)(i << ((t >> (i << _s) & _mask) << _s));
while(++i < _count);
return new P((byte)(r ^ _mix));
}
}
public P Add(P other) {
byte t = Value, o = other.Value, r = 0;
byte i = 0;
do {
r |= (byte)((t >> ((o >> i & _mask) << _s) & _mask) << i);
i += 1 << _s;
} while(i < _len);
return new P((byte)(r ^ _mix));
}
public P Subtract(P other) {
byte t = Value, o = other.Value, r = 0;
byte i = 0;
do {
r |= (byte)((t >> i & _mask) << ((o >> i & _mask) << _s));
i += 1 << _s;
} while(i < _len);
return new P((byte)(r ^ _mix));
}
public P Times(int count) {
return FiniteGroupExtension.Times<P>(this, count);
}
public bool ReducibleTo(int length) {
return _value >> (length << _s) == 0;
}
public P Swap(int i, int j) {
if(i < 0 || i >= _count) _throwOutOfRange(i, "i");
if(j < 0 || j >= _count) _throwOutOfRange(j, "j");
return new P((byte)(_swap(i, j, Value) ^ _mix));
}
private static int _swap(int i, int j, int v) {
i <<= _s;
j <<= _s;
int c = ((v >> i) ^ (v >> j)) & _mask;
return v ^ (c << i) ^ (c << j);
}
public P GetNextPermutation(int maxLength, Order<int> match) {
if(maxLength > _count) maxLength = _count;
int v = Value, r = v;
const int shift = 1 << _s;
int n = 0, i, prev, curr = v & _mask;
do {
prev = curr;
v >>= shift;
curr = v & _mask;
} while(++n < maxLength && match(prev, curr));
v = r;
if(n < maxLength) {
for(i = 0; match(v & _mask, curr); ++i)
v >>= shift;
r = _swap(i, n, r);
}
for(i = 0; i < --n; ++i)
r = _swap(i, n, r);
return new P((byte)(r ^ _mix));
}
public P GetNextPermutation(int maxLength) {
return GetNextPermutation(maxLength, (int l, int r) => l >= r);
}
public P GetPrevPermutation(int maxLength) {
return GetNextPermutation(maxLength, (int l, int r) => l <= r);
}
public void ForAllCyclesDo(Action<byte> digitAction, Action<byte> cycleAction) {
byte t = Value;
byte digitFlag = 0;
for(byte i = 0; i < _count; ++i) {
if((1 << i & digitFlag) != 0) continue;
byte digit = i;
byte cLen = 0;
do {
digitAction(digit);
++cLen;
digitFlag |= (byte)(1 << digit);
digit = (byte)(t >> (digit << _s) & _mask);
} while((1 << digit & digitFlag) == 0);
cycleAction(cLen);
}
}
public IFiniteSet<P> GetCycles(Predicate<P> match) {
List<P> list = new List<P>(_count);
byte value = 0, t = this._value;
ForAllCyclesDo(
d => { value |= (byte)(_mask << (d << _s) & t); },
_ => {
P p = new P(value);
if(match(p)) list.Add(p);
value = 0;
}
);
return list.ToFiniteSet<P>();
}
public int GetCyclesCount(Predicate<int> match) {
int count = 0;
ForAllCyclesDo(_ => { }, c => { if(match(c)) ++count; });
return count;
}
public override int GetHashCode() {
int h = _value;
h = ((h << 4) | h) & 0x0F0F;
h = ((h << 2) | h) & 0x3333;
return h;
}
public override bool Equals(object o) {
return o is P && Equals((P)o);
}
public bool Equals(P o) { return _value == o._value; }
public int CompareTo(P o) { return o.Value - Value; }
public override string ToString() {
return _toString(_count);
}
public string ToString(int minLength) {
if(minLength > _count) minLength = _count;
byte t = Value;
byte i = _count;
if(minLength > 0) --minLength;
while(--i > minLength && (t >> (i << _s) & _mask) == i) ;
if(minLength < i) minLength = i;
return _toString(++minLength);
}
private string _toString(int length) {
StringBuilder sb = new StringBuilder(length, length);
length <<= _s;
byte t = Value;
byte i = 0;
do {
sb.Append((char)(t >> i & _mask | '0'));
i += 1 << _s;
} while(i < length);
return sb.ToString();
}
public short ToInt16() {
return (short)(GetHashCode() ^ 0x3210);
}
public IEnumerator<int> GetEnumerator() {
byte t = Value;
byte i = 0;
do {
yield return t >> i & _mask;
i += 1 << _s;
} while(i < _len);
}
IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); }
public int[] ToArray() {
byte v = Value;
int[] a = new int[_count];
byte i = 0;
do {
a[i] = v & _mask;
v >>= 1 << _s;
} while(++i < _count);
return a;
}
/// <exception cref="ArgumentException">
/// <exception cref="ArgumentNullException">
/// Invalid <paramref name="s"/>.
/// </exception>
/// </exception>
public static P FromString(string s) {
if(ReferenceEquals(s, null)) throw new ArgumentNullException();
if(s.Length > _count)
_throwString(string.Format(
"String length ({2}) is out of range ({0}, {1}).",
0, _count + 1, s.Length
));
if(s.Length < 1) return new P();
byte value = 0;
byte startIndex = 0;
for(byte digit = 0; digit < _count; ++digit) {
byte i = 0;
char c;
do {
c = s[i];
if((-_count & c) != '0')
_throwString(string.Format(
"\'{0}\' is not a digit from {1}.",
c, _charPattern
));
} while((c & _mask) != digit && ++i < s.Length);
if(i == s.Length)
if(startIndex >= digit || i > digit)
_throwString(string.Format(
"Digit \'{0}\' is not found.",
(char)(digit | '0')
));
else return new P((byte)(((1 << (digit << _s)) - 1) & _mix ^ value));
else {
value |= (byte)(digit << (i << _s));
if(startIndex < i) startIndex = i;
}
}
return new P((byte)(_mix ^ value));
}
internal static P FromByteInternal(byte value) {
return new P((byte)(value ^ _mix));
}
public static P FromByte(byte value) {
byte startIndex = 0;
for(byte digit = 0; digit < _count; ++digit) {
byte i = 0;
while(i < _count && (value >> (i << _s) & _mask) != digit) ++i;
if(i == _count)
if(startIndex >= digit || (value & (-1 << (digit << _s))) != 0)
_throwByte(string.Format(
"Digit \'{0}\' is not found.",
(char)(digit | '0')
));
else return new P((byte)(((1 << (digit << _s)) - 1) & _mix ^ value));
else if(startIndex < i) startIndex = i;
}
return new P((byte)(_mix ^ value));
}
private static P FromInt16Internal(short value) {
value = (short)(((short)(value >> 2) | value) & 0x0F0F);
value = (short)(((short)(value >> 4) | value) & 0x00FF);
return new P((byte)(value ^ _mix));
}
public static P FromInt16(short value) {
if((value & -0x3334) != 0)
_throwInt16(string.Format(
"Some digits is out of {0}.",
_charPattern
));
byte startIndex = 0;
for(byte digit = 0; digit < _count; ++digit) {
byte i = 0;
while(i < _count && (value >> (i << 2) & _mask) != digit) ++i;
if(i == _count)
if(startIndex >= digit || (value & (-1 << (digit << 2))) != 0)
_throwInt16(string.Format(
"Digit \'{0}\' is not found.",
(char)(digit | '0')
));
else return FromInt16Internal((short)((-1 << (digit << 2)) & 0x3210 ^ value));
else if(startIndex < i) startIndex = i;
}
return FromInt16Internal(value);
}
[DebuggerStepThrough]
private static void _throwString(string message) {
throw new ArgumentException(string.Concat(message,
" Use unique digits from ",
_charPattern,
". Example: \"0123\"."
));
}
[DebuggerStepThrough]
private static void _throwByte(string message) {
throw new ArgumentException(string.Concat(message,
" Use compressed data format and unique digits from ",
_charPattern,
", Example: 0xE4 or 0b_11_10_01_00."
));
}
[DebuggerStepThrough]
private static void _throwInt16(string message) {
throw new ArgumentException(string.Concat(message,
" Use hexadecimal format and unique digits from ",
_charPattern,
". Example: 0x3210."
));
}
[DebuggerStepThrough]
private static void _throwArray(string message) {
StringBuilder sb = new StringBuilder(message);
sb.AppendFormat(
" Use unique values from range ({0}, {1}).",
0, _count
);
sb.Append(" Example: {");
byte i = 0;
sb.AppendFormat(
CultureInfo.InvariantCulture,
" {0}", i
);
while(++i < _count)
sb.AppendFormat(
CultureInfo.InvariantCulture,
", {0}", i
);
sb.Append(" }.");
throw new ArgumentException(sb.ToString());
}
[DebuggerStepThrough]
private static void _throwOutOfRange(int value, string name) {
throw new ArgumentOutOfRangeException(
name, value, string.Format(
CultureInfo.InvariantCulture,
"Argument \"{0}\" is out of range ({1}, {2}).",
name, 0, _count
)
);
}
public static bool operator ==(P l, P r) { return l.Equals(r); }
public static bool operator !=(P l, P r) { return !l.Equals(r); }
public static bool operator >(P l, P r) { return l.Value < r.Value; }
public static bool operator <(P l, P r) { return l.Value > r.Value; }
public static bool operator >=(P l, P r) { return l.Value <= r.Value; }
public static bool operator <=(P l, P r) { return l.Value >= r.Value; }
public static P operator +(P o) { return o; }
public static P operator -(P o) { return o.InverseElement; }
public static P operator +(P l, P r) { return l.Add(r); }
public static P operator -(P l, P r) { return l.Subtract(r); }
public static P operator *(P l, int r) { return l.Times(r); }
public static P operator *(int l, P r) { return r.Times(l); }
public static implicit operator P(string o) { return FromString(o); }
public static implicit operator P(byte o) { return FromByte(o); }
public static implicit operator P(short o) { return FromInt16(o); }
[CLSCompliant(false)]
public static implicit operator P(sbyte o) { return FromByte((byte)o); }
[CLSCompliant(false)]
public static implicit operator P(ushort o) { return FromInt16((short)o); }
}
}