-
Notifications
You must be signed in to change notification settings - Fork 2
/
common.hpp
4837 lines (3993 loc) · 115 KB
/
common.hpp
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
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// common.hpp
/*===========================================================================
*
* PUBLIC DOMAIN NOTICE
* National Center for Biotechnology Information
*
* This software/database is a "United States Government Work" under the
* terms of the United States Copyright Act. It was written as part of
* the author's official duties as a United States Government employee and
* thus cannot be copyrighted. This software/database is freely available
* to the public for use. The National Library of Medicine and the U.S.
* Government have not placed any restriction on its use or reproduction.
*
* Although all reasonable efforts have been taken to ensure the accuracy
* and reliability of the software and data, the NLM and the U.S.
* Government do not and cannot warrant the performance or results that
* may be obtained by using this software or data. The NLM and the U.S.
* Government disclaim all warranties, express or implied, including
* warranties of performance, merchantability or fitness for any particular
* purpose.
*
* Please cite the author in any work or product based on this material.
*
* ===========================================================================
*
* Author: Vyacheslav Brover
*
* File Description:
* Common utilities
*
*/
#ifndef COMMON_HPP_64052 // random number
#define COMMON_HPP_64052
#ifdef _MSC_VER
#pragma warning (disable : 4061) // enumerator ... in switch of enum ... is not explicitly handled by a case label
#pragma warning (disable : 4290) // C++ exception specification ignored except to indicate a function is not __declspec(nothrow)
#pragma warning (disable : 4365) // conversion from 'type_1' to 'type_2', signed/unsigned mismatch (bool -> size_t)
#pragma warning (disable : 4503) // decorated name length exceeded, name was truncated
#pragma warning (disable : 4514) // '...': unreferenced inline function has been removed
#pragma warning (disable : 4521) // multiple copy constructors specified
#pragma warning (disable : 4522) // multiple assignment operators specified
#pragma warning (disable : 4592) // symbol will be dynamically initialized (implementation limitation)
#pragma warning (disable : 4625) // copy constructor was implicitly defined as deleted
#pragma warning (disable : 4626) // assignment operator was implicitly defined as deleted
#pragma warning (disable : 4710) // function not inlined
#pragma warning (disable : 4800) // 'const char *': forcing value to bool 'true' or 'false' (performance warning)
#pragma warning (disable : 4820) // '...' bytes padding added after data member '...'
#pragma warning (disable : 5026) // move constructor was implicitly defined as deleted
#pragma warning (disable : 5027) // move assignment operator was implicitly defined as deleted
#pragma warning (disable : 4005) // macro redefinition
#define _HAS_ITERATOR_DEBUGGING 0
#pragma warning (default : 4005)
#endif
#include <cassert>
#include <cstring>
#include <cmath>
#include <string>
#include <stdexcept>
#include <limits>
#include <array>
#include <list>
#include <vector>
#include <stack>
#include <set>
#include <map>
#include <unordered_set>
#include <unordered_map>
#include <iostream>
#include <fstream>
#include <sstream>
#include <iomanip>
#include <memory>
#include <algorithm>
#include <thread>
#ifdef _MSC_VER
#pragma warning(push)
#pragma warning(disable:4265)
#endif
#include <mutex>
#ifdef _MSC_VER
#pragma warning(pop)
#endif
using namespace std;
namespace Common_sp
{
bool initCommon ();
// Module initialization
// Invoked automaticallly
// Numeric types
typedef unsigned char uchar;
typedef unsigned int uint;
typedef unsigned long ulong;
// Numeric constants
constexpr size_t no_index = numeric_limits<size_t>::max ();
static_assert ((size_t) 0 - 1 == no_index);
constexpr double NaN = numeric_limits<double>::quiet_NaN ();
// Global variables
extern vector<string> programArgs;
extern string programName;
string getCommandLine ();
extern ostream* logPtr;
extern bool qc_on;
extern ulong seed_global;
// >= 1
// Errors
constexpr const char* error_caption ("*** ERROR ***");
[[noreturn]] void errorExit (const char* msg,
bool segmFault = false);
// Input: programArgs, programName, logptr
// Update: *logPtr
// Invokes: if segmFault then abort() else exit(1)
void errorExitStr (const string &msg);
// For debugger: should not be inline
// Invokes: beep()
[[noreturn]] void throwf (const string &s);
// For debugger: should not be inline
// Invokes: throw logic_error
#if 0
struct InputError : runtime_error // ??
{
static bool on;
// Init: false
InputError (const string &what_arg)
: runtime_error (what_arg)
{ on = true; }
};
#endif
void sleepNano (long nanoSec);
void beep ();
// Requires: !isRedirected()
// SHLVL = 1 ??
// Comparison templates
template <typename T>
inline void swapGreater (T &a, T &b)
{ if (a > b)
swap (a, b);
}
template <typename T>
inline bool maximize (T &a, T b)
{ if (a < b) { a = b; return true; } return false; }
template <typename T>
inline bool minimize (T &a, T b)
{ if (a > b) { a = b; return true; } return false; }
template <typename T>
inline T difference (T a, T b)
{ if (a > b) return a - b; return b - a; }
template <typename T /*:number*/>
inline bool between (T x, T low, T high)
{ return x >= low && x < high; }
template <typename T/*:number*/>
inline bool betweenEqual (T x, T low, T high)
{ return x >= low && x <= high; }
template <typename T>
inline bool lessPtr (const T* x,
const T* y)
{ return *x < *y; }
typedef int (*CompareInt) (const void*, const void*);
// Pointer templates
template <typename T>
inline T* var_cast (const T* t)
{ return const_cast <T*> (t); }
template <typename T>
inline T& var_cast (const T &t)
{ return const_cast <T&> (t); }
template <typename T, typename S>
inline T const_static_cast (const S* s)
{ return static_cast <T> (const_cast <S*> (s)); }
template <typename T, typename S>
inline T const_static_cast (const S &s)
{ return static_cast <T> (const_cast <S&> (s)); }
template <typename T>
inline T* checkPtr (T* t)
{ if (t)
return t;
throwf ("Dereferencing nullptr");
return nullptr;
}
// Container templates
template <typename T>
inline void sort (T &t)
{ std::sort (t. begin (), t. end ()); }
template <typename T, typename StrictlyLess>
inline void sort (T &t,
const StrictlyLess &strictlyLess)
{ std::sort (t. begin (), t. end (), strictlyLess); }
template <typename T, typename U>
bool intersects (const T &t,
const U &u)
{ if (u. empty ())
return false;
for (const auto& x : t)
if (u. find (static_cast <typename U::value_type> (x)) != u. end ())
return true;
return false;
}
template <typename T>
unordered_set<T> setIntersect (const unordered_set<T> &s1,
const unordered_set<T> &s2)
{ const unordered_set<T>* s1_ = & s1;
const unordered_set<T>* s2_ = & s2;
if (s1. size () > s2. size ())
swap (s1_, s2_);
unordered_set<T> res; res. rehash (s1_->size ());
for (const T& t : *s1_)
if (contains (*s2_, t))
res. insert (t);
return res;
}
template <typename T, typename U>
bool containsSubset (const T &t,
const U &u)
{ for (const auto& x : u)
if (t. find (static_cast <typename U::value_type> (x)) == t. end ())
return false;
return true;
}
template <typename T>
unordered_set<T> getSetMinus (const unordered_set<T> &s1,
const unordered_set<T> &s2)
{ unordered_set<T> res; res. rehash (s1. size ());
for (const T& t : s1)
if (! contains (s2, t))
res. insert (t);
return res;
}
template <typename T, typename U>
void setMinus (T &t,
const U &u)
{ for (const auto& x : u)
t. erase (x);
}
template <typename Key, typename Value, typename KeyParent>
inline bool contains (const map <Key, Value> &m,
const KeyParent& key)
{ return m. find (key) != m. end (); }
template <typename Key, typename Value, typename KeyParent>
inline bool contains (const unordered_map <Key, Value> &m,
const KeyParent& key)
{ return m. find (key) != m. end (); }
template <typename Key, typename KeyParent>
inline bool contains (const unordered_set <Key> &m,
const KeyParent& key)
{ return m. find (key) != m. end (); }
template <typename T, size_t N>
size_t indexOf (const array<T,N> &arr, const T item)
{ for (size_t i = 0; i < N; i++)
if (arr [i] == item)
return i;
return no_index;
}
template <typename T, size_t N>
inline bool contains (const array<T,N> &arr, const T item)
{ return indexOf (arr, item) != no_index; }
template <typename Key, typename Value, typename KeyParent>
bool find (const map <Key, Value> &m,
const KeyParent& key,
Value &value)
// Return: success
// Output: value, if Return
{ const auto& it = m. find (key);
if (it == m. end ())
return false;
value = it->second;
return true;
}
template <typename Key, typename Value, typename KeyParent>
bool find (const unordered_map <Key, Value> &m,
const KeyParent& key,
Value &value)
// Return: success
// Output: value, if Return
{ const auto& it = m. find (key);
if (it == m. end ())
return false;
value = it->second;
return true;
}
template <typename Key, typename Value, typename Hash, typename KeyParent>
bool find (const unordered_map <Key, Value, Hash> &m,
const KeyParent& key,
Value &value)
// Return: success
// Output: value, if Return
{ const auto& it = m. find (key);
if (it == m. end ())
return false;
value = it->second;
return true;
}
template <typename Key, typename Value, typename KeyParent>
const Value* findPtr (const map <Key, Value> &m,
const KeyParent& key)
{ const auto& it = m. find (key);
if (it == m. end ())
return nullptr;
return & it->second;
}
template <typename Key, typename Value, typename KeyParent>
const Value* findPtr (const unordered_map <Key, Value> &m,
const KeyParent& key)
{ const auto& it = m. find (key);
if (it == m. end ())
return nullptr;
return & it->second;
}
template <typename Key, typename Value, typename KeyParent>
const Value* findPtr (const map <Key, const Value* /*!nullptr*/> &m,
const KeyParent& key)
{ const Value* value;
if (find (m, key, value))
return value;
return nullptr;
}
template <typename Key, typename Value, typename KeyParent>
const Value* findPtr (const unordered_map <Key, const Value* /*!nullptr*/> &m,
const KeyParent& key)
{ const Value* value;
if (find (m, key, value))
return value;
return nullptr;
}
template <typename Key, typename Value>
const Value& findMake (map <Key, const Value* /*!nullptr*/> &m,
const Key& key)
{ if (! contains (m, key))
m [key] = new Value ();
return * m [key];
}
template <typename Key, typename Value>
const Value& findMake (unordered_map <Key, const Value* /*!nullptr*/> &m,
const Key& key)
{ if (! contains (m, key))
m [key] = new Value ();
return * m [key];
}
template <typename T, typename UnaryPredicate>
inline size_t count_if (T &t, UnaryPredicate pred)
{ return (size_t) std::count_if (t. begin (), t. end (), pred); }
template <typename To, typename From>
inline void insertAll (To &to,
const From &from)
{ to. insert (to. begin (), from. begin (), from. end ()); }
template <typename To, typename From>
inline void insertIter (To &to,
From &&from)
{ for (auto&& x : from)
to. insert (std::move (x));
}
template <typename To, typename From>
inline void insertIter (To &to,
const From &from)
{ for (const auto& x : from)
to. insert (x);
}
template <typename From, typename What>
inline void eraseIter (From &from,
const What &what)
{ for (const auto& x : what)
if (contains (from, x))
from. erase (x);
}
template <typename T /*container*/>
void save (ostream &os,
const T &container,
char sep)
{ bool first = true;
for (const auto& t : container)
{ if (! first)
os << sep;
os << t;
first = false;
}
}
// KeyValue
typedef map<string/*key*/,string/*value*/> KeyValue;
inline string find (const KeyValue& kv,
const string& key)
{ const auto& it = kv. find (key);
if (it == kv. end ())
throw runtime_error ("Key \"" + key + "\" is not found");
return it->second;
}
// hash
extern hash<string> str_hash;
extern hash<size_t> size_hash;
// PAR
constexpr size_t small_hash_class_max = 1000;
constexpr size_t large_hash_class_max = small_hash_class_max * 100;
inline size_t str2hash_class (const string &s,
bool large_hash)
{ return str_hash (s) % (large_hash
? large_hash_class_max
: small_hash_class_max
);
}
// bool
inline void toggle (bool &b)
{ b = ! b; }
inline int getSign (bool b)
{ return b ? 1 : -1; }
inline bool boolPow (bool x, bool power)
{ return power ? x : ! x; }
inline string yesNo (bool x)
{ return x ? "Y" : "N"; }
// ebool: extended bool
enum ebool {efalse = false,
etrue = true,
enull = true + 1};
inline ebool toEbool (bool b)
{ return b ? etrue : efalse; }
inline bool operator<= (ebool a, ebool b)
{ static constexpr char rank [3/*ebool*/] = {0, 2, 1};
return rank [a] <= rank [b];
}
inline void toggle (ebool &b)
{ if (b == etrue)
b = efalse;
else if (b == efalse)
b = etrue;
}
inline string ebool2txt (ebool choice,
const string &yes,
const string &no,
const string &ambig)
{ switch (choice)
{ case etrue: return yes;
case efalse: return no;
default: return ambig;
}
}
// char
inline bool isChar (long long n)
{ return between<long long> (n, -128, 128); }
inline bool isAlpha (char c)
{ return strchr ("abcdefghijklmnopqrstuvwxyz", tolower (c)); }
// isalpha() is locale-specific
inline bool isDigit (char c)
{ return strchr ("0123456789", c); }
// isdigit() is locale-specific
inline bool isLetter (char c)
{ return isAlpha (c) || isDigit (c) || c == '_'; }
inline char toUpper (char c)
{ return (char) toupper (c); }
inline char toLower (char c)
{ return (char) tolower (c); }
inline bool isUpper (char c)
{ return toUpper (c) == c; }
inline bool isLower (char c)
{ return toLower (c) == c; }
inline bool printable (char c)
{ return between (c, ' ', (char) 127); }
inline bool nonPrintable (long c)
{ return between<long> (c, '\x001', ' '); }
string nonPrintable2str (char c);
inline bool isDelimiter (char c)
{ return c != ' '
&& printable (c)
&& ! isLetter (c);
}
inline bool isSpace (char c)
{ return c > '\0' && c <= ' ' && isspace (c); }
string to_url (const string &s);
// char*
inline const char* nvl (const char* s,
const char* nullS = "-")
{ return s ? s : nullS; }
// string
extern const string noString;
#ifndef _MSC_VER
inline string getEnv (const string& name)
{ if (const char* p = getenv (name. c_str ()))
return p;
return noString;
}
#endif
inline string ifS (bool cond,
const string &s)
{ return cond ? s : noString; }
inline string nvl (const string& s,
const string& nullS = "-")
{ return s. empty () ? nullS : s; }
inline string appendS (const string &s,
const string &suffix)
{ return s. empty () ? noString : (s + suffix); }
inline string prependS (const string &s,
const string &prefix)
{ return s. empty () ? noString : (prefix + s); }
inline void add (string &to,
const string &delimiter,
const string &what)
{ if (! to. empty ())
to += delimiter;
to += what;
}
inline bool isQuoted (const string &s,
char quote = '\"')
{ return ! s. empty () && s [0] == quote && s [s. size () - 1] == quote; }
string strQuote (const string &s,
char quote = '\"');
inline string unQuote (const string &s)
{ return s. substr (1, s. size () - 2); }
bool strBlank (const string &s);
template <typename T>
string toString (const T &t)
{ ostringstream oss;
oss << t;
return oss. str ();
}
template <typename T>
T str2 (const string &s)
{ static_assert (numeric_limits<T>::max() > 256, "str2 does not work on chars");
T i;
istringstream iss (s);
iss >> i;
if ( Common_sp::strBlank (s)
|| ! iss. eof ()
|| iss. fail ()
)
throw runtime_error ("Cannot convert " + strQuote (s) + " to number");
return i;
}
template <typename T>
bool str2 (const string &s,
T &t)
{ try { t = str2<T> (s); return true; }
catch (...) { return false; }
}
inline bool isLeft (const string &s,
const string &left)
{ return s. substr (0, left. size ()) == left; }
bool isRight (const string &s,
const string &right);
bool trimPrefix (string &s,
const string &prefix);
// Return: success
bool trimSuffix (string &s,
const string &suffix);
// Return: success
void trimSuffixNonAlphaNum (string &s);
bool trimTailAt (string &s,
const string &tailStart);
// Return: trimmed
// Update: s
void commaize (string &s);
// ' ' --> ','
inline bool isLeftBlank (const string &s,
size_t spaces)
{ size_t i = 0;
while (i < s. size () && i < spaces && s [i] == ' ')
i++;
return i == spaces;
}
string pad (const string &s,
size_t size,
ebool right);
// right: enull - center
bool goodName (const string &name);
bool isIdentifier (const string& name,
bool dashInName);
// Return: true. !empty(), !dashInName => (c \in mame => isLetter(c))
bool isNatural (const string& name,
bool leadingZeroAllowed);
void strUpper (string &s);
void strLower (string &s);
bool isUpper (const string &s);
bool isLower (const string &s);
inline string strUpper1 (const string &s)
{ if (s. empty ())
return s;
return toUpper (s [0]) + s. substr (1);
}
inline bool charInSet (char c,
const string &charSet)
{ return charSet. find (c) != string::npos; }
string::const_iterator stringInSet (const string &s,
const string &charSet);
// Return: != s.end() => *Return is not in charSet
size_t strCountSet (const string &s,
const string &charSet);
void strDeleteSet (string &s,
const string &charSet);
void trimLeading (string &s);
void trimTrailing (string &s);
inline void trim (string &s)
{ trimTrailing (s);
trimLeading (s);
}
void trimLeading (string &s,
char c);
// Invokes: isSpace()
void trimTrailing (string &s,
char c);
// Invokes: isSpace()
inline void trim (string &s,
char c)
{ trimTrailing (s, c);
trimLeading (s, c);
}
inline bool contains (const string &hay,
const string &needle)
{ return hay. find (needle) != string::npos; }
inline bool contains (const string &hay,
char needle)
{ return hay. find (needle) != string::npos; }
size_t containsWord (const string& hay,
const string& needle);
// Return: position of needle in hay; string::npos if needle does not exist
struct StringMatch
{
enum Type {part, word, whole};
};
bool matches (const string &hay,
const string &needle,
StringMatch::Type type);
void replace (string &s,
char from,
char to);
void replace (string &s,
const string &fromAnyChars,
char to);
void replaceStr (string &s,
const string &from,
const string &to);
// Replaces "from" by "to" in s from left to right
// The replacing "to" is skipped if it contains "from"
// Requires: !from.empty()
string to_c (const string &s);
// " --> \", etc.
void collapseSpace (string &s);
// " " --> " "
void visualizeTrailingSpaces (string &s);
// Invokes: nonPrintable2str(' ')
string str2streamWord (const string &s,
size_t wordNum);
// Return: May be empty()
// Input: wordNum: 0-based
string str2sql (const string &s);
// Return: ' s ' (replacing ' by '')
string findSplit (string &s,
char c = ' ');
// Return: prefix of s+c before c
// Update: s
string rfindSplit (string &s,
char c = ' ');
// Return: suffix of c+s after c
// Update: s
void reverse (string &s);
size_t strMonth2num (const string& month);
// Input: month: "Jan", "Feb", ... (3 characters)
// Bit operations
inline bool contains (uint who,
uint what)
{ return (who & what) == what; }
inline uchar reverse (uchar b)
{ return uchar (numeric_limits<uchar>::max () - b); }
size_t byte2first (uchar b);
// Return: First 1-bit, 0-based
size_t utf8_len (char first);
// Return: 0 - first is ASCII
// 1 - first is UTF-8 not first byte
// else - first is UTF-8 first byte and value is the number of UTF-8 bytes
// Integer operations
inline void advance (size_t &index,
size_t size)
// Update: index: < size
{ index++; if (index == size) index = 0; }
template <typename T/*:integer*/>
inline bool even (T x)
{ static_assert (numeric_limits<T>::is_integer);
return x % 2 == 0;
}
inline bool divisible (size_t n,
size_t divisor)
{ return ! (n % divisor); }
inline uint remainder (int n, uint div)
{ if (const int rem = n % (int) div)
return (uint) (rem > 0 ? rem : (rem + (int) div));
return 0;
}
inline uint gcd (uint a,
uint b)
// Greatest common divisor
// Euclid's algorithm
{ if (! b)
return a;
if (a < b)
return gcd (b, a);
return gcd (b, a % b);
}
size_t powInt (size_t a,
size_t b);
// Return: a^b
// Time: O(log(b))
struct Rand
// Numerical Recipes in C, p. 279
{
static const long /*actually ulong*/ max_;
private:
long seed;
// 0 < seed < max_
public:
explicit Rand (ulong seed_arg = 1)
{ setSeed (seed_arg); }
void setSeed (ulong seed_arg)
{ seed = (long) (seed_arg % (ulong) max_);
qc ();
}
// Input: seed_arg > 0
ulong get (ulong max);
// Return: in 0 .. max - 1
// Input: 0 < max <= max_
ulong get ()
{ return get ((ulong) max_); }
double getProb ()
{ return (double) get ((ulong) max_) / ((double) max_ - 1); }
// Return: [0,1]
private:
void qc () const;
void run ();
};
// Hexadecimal
inline bool isHex (char c)
{ return isDigit (c) || strchr ("ABCDEF", toUpper (c)); }
inline uchar hex2uchar (char c)
{ return uchar (isDigit (c) ? (c - '0') : (toUpper (c) - 'A' + 10)); }
inline string uchar2hex (uchar c)
{ constexpr char hex [16] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
string res (" ");
res [0] = hex [c / 16];
res [1] = hex [c % 16];
return res;
}
string unpercent (const string &s);
// '%HH' -> char
struct DisjointCluster
// Cormen, Leiserson, Rivest, Introduction to Algorithms, p. 449
{
protected:
DisjointCluster* parentDC;
// !nullptr
// Tree
// = this <=> root
size_t rankDC;
// Upper bound on the height of *this
// (Height = max. # arcs between *this and a leaf)
public:
protected:
DisjointCluster ()
{ init (); }
public:
void init ()
{ rankDC = 0;
parentDC = this;
}
void merge (DisjointCluster &other);
DisjointCluster* getDisjointCluster ();
};