-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathCBioInfCpp.h
18590 lines (12300 loc) · 714 KB
/
CBioInfCpp.h
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
// Документы CBioInfCpp.h, About_CBioInfCpp.rtf, About_CBioInfCpp.pdf (все указанные файлы размещены в настоящем каталоге) составляют собой одно произведение, которое распространяется на условиях лицензии Creative Commons Attribution 4.0 International Public License (сокращенно - CC BY, гиперссылка на текст лицензии: https://creativecommons.org/licenses/by/4.0/legalcode.ru).
// Автор CBioInfCpp.h, About_CBioInfCpp.rtf, About_CBioInfCpp.pdf - Черноухов Сергей ([email protected])
// The documents About_CBioInfCpp.pdf, CBioInfCpp.h, About_CBioInfCpp.rtf (all of them are placed in this directory) constitute a single Work (i.e. this Work is divided into these 3 files), and this Work is distributed under Creative Commons Attribution 4.0 International Public License (CC BY) (hyperlink to the License: https://creativecommons.org/licenses/by/4.0/legalcode.ru).
// CBioInfCpp.h, About_CBioInfCpp.rtf, About_CBioInfCpp.pdf are written by Sergey Chernouhov ([email protected]).
#ifndef CBIOINFCPP_H
#define CBIOINFCPP_H
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <set>
#include <algorithm>
#include <queue>
#include <map>
#include <cmath>
#include <stack>
#include <limits>
#include <limits.h>
#include <float.h>
#include <cstdlib>
#include <ctime>
#include <unordered_map>
#include <unordered_set>
#include <utility>
#include <functional>
#include <list>
int FastaRead (std::ifstream & fin, std::vector <std::string> & IndexS, std::vector <std::string> & DataS)
// Чтение строк FASTA из файла. Возвращает 0, если кол-во индексов строк равно кол-ву самих строк, самая первая строка является индексом (не начинается с ">") и в процессе считывания не встретились 2 индекса подряд. Иначе вернет -1.
// Reads FASTA dataset from file. Returns 0 if the number of indexes of strings = number of strings, the first string in dataset is index (starts with ">") and in dataset there is no 2 indexes one-by-one without a data string in between. Otherwise returns -1.
{
IndexS.clear();
// Сюда будут записываться индексы (обозначения) строк
// Here indexes of strings will be contained
DataS.clear();
// Сюда будут записываться сами строки
// Here data strings will be contained
std::string TempS = "";
int q = -1;
char f = 'd';
// флаг f = 'd'(data) или 'i' (индекс) - для исключения ситуации когда подряд идут 2 индекса
// flag f may be set as 'd' (data) or 'i' (index) - to prevent code-after-code situation.
while (!fin.eof())
{
TempS.clear();
getline (fin, TempS);
if (TempS[0] == '>')
{
if (f == 'i') {IndexS.clear(); DataS.clear(); return -1;}
q++;
f = 'i';
DataS.push_back("");
TempS.erase(0,1); // Вырезание начального символа ">" cutting symbol ">" from string's code
IndexS.push_back(TempS);
}
else
{
if (q==-1) return -1;
if (TempS.length() !=0) {DataS[q] = DataS[q] + TempS; f = 'd';};
}
}
if (DataS.size()!=IndexS.size()) {IndexS.clear(); DataS.clear(); return -1;}
return 0;
}
void StringsRead (std::ifstream & fin, std::vector <std::string> & DataS) // reads all strings from file to vector DataS
{
std::string TempS = "";
while (!fin.eof())
{
getline (fin, TempS);
if (TempS.length()!=0) DataS.push_back(TempS);
TempS.clear();
}
}
int MatrixSet (std::vector <std::vector <double>> & B, const int NLines, const int NColumns, const double i)
// Создает матрицу NLines х NColumns и заполняет значением i (double). Возвращает -1 если число строк или столбцов неположительно
// Sets (resets) matrix NLines x NColumns filled value "i" (double). Returns -1 if NLines or NColumns <=0
{
if ((NLines<=0) || (NColumns<=0)) return -1;
B.resize (NLines);
for (unsigned int row = 0; (row< NLines); row++)
{
B [row].resize(NColumns);
for (unsigned int column = 0; column < NColumns; column++)
{
B [row] [column] = i;
}
}
return 0;
}
int MatrixSet (std::vector <std::vector <int>> & B, const int NLines, const int NColumns, const int i)
// Создает матрицу NLines х NColumns и заполняет значением i (int). Возвращает -1 если число строк или столбцов неположительно
// Sets (resets) matrix NLines x NColumns filled value "i" (int). Returns -1 if NLines or NColumns <=0
{
if ((NLines<=0) || (NColumns<=0)) return -1;
B.resize (NLines);
for (unsigned int row = 0; (row< NLines); row++)
{
B [row].resize(NColumns);
for (unsigned int column = 0; column < NColumns; column++)
{
B [row] [column] = i;
}
}
return 0;
}
int MatrixSet (std::vector <std::vector <long long int>> & B, const int NLines, const int NColumns, const long long int i)
// Создает матрицу NLines х NColumns и заполняет значением i (long long int). Возвращает -1 если число строк или столбцов неположительно
// Sets (resets) matrix NLines x NColumns filled value "i" (long long int). Returns -1 if NLines or NColumns <=0
{
if ((NLines<=0) || (NColumns<=0)) return -1;
B.resize (NLines);
for (unsigned int row = 0; (row< NLines); row++)
{
B [row].resize(NColumns);
for (unsigned int column = 0; column < NColumns; column++)
{
B [row] [column] = i;
}
}
return 0;
}
int MatrixSet (std::vector <std::vector <long double>> & B, const int NLines, const int NColumns, const long double i)
// Создает матрицу NLines х NColumns и заполняет значением i (long double). Возвращает -1 если число строк или столбцов неположительно
// Sets (resets) matrix NLines x NColumns filled value "i" (long double). Returns -1 if NLines or NColumns <=0
{
if ((NLines<=0) || (NColumns<=0)) return -1;
B.resize (NLines);
for (unsigned int row = 0; (row< NLines); row++)
{
B [row].resize(NColumns);
for (unsigned int column = 0; column < NColumns; column++)
{
B [row] [column] = i;
}
}
return 0;
}
int MatrixSet (std::vector <std::vector <short int>> & B, const int NLines, const int NColumns, const short int i)
// Создает матрицу NLines х NColumns и заполняет значением i (short int). Возвращает -1 если число строк или столбцов неположительно
// Sets (resets) matrix NLines x NColumns filled value "i" (short int). Returns -1 if NLines or NColumns <=0
{
if ((NLines<=0) || (NColumns<=0)) return -1;
B.resize (NLines);
for (unsigned int row = 0; (row< NLines); row++)
{
B [row].resize(NColumns);
for (unsigned int column = 0; column < NColumns; column++)
{
B [row] [column] = i;
}
}
return 0;
}
int MatrixSet (std::vector <std::vector <bool>> & B, const int NLines, const int NColumns, const bool i)
// Создает матрицу NLines х NColumns и заполняет значением i (bool). Возвращает -1 если число строк или столбцов неположительно
// Sets (resets) matrix NLines x NColumns filled value "i" (bool). Returns -1 if NLines or NColumns <=0
{
if ((NLines<=0) || (NColumns<=0)) return -1;
B.resize (NLines);
for (unsigned int row = 0; (row< NLines); row++)
{
B [row].resize(NColumns);
for (unsigned int column = 0; column < NColumns; column++)
{
B [row] [column] = i;
}
}
return 0;
}
template < typename TMC>
int MatrixCout (std::vector <std::vector <TMC>> & B, char g = ' ')
// Вывод матрицы (элементов стандартных типов TMF) на экран через пробелы. Возвращает -1, если матрица не содержит строк/ столбцов
// Если строки матрицы разной длины, то "остатки" длины до максимальной при выводе заполняются символом g
// "Fouts" Matrix of standard type elements to screen. Returns -1 if the Matrix is empty.
// The Matrix may have lines of different length. In this case the "missing" values to the end for the "shorter lines" are filled with the char g.
{
int NLines, NColumns;
NLines = B.size();
if (NLines==0) return -1;
NColumns = B[0].size();
for (int i=0;i<NLines; i++)
if (B[i].size()>NColumns) NColumns=B[i].size();
if (NColumns==0) return -1;
for (unsigned int row = 0; (row< NLines); row++)
{
for (unsigned int column = 0; column < B[row].size(); column++)
{
std::cout<< B [row] [column]<< " ";
}
for (unsigned int column = B[row].size(); column < NColumns; column++)
{
std::cout<< g << " ";
}
std::cout<< std::endl;
}
return 0;
}
int MatrixCout (std::vector <std::vector <double>> & B, unsigned int prec = 4, char g = ' ', bool scientifique = false)
// Вывод матрицы (double) на экран через пробелы. Возвращает -1, если матрица не содержит строк/ столбцов
// Если строки матрицы разной длины, то "остатки" длины до максимальной при выводе заполняются символом g
// Вывод чисел проводится с заданной точностью prec, если bool scientifique == false. Если bool scientifique == true, вывод производится в экспоненциальной форме.
// "Couts" Matrix (double) to screen. Returns -1 if the Matrix is empty.
// The Matrix may have lines of different length. In this case the "missing" values to the end for the "shorter lines" are filled with the char g.
// If bool scientifique == false, the precision will be set as prec; if bool scientifique == true, scientific notation will be applied.
{
int NLines, NColumns;
NLines = B.size();
if (NLines==0) return -1;
NColumns = B[0].size();
for (int i=0;i<NLines; i++)
if (B[i].size()>NColumns) NColumns=B[i].size();
if (NColumns==0) return -1;
if (!scientifique)
{
std::cout.precision(prec);
for (unsigned int row = 0; (row< NLines); row++)
{
//for (unsigned int column = 0; column < NColumns; column++)
for (unsigned int column = 0; column < B[row].size(); column++)
{
std::cout<< std::fixed<< B [row] [column]<< " ";
}
for (unsigned int column = B[row].size(); column < NColumns; column++)
{
std::cout<< g << " ";
}
std::cout<< std::endl;
}
}
if (scientifique)
{
for (unsigned int row = 0; (row< NLines); row++)
{
//for (unsigned int column = 0; column < NColumns; column++)
for (unsigned int column = 0; column < B[row].size(); column++)
{
std::cout<< std::scientific << B [row] [column]<< " ";
}
std::cout.unsetf(std::ios::scientific);
for (unsigned int column = B[row].size(); column < NColumns; column++)
{
std::cout<< g << " ";
}
std::cout<< std::endl;
}
}
return 0;
}
int MatrixCout (std::vector <std::vector <long double>> & B, unsigned int prec = 4, char g = ' ', bool scientifique = false)
// Вывод матрицы (long double) на экран через пробелы. Возвращает -1, если матрица не содержит строк/ столбцов
// Если строки матрицы разной длины, то "остатки" длины до максимальной при выводе заполняются символом g
// Вывод чисел проводится с заданной точностью prec, если bool scientifique == false. Если bool scientifique == true, вывод производится в экспоненциальной форме.
// "Couts" Matrix (long double) to screen. Returns -1 if the Matrix is empty.
// The Matrix may have lines of different length. In this case the "missing" values to the end for the "shorter lines" are filled with the char g.
// If bool scientifique == false, the precision will be set as prec; if bool scientifique == true, scientific notation will be applied.
{
int NLines, NColumns;
NLines = B.size();
if (NLines==0) return -1;
NColumns = B[0].size();
for (int i=0;i<NLines; i++)
if (B[i].size()>NColumns) NColumns=B[i].size();
if (NColumns==0) return -1;
if (!scientifique)
{
std::cout.precision(prec);
for (unsigned int row = 0; (row< NLines); row++)
{
for (unsigned int column = 0; column < B[row].size(); column++)
{
std::cout<< std::fixed<< B [row] [column]<< " ";
}
for (unsigned int column = B[row].size(); column < NColumns; column++)
{
std::cout<< g << " ";
}
std::cout<< std::endl;
}
}
if (scientifique)
{
for (unsigned int row = 0; (row< NLines); row++)
{
for (unsigned int column = 0; column < B[row].size(); column++)
{
std::cout<< std::scientific<< B [row] [column]<< " ";
}
std::cout.unsetf(std::ios::scientific);
for (unsigned int column = B[row].size(); column < NColumns; column++)
{
std::cout<< g << " ";
}
std::cout<< std::endl;
}
}
return 0;
}
int MatrixFout (std::vector <std::vector <double>> & B, std::ofstream & fout, unsigned int prec = 4, char g = ' ', bool scientifique = false)
// Вывод матрицы (double) в файл через пробелы. Возвращает -1, если матрица не содержит строк/ столбцов
// Если строки матрицы разной длины, то "остатки" длины до максимальной при выводе заполняются символом g
// Вывод чисел проводится с заданной точностью prec, если bool scientifique == false. Если bool scientifique == true, вывод производится в экспоненциальной форме.
// "Fouts" Matrix (double) to file. Returns -1 if the Matrix is empty.
// The Matrix may have lines of different length. In this case the "missing" values to the end for the "shorter lines" are filled with the char g.
// If bool scientifique == false, the precision will be set as prec; if bool scientifique == true, scientific notation will be applied.
{
int NLines, NColumns;
NLines = B.size();
if (NLines==0) return -1;
NColumns = B[0].size();
for (int i=0;i<NLines; i++)
if (B[i].size()>NColumns) NColumns=B[i].size();
if (NColumns==0) return -1;
if (!scientifique)
{
fout.precision(prec);
for (unsigned int row = 0; (row< NLines); row++)
{
for (unsigned int column = 0; column < B[row].size(); column++)
{
fout<< std::fixed<< B [row] [column]<< " ";
}
for (unsigned int column = B[row].size(); column < NColumns; column++)
{
fout<< g << " ";
}
fout<< std::endl;
}
}
if (scientifique)
{
for (unsigned int row = 0; (row< NLines); row++)
{
for (unsigned int column = 0; column < B[row].size(); column++)
{
fout<< std::scientific<< B [row] [column]<< " ";
}
fout.unsetf(std::ios::scientific);
for (unsigned int column = B[row].size(); column < NColumns; column++)
{
fout<< g << " ";
}
fout<< std::endl;
}
}
return 0;
}
int MatrixFout (std::vector <std::vector <long double>> & B, std::ofstream & fout, unsigned int prec = 4, char g = ' ', bool scientifique = false)
// Вывод матрицы (long double) в файл через пробелы. Возвращает -1, если матрица не содержит строк/ столбцов
// Если строки матрицы разной длины, то "остатки" длины до максимальной при выводе заполняются символом g
// Вывод чисел проводится с заданной точностью prec, если bool scientifique == false. Если bool scientifique == true, вывод производится в экспоненциальной форме.
// "Fouts" Matrix (long double) to file. Returns -1 if the Matrix is empty.
// The Matrix may have lines of different length. In this case the "missing" values to the end for the "shorter lines" are filled with the char g.
// If bool scientifique == false, the precision will be set as prec; if bool scientifique == true, scientific notation will be applied.
{
int NLines, NColumns;
NLines = B.size();
if (NLines==0) return -1;
NColumns = B[0].size();
for (int i=0;i<NLines; i++)
if (B[i].size()>NColumns) NColumns=B[i].size();
if (NColumns==0) return -1;
if (!scientifique)
{
fout.precision(prec);
for (unsigned int row = 0; (row< NLines); row++)
{
for (unsigned int column = 0; column < B[row].size(); column++)
{
fout<< std::fixed<< B [row] [column]<< " ";
}
for (unsigned int column = B[row].size(); column < NColumns; column++)
{
fout<< g << " ";
}
fout<< std::endl;
}
}
if (scientifique)
{
for (unsigned int row = 0; (row< NLines); row++)
{
for (unsigned int column = 0; column < B[row].size(); column++)
{
fout<< std::scientific<< B [row] [column]<< " ";
}
fout.unsetf(std::ios::scientific);
for (unsigned int column = B[row].size(); column < NColumns; column++)
{
fout<< g << " ";
}
fout<< std::endl;
}
}
return 0;
}
template < typename TMF>
int MatrixFout (std::vector <std::vector <TMF>> & B, std::ofstream & fout, char g = ' ')
// Вывод матрицы (элементов стандартных типов TMF) в файл через пробелы. Возвращает -1, если матрица не содержит строк/ столбцов
// Если строки матрицы разной длины, то "остатки" длины до максимальной при выводе заполняются символом g
// "Fouts" Matrix of standard type elements to file. Returns -1 if the Matrix is empty.
// The Matrix may have lines of different length. In this case the "missing" values to the end for the "shorter lines" are filled with the char g.
{
int NLines, NColumns;
NLines = B.size();
if (NLines==0) return -1;
NColumns = B[0].size();
for (int i=0;i<NLines; i++)
if (B[i].size()>NColumns) NColumns=B[i].size();
if (NColumns==0) return -1;
for (unsigned int row = 0; (row< NLines); row++)
{
for (unsigned int column = 0; column < B[row].size(); column++)
{
fout<< B [row] [column]<< " ";
}
for (unsigned int column = B[row].size(); column < NColumns; column++)
{
fout<< g << " ";
}
fout<< std::endl;
}
return 0;
}
int FindIn (const std::vector <int> &D, int a, int step = 1, int start = 0)
{
// Возвращает индекс первого найденного элемента (int), совпадающего с искомым (a), поиск ведется с позиции start, шаг поиска = step, если не нашли такого элемента - возвращаем -1. Если переданное значение step <1, то step присваивается значение 1. Если переданное значение start <0, то start присваивается значение 1.
// Returns index in vector (int) of the first element = a. Search starts from index "start" with step = "step". If no such element found the function returns 0. If step<1 step will be set as 1. If start<0 start will be set as 0.
if (step <1) step = 1; if (start <0) start = 0;
for (unsigned int y = start; y<D.size(); y=y+step)
{
if (D[y] == a) return y;
}
return -1;
}
int FindIn (const std::vector <long long int> &D, long long int a, int step = 1, int start = 0)
{
// Возвращает индекс первого найденного элемента (long long int), совпадающего с искомым (a), поиск ведется с позиции start, шаг поиска = step, если не нашли такого элемента - возвращаем -1. Если переданное значение step <1, то step присваивается значение 1. Если переданное значение start <0, то start присваивается значение 1.
// Returns index in vector (long long int) of the first element = a. Search starts from index "start" with step = "step". If no such element found the function returns 0. If step<1 step will be set as 1. If start<0 start will be set as 0.
if (step <1) step = 1; if (start <0) start = 0;
for (unsigned int y = start; y<D.size(); y=y+step)
{
if (D[y] == a) return y;
}
return -1;
}
int FindIn (const std::vector <double> &D, double a, int step = 1, int start = 0)
{
// Возвращает индекс первого найденного элемента (double), совпадающего с искомым (a), поиск ведется с позиции start, шаг поиска = step, если не нашли такого элемента - возвращаем -1. Если переданное значение step <1, то step присваивается значение 1. Если переданное значение start <0, то start присваивается значение 1.
// Да, прямое сравнение чисел double не совсем корректно и это нужно принимать во внимание, но в ряде случаев функция может быть полезна.
// Для сравнения с заданной точностью см. вариант функции ниже.
// Returns index in vector (double) of the first element = a. Search starts from index "start" with step = "step". If no such element found the function returns 0. If step<1 step will be set as 1. If start<0 start will be set as 0.
// Yes, operation like (a==b) may be not correct for doubles. But this function may be considered as an useful one in some cases.
// The following version of the function finds the first element, that differs from "a" less than "d".
if (step <1) step = 1; if (start <0) start = 0;
for (unsigned int y = start; y<D.size(); y=y+step)
{
if ((D[y]-a)==0.0) return y;
}
return -1;
}
int FindIn (const std::vector <double> &D, double a, double d, int step = 1, int start = 0)
{
// Возвращает индекс первого найденного элемента (double), совпадающего с искомым (a) с точностью до d, поиск ведется с позиции start, шаг поиска = step, если не нашли такого элемента - возвращает -1. Если переданное значение step <1, то step присваивается значение 1. Если переданное значение start <0, то start присваивается значение 1.
// Returns index in vector (double) of the first element, that differs from "a" less than nonnegative double "d".
// Search starts from index "start" with step = "step". If no such element found the function returns 0. If step<1 step will be set as 1. If start<0 start will be set as 0.
if (step <1) step = 1; if (start <0) start = 0;
for (unsigned int y = start; y<D.size(); y=y+step)
{
if ( (std::abs(D[y] - a))<d) return y;
}
return -1;
}
int FindIn (const std::vector <long double> &D, long double a, int step = 1, int start = 0)
{
// Возвращает индекс первого найденного элемента (long double), совпадающего с искомым (a), поиск ведется с позиции start, шаг поиска = step, если не нашли такого элемента - возвращает -1. Если переданное значение step <1, то step присваивается значение 1. Если переданное значение start <0, то start присваивается значение 1.
// Да, прямое сравнение чисел long double не совсем корректно и это нужно принимать во внимание, но в ряде случаев функция может быть полезна. Для сравнения с заданной точностью см. вариант функции ниже.
// Returns index in vector (long double) of the first element = a. Search starts from index "start" with step = "step". If no such element found the function returns 0. If step<1 step will be set as 1. If start<0 start will be set as 0.
// Yes, operation like (a==b) may be not correct for doubles. But this function may be considered as an useful one in some cases. The following version of the function finds the first element, that differs from "a" less than "d".
if (step <1) step = 1; if (start <0) start = 0;
for (unsigned int y = start; y<D.size(); y=y+step)
{
if ((D[y]-a)==0.0) return y;
}
return -1;
}
int FindIn (const std::vector <long double> &D, long double a, long double d, int step = 1, int start = 0)
{
// Возвращает индекс первого найденного элемента (long double), совпадающего с искомым (a) с точностью до d, поиск ведется с позиции start, шаг поиска = step, если не нашли такого элемента - возвращаем -1. Если переданное значение step <1, то step присваивается значение 1. Если переданное значение start <0, то start присваивается значение 1.
// Returns index in vector (long double) of the first element, that differs from "a" less than nonnegative long double "d".
// Search starts from index "start" with step = "step". If no such element found the function returns 0. If step<1 step will be set as 1. If start<0 start will be set as 0.
if (step <1) step = 1; if (start <0) start = 0;
for (unsigned int y = start; y<D.size(); y=y+step)
{
if ( (std::abs(D[y] - a))<d) return y;
}
return -1;
}
int FindIn (const std::vector <std::string> &D, std::string a, int step = 1, int start = 0)
{
// Возвращает индекс первого найденного элемента (string), совпадающего с искомым (a), поиск ведется с позиции start, шаг поиска = step, если не нашли такого элемента - возвращаем -1. Если переданное значение step <1, то step присваивается значение 1. Если переданное значение start <0, то start присваивается значение 1.
// Returns index in vector (string) of the first element = a. Search starts from index "start" with step = "step". If no such element found the function returns 0. If step<1 step will be set as 1. If start<0 start will be set as 0.
if (step <1) step = 1; if (start <0) start = 0;
for (unsigned int y = start; y<D.size(); y=y+step)
{
if (D[y] == a) return y;
}
return -1;
}
//template < typename FIV>
//int FindIn (const std::vector <FIV> &D, FIV a, int step = 1, int start = 0)
//{
//// Возвращает индекс первого найденного элемента (int), совпадающего с искомым (a), поиск ведется с позиции start, шаг поиска = step, если не нашли такого элемента - возвращаем -1. Если переданное значение step <1, то step присваивается значение 1. Если переданное значение start <0, то start присваивается значение 1.
//// Returns index in vector (int) of the first element = a. Search starts from index "start" with step = "step". If no such element found the function returns 0. If step<1 step will be set as 1. If start<0 start will be set as 0.
// if (step <1) step = 1; if (start <0) start = 0;
// for (unsigned int y = start; y<D.size(); y=y+step)
// {
// if (D[y] == a) return y;
// }
// return -1;
//}
template < typename TVC>
int VectorCout (const TVC &P)
// Вывод вектора/ списка/ и др. итерируемых контейнеров, содержащих элементы стандартных типов, на экран через пробелы
// "Couts" vector/ list/ etc container of standard type elements to screen. Returns -1 if the container is empty
{
if (P.size()==0)
{
std::cout<< std::endl;
return -1;
}
for (auto i=P.begin(); i!=P.end();i++)
std::cout<< *i<<" ";
std::cout<< std::endl;
return 0;
}
template < typename TVF>
int VectorFout (const TVF &P, std::ofstream &fout)
// Вывод вектора/ списка/ и др. итерируемых контейнеров, содержащих элементы стандартных типов, в файл через пробелы
// "Fouts" vector/ list/ etc container of standard type elements to file. Returns -1 if the container is empty
{
if (P.size()==0)
{
fout<< std::endl;
return -1;
}
for (auto i=P.begin(); i!=P.end();i++)
fout<< *i<<" ";
fout<< std::endl;
return 0;
}
template < typename TMC1>
int MatrixCout (const TMC1 &P)
// Вывод "матрицы" на базе вектора/ списка/ и др. итерируемых контейнеров, содержащих элементы стандартных типов, на экран через пробелы
// "Couts" "matrix" based upon vector/ list/ etc container of standard type elements to screen. Returns -1 if the container is empty
{
if (P.size()==0) return -1;
for (auto i=P.begin(); i!=P.end();i++)
VectorCout(*P);
std::cout<< std::endl;
return 0;
}
template < typename TMF1>
int MatrixFout (const TMF1 &P, std::ofstream &fout)
// Вывод "матрицы" на базе вектора/ списка/ и др. итерируемых контейнеров, содержащих элементы стандартных типов, в файл через пробелы
// "Fouts" "matrix" based upon vector/ list/ etc container of standard type elements to file. Returns -1 if the container is empty
{
if (P.size()==0) return -1;
for (auto i=P.begin(); i!=P.end();i++)
VectorFout(*P, fout);
fout<< std::endl;
return 0;
}
std::string BWTransform (const std::string &s, const char h = '$')
// Constructs BWTransform of string s; the last symbol set as h.
// If input data is incorrest (empty s, h is in s) returns empty string.
// Генерирует BWTransform по строке s, символ h задает последний символ.
// Если s пустая или h есть в s, возвращает пустую строку.
{
std::string TempS="";
if (s=="")
{
return (TempS);
}
if (s.find(h)!=-1)
return TempS;
TempS = s+ h;
std::map <std::string, char> R;
R.clear();
R.insert(std::pair<std::string, char> (TempS, TempS[TempS.length()-1])) ;
for (int i=1; i<TempS.length();i++)
{
TempS = TempS[TempS.length()-1] + TempS;
TempS.pop_back();
R.insert(std::pair<std::string, char> (TempS, TempS[TempS.length()-1])) ;
}
TempS.clear();
for (auto it = R.begin(); it!=R.end();it++)
TempS.push_back(it->second);
return TempS;
}
std::string GenerateAlphabet (const std::vector <std::string> &DataS)
// Generates an alphabet upon the given vector of strings DataS. Symbols will be ordered under ASCII.
// Формирует алфавит из символов, входящих в набор строк DataS. Порядок символов в алфавите задается ASCII.
{
if (DataS.size()==0) return "";
std::string TempS="";
std::set <char> T;
T.clear();
for (int q = 0; q< DataS.size();q++)
for (int w = 0; w< DataS[q].length();w++)
T.insert(DataS[q][w]);
for (auto it=T.begin(); it!=T.end(); it++)
TempS.push_back(*it);
return TempS;
}
std::string GenerateAlphabet (const std::string &DataS)
// Generates an alphabet upon the given string DataS. Symbols will be ordered under ASCII.
// Формирует алфавит из символов, входящих в строку DataS. Порядок символов в алфавите задается ASCII.
{
if (DataS.length()==0) return "";
std::string TempS="";
std::set <char> T;
T.clear();
for (int w = 0; w< DataS.length();w++)
T.insert(DataS[w]);
for (auto it=T.begin(); it!=T.end(); it++)
TempS.push_back(*it);
return TempS;
}
int BW_SubstringsCount (const std::string &S, std::unordered_map<std::string, int>&DataS)
// Counts how many times strings contained in DataS appears at string S (using BWT transform).
// Подсчитывает по полю значение в DataS, сколько раз строка-ключ входит в строку S.
{
if (DataS.size()==0) return 0;
for (auto it = DataS.begin(); it!=DataS.end(); it++)
it->second=0;
if (S.length()==0) return 0;
std::string TempS=S+"$";
std::map <std::string, char> R;
R.clear();
R.insert(std::pair<std::string, char> (TempS, TempS[TempS.length()-1])) ;
for (int i=1; i<TempS.length();i++)
{
TempS = TempS[TempS.length()-1] + TempS;
TempS.pop_back();
R.insert(std::pair<std::string, char> (TempS, TempS[TempS.length()-1])) ;
}
TempS.clear();
for (auto it = R.begin(); it!=R.end();it++)
{
TempS.push_back(it->second);
}
std::string s0 = TempS;
std::sort (s0.begin(), s0.end());
std::map <char, int> FirstOccurrence;
FirstOccurrence.clear();
std::string Alph=GenerateAlphabet(TempS);
for (int q=0; q<Alph.length(); q++)
FirstOccurrence.insert(std::pair <char, int> ((char)(Alph[q]), s0.find((char)(Alph[q]))));
std::string TempS0=TempS;
sort (TempS0.begin(), TempS0.end());
int top, bottom, tindex, bindex;
char h;
int f=-1;
std::string NS;
for (auto it = DataS.begin(); it!=DataS.end(); it++)
{
NS = it->first;
top = 0;
bottom = TempS.length()-1;
while (top<=bottom)
{
if (NS.length()==0)
{it->second=(bottom-top+1);goto l1;}
if (NS.length()>0)
{
h = NS[NS.length()-1];
NS.pop_back();
tindex=0;
bindex =0;
for (int i = 0; i<top; i++)
{
if (TempS[i] == h)
{
tindex++;
}
}
for (int i = 0; i<=bottom; i++)
{
if (TempS[i] == h)
{
bindex++;
}
}
f=-1;
for (int i = top; i<=bottom; i++)
{
if (TempS[i] == h)
{
f=1;
break;
}
}
if (f<0)
{it->second=(0);goto l1;}
top = FirstOccurrence[h]+tindex;
bottom = FirstOccurrence[h]+bindex-1;
}
}
l1: ;
}
return 0;
}
template <typename Tia>
int IndexesInSortedArray (const std::vector <Tia> &Q, std::vector <int> &Qi, const bool increasing = true)
// Generating upon vector Q vector Qi so that Qi[j] equals the value of index (0-based indexing) in the vector Q for j-th element of Q if been sorted.
// bool increasing sets if sorting means increasing (true) or decreasing (false).
// Формирует на основании вектора Q вектор Qi, содержащий на j-й позиции номер индекса в Q, который бы приобрел элемент гипотетически отсортированного вектора Q,
// стоящий в отсортированном Q на позиции j. increasing задает, является ли такая гипотетическая сортировка по возрастанию, или по убыванию.
{
Qi.clear();
if (Q.size()==0) return -1;
std::vector <Tia> A=Q;
Qi.resize(Q.size());
if (increasing)
sort (A.begin(), A.end());