My Project
Loading...
Searching...
No Matches
AronLib.h
Go to the documentation of this file.
1#ifndef __AronLib__
2#define __AronLib__
3
4#ifdef __cplus
5#include <iostream>
6#include <fstream>
7#include <sstream>
8#include <string>
9#include <cmath>
10#include <utility> // std::pair, std::make_pair
11#endif
12
13#include <iostream>
14
15#include <sstream>
16#include <string>
17#include <sstream>
18#include <cmath>
19#include <utility> // std::pair, std::make_pair
20
21#include <execinfo.h>
22#include <stdio.h>
23#include <stdlib.h>
24#include "Vector3.h"
25#include "DDLinkedList.h"
26#include "Const.h"
27#include "/Users/aaa/myfile/bitbucket/clib/AronCLibNew.h"
28
29// #include "/Users/cat/myfile/bitbucket/cpplib/AronPrint.h"
30// #include <experimental/optional>
31// #include "/Library/Developer/CommandLineTools/usr/include/c++/v1/experimental/optional"
32// #include "/usr/local/include/boost/operations.hpp"
33
34#include <vector>
35
36// KEY: math library
37// URL: https://openframeworks.cc/documentation/glm/
38#include "glm/glm/glm.hpp"
39
40#include <dirent.h>
41#include <unistd.h>
42#include <limits.h>
43#include <regex>
44
45#include <algorithm>
46#include <cctype>
47#include <locale>
48
49#include <limits> // for std::numeric_limits
50#include <stdexcept> // for std::overflow_error
51
52#include <array> // std::array<int, 2> arr = {1, 2};
53#include <boost/filesystem.hpp>
54
55#ifdef __has_include // Check if __has_include is present
56# if __has_include(<optional>) // Check for a standard library
57# include<optional>
58# elif __has_include(<experimental/optional>) // Check for an experimental version
59# include <experimental/optional>
60# elif __has_include(<boost/optional.hpp>) // Try with an external library
61# include <boost/optional.hpp>
62# else // Not found at all
63# error "Missing <optional>"
64# endif
65#endif
66
68
83//const string S_RED = "\033[1;31m";
84//const string S_END = "\033[0m";
85
86//cout << "\033[1;31mbold red text\033[0m\n";
87
88// KEY: namespace forward declaration
89/*
90namespace MatrixVector {
91 class row;
92 class mat;
93};
94*/
95
96namespace fs = boost::filesystem;
97using namespace std;
98// using namespace AronGeometry;
99
100int len(string s);
101
102template<typename T>
103int len(vector<T> v);
104
105template<typename T>
106string toStr(const T& s);
107
108template<typename T>
109string toStr2(T& s);
110
111template<typename T>
112string toStrVar(T& s);
113
114template<typename T>
115vector<vector<T>> transpose(vector<vector<T>> mat);
116
117// NOTE: forward template class NO default type
118// ERROR: template<typename T = int , typename U = int>
119template<typename T, typename U>
120class two;
121
122template<typename T>
123bool compareVector(vector<T> v1, vector<T> v2);
124
125template<typename T>
126bool compareVector(vector<vector<T>> v1, vector<vector<T>> v2);
127
128template<typename T>
129vector<vector<T>> arrToVec2(T* arr, int len, int width);
130
131void printArr2(float* arr, int len, int width);
132
133
134
135int unsignToInt(size_t u);
136
137string padRight(string s, string pad, int maxLen);
138string padLeft(string s, string pad, int maxLen);
139
140template<typename T>
141two<T, T> divMod(T a, T b);
142
143void newline();
144void nl();
145int max(int a, int b, int c);
146int max(int a, int b, int c, int d);
147int max(vector<int> v);
148
149string reverseStr(string s);
150
151int maxConsecutiveOne(vector<int> vec);
152int strToInt(string s);
153int numFromBase(string fromBase, string input);
154
155vector<int> range(int a, int b);
156vector<int> range(int a, int b, int stride);
157
158template<typename T>
159vector<T> reverseVec(vector<T> vec);
160
161std::map<char, int> hexMap();
162
163string baseToBase(string fromBase, string toBase, string input);
164
165inline uint64_t nowMilliseconds();
166inline uint64_t nowMicroseconds();
167inline uint64_t nowNanoseconds();
168
169template<typename T>
170vector<T> repeatVec(int n, T t);
171template<typename T>
172vector<T> concatVec(vector<T> v1, vector<T> v2);
173// vector<T> concatVec(vector<T>& v1, vector<T>& v2);
174
175vector<int> randomNanoSec(int n, int max);
176
177template<typename T>
178T dotProduct(vector<T> v1, vector<T> v2);
179
180template<typename T>
181T det2(vector<vector<T>> v2);
182
183template<typename T>
184vector<T> subtract(vector<T> v1, vector<T> v2);
185
186
187void testfun()
188{
189}
190
191void testfun1() {
192}
193
194void testfun2 ( ) {
195}
196
197
202inline uint64_t nowMilliseconds() {
203 return std::chrono::duration_cast<std::chrono::milliseconds>
204 (std::chrono::high_resolution_clock::now().time_since_epoch()).count();
205}
206
211inline uint64_t nowMicroseconds() {
212 return std::chrono::duration_cast<std::chrono::microseconds>
213 (std::chrono::high_resolution_clock::now().time_since_epoch()).count();
214}
219inline uint64_t nowNanoseconds() {
220 return std::chrono::duration_cast<std::chrono::nanoseconds>
221 (std::chrono::high_resolution_clock::now().time_since_epoch()).count();
222}
223
224
225// string to int
226int strToInt(string s) {
227 return stoi(s);
228}
229
230// KEY: get size of types
231void getTypeSize(){
232 cout<<"int => " <<sizeof(int)<<endl;
233 cout<<"long => " <<sizeof(long)<<endl;
234 cout<<"float => " <<sizeof(float)<<endl;
235 cout<<"double => " <<sizeof(double)<<endl;
236 cout<<"size_t => " <<sizeof(size_t)<<endl;
237 cout<<"unsigned int => " <<sizeof(unsigned int)<<endl;
238 cout<<"unsigned long => " <<sizeof(unsigned long)<<endl;
239 cout<<"long long => " <<sizeof(long long)<<endl;
240}
241
250int maxConsecutiveOne(vector<int> vec){
251 int max = 0;
252 int prev = -1;
253 int curr = -1;
254 for(int i = 0; i < len(vec); i++){
255 if (vec[i] == 1){
256 if(prev == -1){
257 // Previous position
258 prev = i;
259 curr = i;
260 }else{
261 // Current position
262 curr = i;
263 }
264 }else{
265 if(prev != -1 && curr != -1){
266 int dist = curr - prev + 1;
267 if(dist > max){
268 max = dist;
269 }
270 }
271 // Reset positions
272 prev = -1;
273 curr = -1;
274 }
275 }
276
277 if(prev != -1 && curr != -1){
278 int dist = curr - prev + 1;
279 if(dist > max){
280 max = dist;
281 }
282 }
283 return max;
284}
285
289int maxConsecutiveChar(char* arr, int size, char c){
290 int max = 0;
291 int prev = -1;
292 int curr = -1;
293 for(int i = 0; i < size; i++){
294 if(arr[i] == c){
295 if(prev == -1){
296 prev = i;
297 curr = i;
298 }else{
299 curr = i;
300 }
301 }else{
302 if(prev != -1){
303 int dist = curr - prev + 1;
304 max = dist > max ? dist : max;
305 prev = -1;
306 curr = -1;
307 }
308 }
309 }
310 if(prev != -1){
311 int dist = curr - prev + 1;
312 max = dist > max ? dist : max;
313 }
314 return max;
315}
316
335std::map<char, int> hexMap(){
336 char c1 = '0';
337 char c2 = 'a';
338 int k = 0;
339
340 std::map<char, int> map;
341 for(int i = 0; i < 16; i++){
342 if(i < 10){
343 map[c1 + i] = i;
344 }
345 else{
346 map[c2 + k] = i;
347 k++;
348 }
349 }
350 return map;
351}
352
353std::map<int, char> hexMapRev(){
354 std::map<int, char> revMap;
355 std::map<char, int> map = hexMap();
356 std::map<char, int>::iterator it = map.begin();
357 while(it != map.end()){
358 char key = it -> first;
359 int value = it -> second;
360 revMap[value] = key;
361 it++;
362 }
363 return revMap;
364}
365
366int numFromBase(string fromBase, string input){
367 int k = 0;
368 int sum = 0;
369 std::map<char, int> map = hexMap();
370 for(auto i : reverseVec(range(0, input.size()))){
371 int ii = input.size() - 1 - i;
372 if('0' <= input[i] && input[i] <= '9' || 'a' <= input[i] && input[i] <= 'z'){
373 int value = map[input[i]];
374 if(value != NULL){
375 sum += value * pow(strToInt(fromBase), ii);
376 }
377 }
378 }
379 return sum;
380}
381
384string baseToBase(string fromBase, string toBase, string input){
385 string ret = "";
386 int sum = numFromBase(fromBase, input);
387 std::map<int, char> map = hexMapRev();
388 int toBaseNum = strToInt(toBase);
389 if(sum == 0){
390 ret += '0';
391 }else{
392 while(sum > 0){
393 int q = sum / toBaseNum;
394 int r = sum % toBaseNum;
395 ret = map[r] + ret;
396 sum = q;
397 }
398 }
399 return ret;
400}
401
405vector<int> toBinary(int n){
406 vector<int> vec;
407 string s = baseToBase("10", "2", toStr2(n));
408 for(int i = 0; i < len(s); i++){
409 if (s[i] == '0'){
410 vec.push_back(0);
411 }else if(s[i] == '1'){
412 vec.push_back(1);
413 }else{
414 printf("ERROR: Invalid Char");
415 exit(1);
416 }
417 }
418 return vec;
419}
420
421template<typename T>
422vector<vector<T>> arrToVec2(T* arr, int len, int width){
423 vector<vector<T>> vv;
424
425 int q = len / width;
426 int r = len % width;
427
428 for(int i = 0; i < q; i++){
429 vector<T> v;
430 for(int j = 0; j < width; j++){
431 v.push_back(arr[width * i + j]);
432 }
433 vv.push_back(v);
434 }
435 if(0 < r){
436 vector<T> w;
437 for(int i = 0; i < width; i++){
438 if(i < r){
439 w.push_back(arr[width * q + i]);
440 }else{
441 w.push_back(0.0);
442 }
443 }
444 vv.push_back(w);
445 }
446 return vv;
447}
448
449
450template<typename T>
451two<T, T> divMod(T a, T b){
452 two<T, T> t(a / b, a % b);
453 return t;
454}
455
456
457int max(int a, int b, int c){
458 return max(max(a, b), c);
459}
460
461int max(int a, int b, int c, int d){
462 return max(max(max(a, b), c), d);
463}
464
465int max(vector<int> v){
466 if(v.size() > 0){
467 int m = v[0];
468 for(auto x : v){
469 m = max(m, x);
470 }
471 return m;
472 }else{
473 printf("ERROR: vector can not be empty\n");
474 std::exit(EXIT_FAILURE);
475 }
476}
477
478int abs_int(int a){
479 std::abs(a);
480}
481float abs_f(float a){
482 std::abs(a);
483}
484long abs_l(long a){
485 std::abs(a);
486}
487long long abs_ll(long long a){
488 std::abs(a);
489}
490double abs_d(double a){
491 std::abs(a);
492}
493unsigned int abs_ui(unsigned int a){
494 return 0;
495}
496
497string reverseStr(string s){
498 std::string rs = s;
499 std::reverse(rs.begin(), rs.end());
500 return rs;
501}
502
503
504template<typename T>
505void writeFileAppendVector(string fname, std::vector<T> vec) {
506 ofstream ofs;
507 ofs.open (fname, std::ofstream::out | std::ofstream::app);
508 for(T s : vec) {
509 ofs<<s<<std::endl;
510 }
511 ofs.close();
512}
513
514void newline(){
515 printf("\n");
516}
517
518
519
520void writeFile(string fname, string s) {
521 ofstream ofs;
522 ofs.open(fname, std::ofstream::out);
523 ofs<<s;
524 ofs.close();
525}
526
527void writeFileAppend(string fname, string s) {
528 ofstream ofs;
529 ofs.open(fname, std::ofstream::out | std::ofstream::app);
530 ofs<<s;
531 ofs.close();
532}
533
534template<typename T>
535void writeFileVector(string fname, std::vector<T> vec) {
536 ofstream ofs;
537 ofs.open (fname, std::ofstream::out);
538 for(T s : vec) {
539 ofs<<s<<std::endl;
540 }
541 ofs.close();
542}
543
544
545
551template<typename T>
552void writeFileAppendRow(string fname, std::vector<T> vec) {
553 ofstream ofs;
554 ofs.open (fname, std::ofstream::out | std::ofstream::app);
555 for(T s : vec) {
556 ofs<<s<<" ";
557 }
558 ofs.close();
559}
560
561std::pair<string, string> split(string s, int inx) {
562 unsigned long len = s.length();
563 if(0 <= inx && inx <= len) {
564 string prefix = s.substr(0, inx);
565 string suffix = s.substr(inx, len);
566 return make_pair(prefix, suffix);
567 } else if(inx < 0) {
568 return make_pair("", s);
569 } else {
570 return make_pair(s, "");
571 }
572}
573
588vector<int> sumVec(vector<int> v1, vector<int> v2){
589 vector<int> vec;
590 int diff = v2.size() > v1.size() ? v2.size() - v1.size() : v1.size() - v2.size();
591 vector<int> mv = v2.size() > v1.size() ? v2 : v1;
592 vector<int> iv = v2.size() > v1.size() ? v1 : v2;
593 vector<int> vz = repeatVec(diff, 0);
594 vector<int> w1 = mv;
595 vector<int> w2 = concatVec(vz, iv);
596 vector<int> ux = repeatVec(len(mv) + 1, 0);
597
598 int c = 0;
599 for(int i = len(w1) - 1; i >= 0; i--){
600 int s = w1[i] + w2[i] + c;
601 ux[i + 1] = s % 10;
602 c = s / 10;
603 }
604 ux[0] = c;
605
606 return ux;
607}
608
609
610
627template<typename T, typename Fun>
628static vector<vector<T>> splitWhen(Fun f, const vector<T>& vec) {
629 vector<vector<T>> ret;
630 vector<T> v2;
631 for(auto const& e : vec) {
632 if(!f(e)) {
633 v2.push_back(e);
634 }else{
635 if(len(v2) > 0){
636 vector<T> tmp(v2);
637 ret.push_back(tmp);
638 v2.clear();
639 }
640 }
641 }
642 if(len(v2) > 0){
643 vector<T> tmp(v2);
644 ret.push_back(tmp);
645 }
646 return ret;
647}
648
655string removeIndex(string s, int inx) {
656 std::pair<string, string> p = split(s, inx);
657 string prefix = p.first;
658 string suffix = p.second;
659 string tail = suffix.substr(1, suffix.length());
660 return prefix + tail;
661}
666template<typename T>
667vector<T> removeIndex(vector<T>& vec, int inx){
668 vector<T> ret(vec); // clone vec
669 ret.erase(ret.begin() + inx);
670 return ret;
671}
672
685template<typename T>
686vector<T> removeIndexRange(vector<T>& vec, int fromInx, int toInx){
687 vector<T> ret(vec); // clone vec
688 // Error if vector is removed from the smaller index
689 for(int i=toInx; i >= fromInx; i--){
690 ret.erase(ret.begin() + i);
691 }
692 return ret;
693}
694
695
696string repeat(int n, string s);
697string cStringToString(const char* pt);
698
699template<typename T>
700void pl(T t);
701
702void print(glm::vec3 v3);
703void print(glm::vec2 v2);
704string removeAdjacentDuplicateChar(string s, char c);
705string concatValidPath(vector<string> vec);
706
707
708
709template<typename T>
710void print(std::pair<T, T> pair);
711
712template<typename T>
713void print(vector<T> vec);
714
715template<typename T>
716void printVec(vector<T> vec);
717
718
719template<typename T>
720void print(vector< vector<T> > vec);
721
722template<typename T>
723void print(T t);
724
725template<typename T>
726void print(string msg, T t);
727
728void nl();
729
730template<typename T>
731void printLnNb(T t);
732
733template<typename T>
734vector<T> operator+(vector<T> v1, vector<T> v2);
735
736string operator+(const char* chars, string s);
737
738string operator+(string s, const char* chars);
739
740template<typename T>
741vector<T> con(T t, vector<T> v);
742
743namespace AronPrint {
744using namespace std;
745
746void ppf(const char* format, ...);
747// void fl();
748void fw(string s);
749
750template<typename T>
751void pp(T t);
752
753template<typename T>
754void pp(T t1, T t2);
755
756template<typename T>
757void pp(T t1, T t2, T t3);
758
759template<typename T, typename U>
760void pp(std::pair<T, U> p);
761
762void pp(int n);
763void pp(float n);
764void pp(long n);
765void pp(unsigned long n);
766
767template<typename T>
768void pp(T t) {
769 print(t);
770}
771
772template<typename T>
773void pp(T t1, T t2) {
774 std::cout<<"call me maybe"<<endl;
775 std::cout<<t1<<t2<<endl;
776}
777
778template<typename T>
779void pp(T t1, T t2, T t3) {
780 std::cout<<t1<<t2<<t3<<endl;
781}
782void ppf(const char* format, ...) {
783 std::cout<<"printf format"<<endl;
784 printf(format);
785}
786
787template<typename T, typename U>
788void pp(std::pair<T, U> p){
789 pp(toStr(p));
790}
791
792void pp(int n) {
793 std::cout<<"["<<n<<"]"<<endl;
794}
795
796void pp(float n) {
797 std::cout<<"["<<n<<"]"<<endl;
798}
799
800void pp(long n) {
801 std::cout<<"["<<n<<"]"<<endl;
802}
803void pp(unsigned long n) {
804 std::cout<<"["<<n<<"]"<<endl;
805}
806
807void pp(string msg0, string msg1){
808 std::cout<<msg0<<msg1<<std::endl;
809}
810void pp(string msg0, float num){
811 std::cout<<msg0<<num<<std::endl;
812}
813void pp(string msg0, int num){
814 std::cout<<msg0<<num<<std::endl;
815}
816void pp(string msg0, long num){
817 std::cout<<msg0<<num<<std::endl;
818}
819void pp(string msg0, double num){
820 std::cout<<msg0<<num<<std::endl;
821}
822void pp(string msg0, char* charPt){
823 std::cout<<msg0<<charPt<<std::endl;
824}
825
826/*
827void fl() {
828 newline();
829 printLnNb(repeat(80, "-"));
830}
831*/
832
833void fl(string s) {
834 int n = 80;
835 string s1 = repeat(n/2 - len(s)/2, "-");
836 string s2 = repeat(n/2 - len(s)/2, "-");
837 printLnNb(s1 + s + s2);
838}
839
840void fw(string s) {
841 int len = s.length();
842 int pad = 40 - (len/2);
843 cout<<endl;
844 printLnNb(repeat(pad, "-") + s + repeat(pad, "-"));
845}
846
847} // end AronPrint
848
849
851 clock_t startTime = 0;
852 clock_t endTime = 0;
853 clock_t diff = 0;
854 public:
855 StopWatch() {
856 startTime = clock();
857 }
858
859 // Deprecated, use start() instead
860 void begin() {
861 startTime = clock();
862 pl("Start StopWatch()");
863 }
864 void start() {
865 begin();
866 }
867 void end() {
868 endTime = clock();
869 diff = endTime - startTime;
870 std::cout<<"Diff=["<<(float)diff/CLOCKS_PER_SEC<<"] Seconds"<<std::endl;
871 std::cout<<"Tick=["<<diff<<"] ticks"<<std::endl;
872 }
873 void print() {
874 endTime = clock();
875 diff = endTime - startTime;
876 std::cout<<"Diff=["<<(float)diff/CLOCKS_PER_SEC<<"] Seconds"<<std::endl;
877 std::cout<<"Tick=["<<diff<<"] ticks"<<std::endl;
878 }
879 void printTick() {
880 endTime = clock();
881 clock_t diff = endTime - startTime;
882 std::cout<<"Tick=["<<diff<<"] CPU ticks"<<std::endl;
883 }
884};
885
886
887template<typename T = int, typename U = int>
888class two{
889 public:
890 T first;
891 T x;
892 // T& fst = 0;
893 U second;
894 U y;
895 two(){
896 // fst = 0;
897 }
898 two(T first, U second) {
899 this -> x = this -> first = first;
900 this -> y = this -> second = second;
901 }
902 public:
903 string toStr(){
904 return "(" + toStr2(x) + "," + toStr2(y) + ")";
905 }
906 string toString(){
907 return toStr();
908 }
909};
910
911
912
913namespace AronLambda {
918template<typename T>
919T head(vector<T> vec) {
920 assert(vec.size() > 0);
921 return vec[0];
922
923}
924
925char head(string s){
926 if(len(s) > 0)
927 return s[0];
928 else
929 throw std::runtime_error("string is empty.");
930}
931
936template<typename T>
937T last(vector<T> vec) {
938 assert(vec.size() > 0);
939 return vec.back();
940}
941
952template<typename T>
953static vector<T> reverse(vector<T> vec) {
954 vector<T> v;
955 for(auto it=vec.rbegin(); it != vec.rend(); it++)
956 v.push_back(*it);
957 return v;
958}
959
960template<typename T>
961static vector<T> rev(vector<T> vec) {
962 return reverse(vec);
963}
964
982template<typename Fun, typename T>
983static vector<T> takeWhile(Fun f, vector<T> vec) {
984 vector<T> ret;
985 for(auto const& n : vec) {
986 if(f(n))
987 ret.push_back(n);
988 else
989 break;
990 }
991 return ret;
992}
993
1000template<typename Fun, typename T>
1001static vector<T> dropWhile(Fun f, vector<T> vec) {
1002 vector<T> ret;
1003 bool flag = false;
1004 for(auto const& n : vec) {
1005 if(!f(n) || flag) {
1006 ret.push_back(n);
1007 flag = true;
1008 }
1009 }
1010 return ret;
1011}
1012
1013template<typename Fun>
1014static string takeWhile(Fun f, string str) {
1015 string ret = "";
1016 int inx = -1;
1017 for(int i = 0; i < len(str); i++){
1018 if(!f(str[i])){
1019 inx = i;
1020 break;
1021 }
1022 }
1023 if(inx != -1)
1024 ret = str.substr(0, inx);
1025
1026 return ret;
1027}
1028
1029template<typename Fun>
1030static string dropWhile(Fun f, string str) {
1031 string ret = "";
1032 int inx = -1;
1033 for(int i = 0; i < len(str); i++){
1034 if(!f(str[i])){
1035 inx = i;
1036 break;
1037 }
1038 }
1039 if(inx != -1)
1040 ret = str.substr(inx, len(str));
1041
1042 return ret;
1043}
1044
1045template<typename Fun>
1046static two<string, string> splitWhileStr(Fun f, string str){
1048
1049 int ln = len(str);
1050 int i = 0;
1051 for(i = 0; i < ln; i++){
1052 if(!f(str[i])){
1053 break;
1054 }
1055 }
1056 string s1 = str.substr(0, i);
1057 string s2 = str.substr(i, ln);
1058 tw.x = s1;
1059 tw.y = s2;
1060
1061 return tw;
1062}
1063
1070template<typename T>
1071static vector<T> tail(vector<T> vec) {
1072 vector<T> v;
1073 for(int i=1; i<vec.size(); i++) {
1074 v.push_back(vec.at(i));
1075 }
1076 return v;
1077}
1078
1083template<typename Fun, typename T>
1084static T foldl(Fun f, T acc, vector<T> vec) {
1085 T tmpAcc = acc;
1086 for(auto ite = vec.begin(), end = vec.end(); end != ite; ite++) {
1087 tmpAcc = f(tmpAcc, *ite);
1088 }
1089 return tmpAcc;
1090}
1091
1092
1102template<typename Fun, typename T>
1103static T foldr(Fun f, T acc, const vector<T>& vec) {
1104 T tmpAcc = acc;
1105 for(int i=vec.size() - 1; i >= 0; i--) {
1106 tmpAcc = f(vec[i], tmpAcc);
1107 }
1108 return tmpAcc;
1109}
1110
1111template<class T>
1112static vector<T> init(const vector<T>& vec) {
1113 assert(vec.size() > 0);
1114 vector<T> v;
1115 for(int i=0; i < vec.size() - 1; i++) {
1116 v.push_back(vec[i]);
1117 }
1118 return v;
1119}
1120
1121
1133template<typename Fun, typename A>
1134static vector<A> map(Fun f, vector<A> vec) {
1135 vector<A> vec1;
1136 for(auto& v : vec) {
1137 vec1.push_back(f(v));
1138 }
1139 return vec1;
1140}
1141
1142template<typename Fun, typename T>
1143static vector<T> zipWith(Fun f, vector<T> v1, vector<T> v2) {
1144 vector<T> vec;
1145 int len1 = unsignToInt(v1.size());
1146 int len2 = unsignToInt(v2.size());
1147 for(int i=0; i<min(len1, len2); i++) {
1148 for(int j=0; j<min(len1, len2); j++) {
1149 vec.push_back(f(v1[i], v2[j]));
1150 }
1151 }
1152 return vec;
1153}
1154
1166template<typename T>
1167static vector<T> flat(vector<vector<T>>& vec2){
1168 vector<T> vec;
1169 for(vector<T>& v : vec2){
1170 vec = vec + v;
1171 }
1172 return vec;
1173}
1174
1184template<typename T, typename Fun>
1185static vector<T> filter(Fun f, const vector<T>& vec) {
1186 vector<T> vec1;
1187 for(auto const& v : vec) {
1188 if(f(v)) {
1189 vec1.push_back(v);
1190 }
1191 }
1192 return vec1;
1193}
1194
1195// take n char from a string
1196static string take(int n, string s) {
1197 return s.substr(0, n);
1198}
1199
1200/*
1201string cStringToString(const char* pt) {
1202 std::string s(pt);
1203 return s;
1204}
1205*/
1206
1207static string take(int n, const char* str){
1208 string s = cStringToString(str);
1209 return take(n, s);
1210}
1211
1212template<class T>
1213static vector<T> take(int n, const vector<T>& vec) {
1214 vector<T> vec1;
1215 int c = 0;
1216 for(auto const& v : vec) {
1217 if (c < n) {
1218 vec1.push_back(v);
1219 } else {
1220 break;
1221 }
1222 c++;
1223 }
1224 return vec1;
1225}
1226
1227template<class T>
1228static vector<T> drop(int n, vector<T> vec) {
1229 vector<T> vec1;
1230 int c = 0;
1231 for(auto const& v : vec) {
1232 if (c >= n)
1233 vec1.push_back(v);
1234 c++;
1235 }
1236 return vec1;
1237}
1238
1239template<typename Fun, typename T>
1240static vector<T> mergeSortListLam(Fun f, vector<T> v1, vector<T> v2) {
1241 vector<T> empty;
1242 if (v1.size() == 0)
1243 return v2;
1244 if (v2.size() == 0)
1245 return v1;
1246
1247 vector<T> vh1 = take(1, v1);
1248 vector<T> vh2 = take(1, v2);
1249 if (f(vh1.at(0), vh2.at(0))) {
1250 return vh1 + mergeSortListLam(f, tail(v1), v2);
1251 } else {
1252 return vh2 + mergeSortListLam(f, v1, tail(v2));
1253 }
1254}
1255
1261template<class T>
1262static vector<T> mergeSortList(vector<T> v1, vector<T> v2) {
1263 vector<T> empty;
1264 if (v1.size() == 0)
1265 return v2;
1266 if (v2.size() == 0)
1267 return v1;
1268
1269 vector<T> vh1 = take(1, v1);
1270 vector<T> vh2 = take(1, v2);
1271 if (vh1.at(0) < vh2.at(0)) {
1272 return vh1 + mergeSortList(tail(v1), v2);
1273 } else {
1274 return vh2 + mergeSortList(v1, tail(v2));
1275 }
1276}
1277
1278template<class T>
1279static vector<T> mergeSort(vector<T> v1) {
1280 if(v1.size() > 1) {
1281 vector<T> left = take(v1.size()/2, v1);
1282 vector<T> right= drop(v1.size()/2, v1);
1283 vector<T> subl = mergeSort(left);
1284 vector<T> subr = mergeSort(right);
1285 return mergeSortList(subl, subr);
1286 } else {
1287 return v1;
1288 }
1289}
1290
1291}; // end namespace AronLambda
1292
1293template<typename T, typename U>
1294class two;
1295
1296using namespace AronLambda;
1297
1298
1299
1300// using namespace MySpace;
1301
1302// namespace fs = boost::filesystem;
1303
1304// using namespace Algorithm;
1305// using namespace AronClass;
1306
1307
1308
1309
1310template<typename T>
1311void pl(T t) {
1312 print(t);
1313 newline();
1314}
1315
1316// TODO: Rename a better name
1317template<typename T>
1318string toStr2(T& s) {
1319 std::ostringstream out;
1320 out<<s;
1321 return out.str();
1322}
1323
1324template<typename T>
1325string toStrVar(T& s) {
1326 std::ostringstream out;
1327 out<<s;
1328 return out.str();
1329}
1330
1331
1332template<typename T>
1333void swap(vector<T>& vec, int i, int j);
1334
1335
1336int random(int n);
1337string cStringToString(const char* pt);
1338
1339void nl(){
1340 printf("\n");
1341}
1342
1343template<typename T>
1344void swap(T arr[], int i, int j) {
1345 T tmp = arr[i];
1346 arr[i] = arr[j];
1347 arr[j] = tmp;
1348}
1349
1350template<typename T>
1351void swap(vector<T>& vec, int i, int j){
1352 T tmp = vec[i];
1353 vec[i] = vec[j];
1354 vec[j] = tmp;
1355}
1356
1357
1369long lcgRandom(long x0){
1370 long a = 1664525;
1371 long c = 1013904223;
1372 long m = (long)pow((double)2, (double)32);
1373 long x1 = (a * x0 + c) % m;
1374 return x1;
1375}
1376
1377
1378vector<int> randomIntVec(int count, int max){
1379 vector<int> v;
1380 long x0 = 22337737;
1381 for(int i = 0; i < count; i++){
1382 int x1 = lcgRandom(x0) % INT_MAX;
1383 v.push_back(x1 % max);
1384 x0 = (long)x1;
1385 }
1386 return v;
1387}
1388
1392vector<int> randomNanoSec(int n, int max){
1393 vector<int> v;
1394 for(int i = 0; i < n; i++){
1395 auto n = nowNanoseconds();
1396 v.push_back(n % max);
1397 }
1398 return v;
1399}
1400
1401
1402
1410int random(int n) {
1411 long x0 = 399;
1412 return lcgRandom(x0) % n;
1413}
1414
1415
1416// print all prime from 2 to n
1417vector<int> allPrime(int n) {
1418 vector<int> vec;
1419 if(n >= 2) {
1420 vec.push_back(2);
1421 for(int p=3; p<n; p++) {
1422 bool isPrime = true;
1423 for(int i=0; i<vec.size() && isPrime; i++) {
1424 if(p % vec[i] == 0)
1425 isPrime = false;
1426 }
1427 if(isPrime)
1428 vec.push_back(p);
1429 }
1430 }
1431 return vec;
1432}
1433
1434vector<int>* nPrime(int n){
1435 vector<int>* vec = new vector<int>();
1436 if(n > 0){
1437 vec -> push_back(2);
1438 int c = 1;
1439 int num = 3;
1440 while(c < n){
1441 bool isPrime = true;
1442 for(auto const& p : *vec){
1443 if (num % p == 0){
1444 isPrime = false;
1445 break;
1446 }
1447 }
1448 if(isPrime){
1449 vec -> push_back(num);
1450 c++;
1451 }
1452 num++;
1453 }
1454 }
1455 return std::move(vec);
1456}
1457
1463const char* stringToCString(string s) {
1464 return s.c_str();
1465}
1466
1470const char* s2c(string s) {
1471 return s.c_str();
1472}
1473
1479const char* toCharPtr(string s) {
1480 return s2c(s);
1481}
1482
1483const char* strToCharArray(string s){
1484 return s.c_str();
1485}
1486
1493template<typename T>
1494string toStr(const T& s) {
1495 std::ostringstream out;
1496 out<<s;
1497 return out.str();
1498}
1499
1500template<typename T, typename U>
1501string toStr(std::pair<T, U> p){
1502 string ret = "";
1503 ret += "(";
1504 ret += toStr(p.first) + " , ";
1505 ret += toStr(p.second);
1506 ret += ")";
1507 return ret;
1508}
1509
1510template<typename T, typename U>
1511string str(std::pair<T, U> p){
1512 return toStr(p);
1513}
1514
1515template<typename T>
1516string str(const T& s) {
1517 return toStr(s);
1518}
1519
1520template<typename T>
1521string str2(T& s) {
1522 return toStr2(s);
1523}
1524
1525string trimLeft(string str) {
1526 string s = str;
1527 s.erase(s.begin(), std::find_if(s.begin(), s.end(), [](char& x) {
1528 return !std::isspace(x);
1529 }));
1530 return s;
1531}
1532
1533string trimRight(string str) {
1534 string s = str;
1535 s.erase(std::find_if(s.rbegin(), s.rend(), [](char& x) {
1536 return !std::isspace(x);
1537 }).base(), s.end());
1538 return s;
1539}
1540
1547string trim(string str) {
1548 string s = str;
1549 return trimRight(trimLeft(s));
1550}
1551
1557string cStringToString(const char* pt) {
1558 std::string s(pt);
1559 return s;
1560}
1561
1562string charPtrToString(const char* pt){
1563 std::string s(pt);
1564 return s;
1565}
1566
1570string c2s(const char* pt) {
1571 string s(pt);
1572 return s;
1573}
1574
1584bool containStrRegex(string s, regex rx) {
1585 smatch m;
1586 regex_search(s, m, rx);
1587 return m.size() > 0;
1588}
1589
1599bool containStr(string str, string pat) {
1600 smatch m;
1601 regex rx(pat);
1602 regex_search(str, m, rx);
1603 return m.size() > 0;
1604}
1605
1619vector<string> splitStr(string s, string delim) {
1620 vector<string> vec;
1621 auto start = 0U;
1622 auto end = s.find(delim);
1623 while (end != std::string::npos) {
1624 vec.push_back(s.substr(start, end - start));
1625 start = end + delim.length();
1626 end = s.find(delim, start);
1627 }
1628 vec.push_back(s.substr(start, s.size() - start));
1629 return vec;
1630}
1631
1644template<typename T>
1645std::pair<vector<T>, vector<T>> splitAt(int n, vector<T> vec) {
1646 vector<T> fstVec;
1647 vector<T> sndVec;
1648 for(int i=0; i<vec.size(); i++) {
1649 if(i < n)
1650 fstVec.push_back(vec[i]);
1651 else
1652 sndVec.push_back(vec[i]);
1653 }
1654 return std::make_pair(fstVec, sndVec);
1655}
1656
1662template<typename Fun, typename T>
1663std::pair<vector<T>, vector<T>> breakVec(Fun f, vector<T> vec) {
1664 bool first = true;
1665 vector<T> fstVec;
1666 for(int i=0; i<vec.size(); i++) {
1667 if(f(vec[i])) {
1668 return splitAt(i, vec);
1669 }
1670 }
1671 return std::make_pair(fstVec, vec);
1672}
1673
1680template<typename T>
1681vector<T> replaceVec(T oldVal, T newVal, vector<T> vec) {
1682 vector<T> retVec(vec);
1683 std::replace(retVec.begin(), retVec.end(), oldVal, newVal);
1684 return retVec;
1685}
1686
1703template<typename T>
1704vector<T> insertAt(vector<T> vec, int pos, vector<T> insertVec) {
1705 assert(0 <= pos && pos <= vec.size());
1706 vector<T> v(vec);
1707 typename vector<T>::iterator it = v.begin();
1708 advance(it, pos);
1709 std::copy (insertVec.begin(),insertVec.end(),std::inserter(v,it));
1710 return v;
1711}
1712
1728vector<std::string> splitStrRegex(const string& s, string rgxStr = "\\s+") {
1729 vector<std::string> vec;
1730 regex rgx (rgxStr);
1731
1732 sregex_token_iterator iter(s.begin(), s.end(), rgx, -1);
1733 sregex_token_iterator end;
1734
1735 while (iter != end) {
1736 vec.push_back(*iter);
1737 ++iter;
1738 }
1739 return vec;
1740}
1741
1745bool isEmpty(string s) {
1746 return s.empty();
1747}
1748
1752bool isEmpty(const char* cpt) {
1753 if(cpt != NULL) {
1754 return strlen(cpt) == 0;
1755 } else {
1756 perror("cpt is NULL");
1757 exit(EXIT_FAILURE);
1758 }
1759 return false;
1760}
1761
1766double squareRoot(double a) {
1767 double x0 = a + 1;
1768 double x = x0;
1769 while(fabs(x*x - a) > 0.00000001) {
1770 x = x + (a - x*x)/(2*x);
1771 }
1772 return x;
1773}
1774
1780double intToDouble(int n) {
1781 return static_cast<double>(n);
1782}
1783
1790double nthRoot(double c, int n, double epsilon = 0.000001) {
1791
1792 // f(x) = x^{1/2}
1793 auto ff = [](double xx, int nn, double cc) {
1794 double nb = intToDouble(nn);
1795 return pow(xx, nb) - cc;
1796 };
1797
1798 // The first derivative of f(x)
1799 auto df = [](double xx, int nn, double cc) {
1800 double bb = intToDouble(nn - 1);
1801 return nn*pow(xx, bb);
1802 };
1803
1804 double b = intToDouble(n);
1805 double x = c + 1;
1806 while(fabs(pow(x, b) - c) > epsilon) {
1807 x = x - ff(x, n, c)/df(x, n, c);
1808 }
1809 return x;
1810}
1811
1812// KEY: char array to string, char arr to str
1813string charArrToString(const char* pt) {
1814 return cStringToString(pt);
1815}
1816
1817// TODO: find a better way to do it
1818// replicate n copy of s
1819string replicate(int n, string s) {
1820 string str = "";
1821 for(int i=0; i<n; i++) {
1822 str += s;
1823 }
1824 return str;
1825}
1826
1831string repeat(int n, string s) {
1832 return replicate(n, s);
1833}
1834
1835template<typename T>
1836vector<T> repeatVec(int n, T t) {
1837 vector<T> vec;
1838 for(int i=0; i<n; i++) {
1839 vec.push_back(t);
1840 }
1841 return vec;
1842}
1843
1844template<typename T>
1845void add(vector<T>& vec, T t){
1846 vec.push_back(t);
1847}
1848
1853int compareCString(char* s1, char* s2) {
1854 return strcmp(s1, s2);
1855}
1856
1861int compareString(string s1, string s2) {
1862 return s1.compare(s2);
1863}
1864
1865template<typename T>
1866bool compareVector(vector<T> v1, vector<T> v2){
1867 if(v1.size() == v2.size()){
1868 for(int i = 0; i < v1.size(); i++){
1869 if(v1[i] != v2[i]){
1870 return false;
1871 }
1872 }
1873 return true;
1874 }
1875 return false;
1876}
1877
1878template<typename T>
1879bool compareVector(vector<vector<T>> v1, vector<vector<T>> v2){
1880 if(v1.size() == v2.size()){
1881 for(int i = 0; i < v1.size(); i++){
1882 if(!compareVector(v1[i], v2[i])){
1883 return false;
1884 }
1885 }
1886 return true;
1887 }
1888 return false;
1889}
1890
1891
1895bool compareFloat(double a, double b) {
1896 double epsilon = 0.00001;
1897 return fabs(a-b) < epsilon;
1898}
1899
1900void print(glm::vec3 v3) {
1901 printf("%2.3f %2.3f %2.3f \n",v3.x, v3.y, v3.z);
1902}
1903void print(glm::vec2 v2) {
1904 printf("%2.3f %2.3f \n",v2.x, v2.y);
1905}
1906
1907void printLn(glm::vec3 v3) {
1908 printf("%2.3f %2.3f %2.3f ",v3.x, v3.y, v3.z);
1909}
1910void printLn(glm::vec2 v2) {
1911 printf("%2.3f %2.3f ",v2.x, v2.y);
1912}
1913
1914string toString(glm::vec3 v3) {
1915 char strPt[50];
1916 sprintf(strPt, "%2.3f %2.3f %2.3f", v3.x, v3.y, v3.z);
1917 return charArrToString(strPt);
1918}
1919
1955template<typename T>
1956vector<vector<T>> transpose(vector<vector<T>> mat) {
1957 vector<vector<T>> retMat;
1958 int min = INT_MAX;
1959 for(auto const& v : mat) {
1960 if(min > v.size())
1961 min = v.size();
1962 }
1963
1964 for(int i=0; i<min; i++) {
1965 vector<T> v;
1966 for(int k = 0; k < mat.size(); k++) {
1967 v.push_back(mat[k][i]);
1968 }
1969 retMat.push_back(v);
1970 }
1971 return retMat;
1972}
1973
1974int inx(int cIx, int rIx, int width){
1975 return cIx * width + rIx;
1976}
1977
1997void tranmat4(float arr[16]){
1998 int width = 4;
1999 for(int c = 0; c < width; c++){
2000 for(int r = c; r < width; r++){
2001 float tmp = arr[inx(c, r, width)];
2002 arr[inx(c, r, width)] = arr[inx(r, c, width)];
2003 arr[inx(r, c, width)] = tmp;
2004 }
2005 }
2006}
2007
2008
2009// Compare array, compare int array
2010template<typename T>
2011bool compareArray(T arr1[], T arr2[], const int s1) {
2012 for(int i=0; i<s1; i++) {
2013 if(arr1[i] != arr2[i])
2014 return false;
2015 }
2016 return true;
2017}
2018
2019template<typename T>
2020void print(std::pair<T, T> pair) {
2021 cout<<"("<<pair.first<<" "<<pair.second<<")"<<endl;
2022}
2023
2024template<typename T>
2025void print(two<T, T> t) {
2026 cout<<"("<<t.x<<" "<<t.y<<")";
2027}
2028
2029
2030template<typename T>
2031void print(vector<T> vec) {
2032 for(auto const& v: vec) {
2033 std::cout<<v<<" ";
2034 }
2035
2036 std::cout<<std::endl;
2037}
2038
2039template<typename T>
2040void printVec(vector<T> vec) {
2041 print(vec);
2042}
2043
2044template<typename T>
2045void print(vector< vector<T> > vec) {
2046 for(auto const& v: vec) {
2047 print(v);
2048 }
2049 std::cout<<std::endl;
2050}
2051
2052
2053template<typename T>
2054void print(T t) {
2055 // std::cout<<"["<<t<<"];"
2056 std::cout<<t;
2057}
2058
2059
2063template<typename T>
2064void printNb(T t) {
2065 std::cout<<t;
2066}
2067
2068template<typename T>
2069void printLn(T t) {
2070 std::cout<<"["<<t<<"]"<<std::endl;
2071}
2072
2073template<typename T>
2074void printLnNb(T t) {
2075 std::cout<<t<<std::endl;
2076}
2077
2078
2079
2080template<typename T>
2081void ppL(T t) {
2082 printLn(t);
2083}
2084
2085
2086void printArr(float arr[10], int n, int nCol){
2087 for(int i = 0; i < n; i++){
2088 if((i + 1) % nCol != 0){
2089 cout<<arr[i]<<" ";
2090 }else{
2091 cout<<arr[i]<<" "<<endl;
2092 }
2093 }
2094}
2095
2099template<typename T>
2100vector<T> concatVec(vector<T> v1, vector<T> v2){
2101// vector<T> concatVec(vector<T>& v1, vector<T>& v2){
2102 return v1 + v2;
2103}
2104
2110template<typename T>
2111vector<T> operator+(vector<T> v1, vector<T> v2) {
2112 vector<T> vec(v1);
2113 vec.insert(vec.end(), v2.begin(), v2.end());
2114 return vec;
2115}
2116
2117string operator+(const char* chars, string s) {
2118 return charArrToString(chars) + s;
2119}
2120
2121string operator+(string s, const char* chars) {
2122 return s + charArrToString(chars);
2123}
2124
2125template<typename T>
2126vector<T> con(T t, vector<T> v) {
2127 vector<T> vec;
2128 vec.push_back(t);
2129 for(auto const& e: v)
2130 vec.push_back(e);
2131 return vec;
2132}
2133
2138template<typename T>
2139vector<T>* moveVec(T a, vector<T> vec) {
2140 vector<T>* pt = new vector<T>();
2141 for(auto const& val: vec) {
2142 pt -> push_back(val);
2143 }
2144 pt -> push_back(a);
2145 return std::move(pt);
2146}
2147
2148int unsignToInt(size_t u){
2149 if(u > std::numeric_limits<int>::max()){
2150 throw std::overflow_error("ERROR: size_t > int");
2151 }
2152 return static_cast<int>(u);
2153}
2154
2161template<typename T>
2162vector<T>* append(vector<T> vec, T a) {
2163 vector<T>* pt = new vector<T>();
2164 for(auto const& val: vec) {
2165 pt -> push_back(val);
2166 }
2167 pt -> push_back(a);
2168 return std::move(pt);
2169}
2170
2174int length(string s){
2175 return unsignToInt(s.size());
2176}
2177
2178
2179
2180
2184template<typename T>
2185int length(vector<T> v){
2186 return unsignToInt(v.size());
2187}
2188
2192int len(string s){
2193 return length(s);
2194}
2195
2199template<typename T>
2200int len(vector<T> v){
2201 return length(v);
2202}
2203
2215template<typename T>
2216bool binSearch(T key, T arr[], int lo, int hi){
2217 if(lo < hi){
2218 int mid = (lo + hi)/2;
2219 if(key < arr[mid]){
2220 return binSearch(key, arr, lo, mid - 1);
2221 }else{
2222 return binSearch(key, arr, mid + 1, hi);
2223 }
2224 }else if(lo == hi){
2225 return key == arr[lo];
2226 }
2227 return false;
2228}
2229
2235template<typename T>
2236vector<T> operator*(T a, vector<T> vec) {
2237 vector<T> newVec;
2238 for(auto const& value: vec) {
2239 newVec.push_back(a*value);
2240 }
2241 return newVec;
2242}
2243
2249template<typename T>
2250vector<T> operator*(vector<T> vec, T a) {
2251 vector<T> newVec;
2252 for(auto const& value: vec) {
2253 newVec.push_back(a*value);
2254 }
2255 return newVec;
2256}
2257
2258template<typename T>
2259vector< vector<T> > operator*(T a, vector< vector<T> > vec2) {
2260 vector< vector<T> > newVec2;
2261 vector<T> vec;
2262 for(auto const& vec : vec2) {
2263 newVec2.push_back(a*vec);
2264 }
2265 return newVec2;
2266}
2267
2268template<typename T>
2269vector< vector<T> > operator*(vector< vector<T> > vec2, T a) {
2270 return a*vec2;
2271}
2272
2273
2281template<typename T>
2282vector<T> reverseVec(vector<T> vec){
2283 vector<T> v(vec);
2284 std::reverse(v.begin(), v.end());
2285 return v;
2286}
2287
2288
2289// Thanks for the default parameter
2290vector<int> range(int a, int b) {
2291 int stride = 1;
2292 vector<int> vec;
2293 for(int i=a; i<=b; i += stride)
2294 vec.push_back(i);
2295 return vec;
2296}
2297
2298vector<int> range(int a, int b, int stride) {
2299 vector<int> vec;
2300 for(int i=a; i<=b; i += stride)
2301 vec.push_back(i);
2302 return vec;
2303}
2304
2305// generate vector double
2306vector<int> geneVector(int a, int b) {
2307 int len = b - a;
2308 std::vector<int> vec;
2309 for(int i=0; i<=len; i++) {
2310 vec.push_back(a + i);
2311 }
2312 return vec;
2313}
2314
2320bool isBST(Node<int>* curr, Node<int>* &prev){
2321 if(curr != NULL){
2322 if(!isBST(curr -> left, prev))
2323 return false;
2324 if(prev != NULL && prev -> data > curr -> data)
2325 return false;
2326 prev = curr;
2327 if(!isBST(curr -> right, curr))
2328 return false;
2329 }
2330 return true;
2331}
2332
2337template<typename T>
2338vector< vector<T> > geneMatrix(int ncol, int nrow, T init) {
2339 vector< vector<T> > vv;
2340 T val = init;
2341 for(int c=0; c<ncol; c++) {
2342 vector<T> tv;
2343 for(int r=0; r<nrow; r++) {
2344 tv.push_back(val);
2345 val++;
2346 }
2347 vv.push_back(tv);
2348 }
2349 return vv;
2350}
2351
2352// swap array
2353template<typename T>
2354void swapT(T array[], int i, int j) {
2355 T tmp = array[i];
2356 array[i] = array[j];
2357 array[j] = tmp;
2358}
2359
2366template<typename T>
2367int partitionT(T array[], int lo, int hi) {
2368 if(hi > lo) {
2369 T p = array[hi];
2370 int bInx = lo;
2371 for(int i=lo; i<=hi; i++) {
2372 if(array[i] <= p) {
2373 if(i != bInx){
2374 swapT(array, i, bInx);
2375 }
2376
2377 if(i < hi){
2378 bInx++;
2379 }
2380 }
2381 }
2382 return bInx;
2383 }
2384 return lo;
2385}
2386
2387// 2 3
2388// i = 0
2389// j=1
2390
2396template<typename T>
2397T partition(vector<T>& vec, int lo, int hi){
2398 if(lo < hi){
2399 T pivot = vec[hi];
2400 vector<T> tmp(hi - lo + 1);
2401 int i = lo;
2402 int j = hi;
2403 for(int k = 0; k < len(vec) && i != j; k++){
2404 if(vec[k] < pivot){
2405 tmp[i] = vec[k];
2406 i++;
2407 }else{
2408 tmp[j] = vec[k];
2409 j--;
2410 }
2411 }
2412 tmp[i] = pivot;
2413
2414 for(int k=0; k < len(tmp); k++)
2415 vec[lo + k] = tmp[k];
2416
2417 return i;
2418 }else{
2419 return lo;
2420 }
2421}
2422
2433template<typename T>
2434int partitionInline(vector<T>& vec, int lo, int hi){
2435 int bigInx = lo;
2436 if(lo <= hi){
2437 T pivot = vec[hi];
2438 for(int i = lo; i <= hi; i++){
2439 if(vec[i] <= pivot){
2440 if (i != bigInx){
2441 swap(vec, i, bigInx);
2442 }
2443 if(bigInx < hi){
2444 bigInx++;
2445 }
2446 }
2447 }
2448 }
2449 return bigInx;
2450}
2451
2452template<typename T>
2453void quickSortVec(vector<T>& vec, int lo, int hi){
2454 if(lo < hi){
2455 int pInx = partitionInline(vec, lo, hi);
2456 quickSortVec(vec, lo, pInx - 1);
2457 quickSortVec(vec, pInx + 1, hi);
2458 }
2459}
2460
2464template<typename T>
2465void quickSortT(T array[], int lo, int hi) {
2466 if(hi > lo) {
2467 int pInx = partitionT(array, lo, hi);
2468 quickSortT(array, lo, pInx - 1);
2469 quickSortT(array, pInx + 1, hi);
2470 }
2471}
2472
2473std::string replace(std::string str, regex rex, std::string rep){
2474 return std::regex_replace (str, rex, rep);
2475}
2476
2477bool isEmptyLine(string s){
2478 regex rx("\\s+");
2479 string str = replace(s, rx, "");
2480 return len(str) == 0;
2481}
2482
2483// get environment variable
2484string getEnv(string env){
2485 const char* pt = std::getenv(s2c(env));
2486 return c2s(pt);
2487}
2488
2489template<typename T>
2490vector<T> getCol(int ix, vector<vector<T>> v){
2491 vector<vector<T>> tv = transpose(v);
2492 if(0 <= ix && ix < tv.size()){
2493 return tv[ix];
2494 }else{
2495 printf("ERROR: Invalid index=%d\n", ix);
2496 }
2497}
2498
2499
2510string concatValidPath(vector<string> vec){
2511 string s = AronLambda::foldl([](string x, string y) { return x + "/" + y;}, c2s(""), vec);
2512 return removeAdjacentDuplicateChar(s, '/');
2513}
2514
2524string removeAdjacentDuplicateChar(string s, char c){
2525 string ret;
2526 if(len(s) > 0) {
2527 ret.push_back(s[0]);
2528 for (int i = 0; i + 1 < len(s); i++) {
2529 if (s[i] != s[i + 1]) {
2530 ret.push_back(s[i + 1]);
2531 }else{
2532 if(c != s[i + 1])
2533 ret.push_back(s[i + 1]);
2534 }
2535 }
2536 }
2537 return ret;
2538}
2539
2540#if 1
2541namespace SpaceTest {
2542using namespace AronPrint;
2543
2544 static void t(double a, double b, string s = "") {
2545 bool ret = compareFloat(a, b);
2546 if(ret)
2547 pp("True => " + s);
2548 else{
2549 pp(a, b);
2550 pp("False => " + s);
2551 }
2552 nl();
2553 }
2554 static void t(int a, int b, string s = "") {
2555 if(a == b)
2556 pp("True => " + s);
2557 else{
2558 pp(a, b);
2559 pp("False => " + s);
2560 }
2561 nl();
2562 }
2563 static void t(long a, long b, string s = "") {
2564 if(a == b)
2565 pp("True => " + s);
2566 else{
2567 pp(a, b);
2568 pp("False => " + s);
2569 }
2570 nl();
2571 }
2572 static void t(bool a, bool b, string s = "") {
2573 if(a == b)
2574 pp("True=> " + s);
2575 else{
2576 pp(a, b);
2577 pp("False => " + s);
2578 }
2579 nl();
2580 }
2581 static void t(string a, string b, string s = "") {
2582 if(a == b)
2583 pp("True => " + s);
2584 else{
2585 pp(a, b);
2586 pp("False => " + s);
2587 }
2588 nl();
2589 }
2590
2591 template<typename T>
2592 static void t(vector<T> v1, vector<T> v2, string s = "") {
2593 if(compareVector(v1, v2)){
2594 pp("True => " + s);
2595 }else{
2596 printVec(v1);
2597 printVec(v2);
2598 pp("False => " + s);
2599 }
2600 nl();
2601 }
2602
2603 template<typename T>
2604 static void t(vector<vector<T>> v1, vector<vector<T>> v2, string s = "") {
2605 if(compareVector(v1, v2)){
2606 pp("True => " + s);
2607 }else{
2608 print(v1);
2609 print(v2);
2610 pp("False => " + s);
2611 }
2612 nl();
2613 }
2614}; // end SpaceTest
2615#endif
2616
2617// all the geometry functions here
2618
2619namespace AronGeometry {
2620using namespace AronPrint;
2621
2622template<class T = double> class Vector;
2623
2624template<class T = double>
2625class Point {
2626public:
2627 T x;
2628 T y;
2629 T z;
2630 Point() {
2631 x = 0.0;
2632 y = 0.0;
2633 z = 0.0;
2634 }
2635 Point(T x, T y, T z = 0.0 ) {
2636 this->x = x;
2637 this->y = y;
2638 this->z = z;
2639 }
2640
2641 friend Point<T> operator+(Point<T> p1, Point<T> p2) {
2642 Point<T> p(p1.x + p2.x, p1.y + p2.y, p1.z + p2.z);
2643 return p;
2644 }
2645 friend Point<T> operator-(Point<T> p1, Point<T> p2) {
2646 Point<T> p(p1.x - p2.x, p1.y - p2.y, p1.z - p2.z);
2647 return p;
2648 }
2649 friend Point<T> operator*(double k, Point<T> p) {
2650 Point<T> p1(k*p.x, k*p.y, k*p.z);
2651 return p1;
2652 }
2653 friend Point<T> operator*(Point<T> p, double k) {
2654 return k*p;
2655 }
2656
2657
2658 // TODO: add test
2659 Point<T> operator+(Vector<T> v) {
2660 Point p(x + v.x, y + v.y, z + v.z);
2661 return p;
2662 }
2663 bool operator==(Point p0) {
2664 return x == p0.x && y == p0.y && z == p0.z;
2665 }
2666 bool operator!=(Point p0) {
2667 return x != p0.x || y != p0.y || z != p0.z;
2668 }
2669};
2670
2671
2672/*
2673 /Library/WebServer/Documents/zsurface/pdf/colinear_point.pdf
2674
2675 p on segment p1 p2 => return 0
2676 p on one side of segment p1 p2 => return > 0
2677 p on other size of segment p1 p2 => return < 0
2678*/
2679
2680template<class T>
2681class Pair {
2682public:
2683 Point<T> p0;
2684 Point<T> p1;
2685 Pair(Point<T> p0, Point<T> p1) {
2686 this -> p0 = p0;
2687 this -> p1 = p1;
2688 }
2689public:
2690 Pair operator+(Pair pair) {
2691 Pair pa(this -> p0 + pair.p0, this -> p1 + pair.p1);
2692 return pa;
2693 }
2694 Pair operator-(Pair pair) {
2695 Pair pa(this -> p0 - pair.p0, this -> p1 - pair.p1);
2696 return pa;
2697 }
2698};
2699
2700
2701
2702template<class T>
2703class Vector {
2704public:
2705 Point<T> p0; // origin
2706 Point<T> p1;
2707public:
2708 Vector(Point<T> p0, Point<T> p1) {
2709 this -> p0 = p0;
2710 this -> p1 = p1;
2711 }
2712
2713 bool isZero() {
2714 return p0 == p1;
2715 }
2716 Vector<T> dir() {
2717 // affine formula
2718 // vector: p0 -> p1 = p1 - p0
2719 return p1 - p0;
2720 }
2721
2722 // v1 + v1' =
2723 // v1 = p1 - p0
2724 // v1' = p1' - p0'
2725 // v1 + v1' = (p1 - p0) + (p1' - p0')
2726 // Affine axiom:
2727 // there is unique map f such as
2728 // f:(S, V) -> S
2729 // a + v = bf
2730 Vector<T> operator+(Vector<T> v) {
2731 Vector<T> v1(p0 + v.p0, p1, v.p1);
2732 return v1;
2733 }
2734};
2735
2736
2737template<class T = double>
2738class Segment {
2739public:
2740 Point<T> p0;
2741 Point<T> p1;
2742public:
2743 /*
2744 Segment definition:
2745 1. p0 != p2
2746 */
2747 Segment(Point<T> p0, Point<T> p1) {
2748 if(p0 != p1) {
2749 this -> p0 = p0;
2750 this -> p1 = p1;
2751 } else {
2752 pp("some error");
2753 }
2754 }
2755
2756 double squareDist() {
2757 double d = (p1.x - p0.x)*(p1.x - p0.x) +
2758 (p1.y - p0.y)*(p1.y - p0.y);
2759 return d;
2760 }
2761 double distance() {
2762 double d = (p1.x - p0.x)*(p1.x - p0.x) +
2763 (p1.y - p0.y)*(p1.y - p0.y);
2764 return sqrt(d);
2765 }
2766 bool isColinear(Point<T> p) {
2767 return isColinear3(p, p0, p1) == 0;
2768 }
2769
2770 /*
2771 1. If two segment are the same, return false
2772 2. If one end point of segment on other segment, return true
2773 3.
2774 */
2775 bool isCrossSegment(Segment<T> s1, Segment<T> s2) {
2776 return true;
2777 }
2778 bool isEndPoint(Point<T> p) {
2779 return p == p0 || p == p1;
2780 }
2781 bool operator==(Segment<T> s) {
2782 return (p0 == s.p0 && p1 = s.p1) || (p1 = s.p0 && p0 == s.p1);
2783 }
2784};
2785
2786template<class T = double>
2787double isColinear3(Point<T> p, Point<T> p1, Point<T> p2) {
2788 // TODO: ignore z for now
2789 return (p2.y - p.y)*(p2.x - p1.x) - (p2.x - p.x)*(p2.y - p1.y);
2790}
2791template<class T = double>
2792bool isCrossSegment(Point<T> p0, Point<T> p1) {
2793 bool ret = false;
2794 return ret;
2795}
2796
2797} // send AronGeometry
2798
2799
2800
2801
2802
2803
2810namespace Utility {
2811using namespace AronPrint;
2812
2813// void fl();
2814
2825bool isSubstring(string sub, string s){
2826 bool ret = false;
2827 if(isEmpty(sub)){
2828 // sub.length() == 0
2829 ret = true;
2830 }else if(sub.length() > 0 && sub.length() <= s.length()){
2831 // sub.length() > 0
2832 //
2833 // abcd
2834 // bc
2835 // bc
2836 int j = 0;
2837 int count = 0;
2838 for(int i=0; i < s.length() && ret == false; i++){
2839 count = 0;
2840 j = 0;
2841 while(j < sub.length() && i + count < s.length() && sub[j] == s[i + count]){
2842 j++;
2843 count++;
2844 if(count == sub.length()){
2845 ret = true;
2846 break;
2847 }
2848 }
2849 }
2850 }
2851 return ret;
2852}
2853
2864int substringFirstIndex(string sub, string s){
2865 int ret = -1;
2866 if(isEmpty(sub)){
2867 // sub.length() == 0
2868 }else if(sub.length() > 0 && sub.length() <= s.length()){
2869 // sub.length() > 0
2870 //
2871 // abcd
2872 // bc
2873 // bc
2874 int j = 0;
2875 int count = 0;
2876 for(int i=0; i < s.length() && ret == -1; i++){
2877 count = 0;
2878 j = 0;
2879 while(j < sub.length() && i + count < s.length() && sub[j] == s[i + count]){
2880 j++;
2881 count++;
2882 if(count == sub.length()){
2883 ret = i;
2884 break;
2885 }
2886 }
2887 }
2888 }
2889 return ret;
2890}
2891
2892
2893
2894
2895string fun_parent_parent();
2896void cut(char* pt);
2897
2898
2899int stringToInt(string s) {
2900 return stoi(s);
2901}
2902
2903
2904
2905// KEY: string to double
2906double stringToDouble(std::string s) {
2907 return stod(s);
2908}
2909
2910// KEY: string to long
2911long stringToLong(std::string s) {
2912 return stol(s);
2913}
2914
2915// KEY: string to float
2916float stringToFloat(std::string s) {
2917 return stof(s);
2918}
2919
2920// KEY: char to string
2921string charToString(char ch) {
2922 string s;
2923 s.push_back(ch);
2924 return s;
2925}
2926
2927// KEY: padding string
2928void begin() {
2929 int sz = 80;
2930 std::string pretty_fun = fun_parent_parent();
2931 int len = pretty_fun.length();
2932 printf ("[%s%.*s]\n", pretty_fun.c_str(), sz < len ? 0 : (int)(sz - len), PAD);
2933}
2934
2935// KEY: padding string
2936void begin(const char* name) {
2937 int sz = 80;
2938 printf ("[%s%.*s]\n", name, (sz < strlen(name)) ? 0 : (int)(sz - strlen(name)), PAD);
2939}
2940
2941void end() {
2942 fl();
2943}
2944
2945void cut(char* pt) {
2946 int k = strlen(pt) - 1;
2947 while(k >= 0 && pt[k] != 'v') k--;
2948
2949 k >= 0 ? pt[k] = 0 : printf("Error: invalid string format.");
2950}
2951
2952// get the name of parent function, get the name of caller function
2953string fun_parent() {
2954 void *array[10];
2955 size_t size;
2956 char **strings;
2957
2958 size = backtrace (array, 10);
2959 strings = backtrace_symbols (array, size);
2960
2961 cut(strings[1]);
2962 string str = std::string(strings[1] + 62);
2963 free(strings);
2964 return str;
2965}
2966
2967// get name of caller of caller function, get the name of parent of parent function
2968string fun_parent_parent() {
2969 void *array[10];
2970 size_t size;
2971 char **strings;
2972
2973 size = backtrace (array, 10);
2974 strings = backtrace_symbols (array, size);
2975
2976 cut(strings[2]);
2977 string str = std::string(strings[2] + 62);
2978 free (strings);
2979 return str;
2980}
2981
2982void print(Vector3 v) {
2983 v.print();
2984}
2985
2986void print(DDLinkedList<Vector3>* ddl) {
2987 Node<Vector3>* curr = ddl->head;
2988 while(curr) {
2989 curr->data.print();
2990 curr = curr->next;
2991 }
2992}
2993
2994}; // end class Utility
2995
2996// TODO: delete it
2997//namespace SpaceDraw {
2998//class Cube {
2999//public:
3000// float x = 1.0f;
3001// float y;
3002// float z;
3003// float r;
3004//
3005// GLfloat vertices[108] = { 1, 1, 1, -1, 1, 1, -1,-1, 1, // v0-v1-v2 (front)
3006// -1,-1, 1, 1,-1, 1, 1, 1, 1, // v2-v3-v0
3007//
3008// 1, 1, 1, 1,-1, 1, 1,-1,-1, // v0-v3-v4 (right)
3009// 1,-1,-1, 1, 1,-1, 1, 1, 1, // v4-v5-v0
3010//
3011// 1, 1, 1, 1, 1,-1, -1, 1,-1, // v0-v5-v6 (top)
3012// -1, 1,-1, -1, 1, 1, 1, 1, 1, // v6-v1-v0
3013//
3014// -1, 1, 1, -1, 1,-1, -1,-1,-1, // v1-v6-v7 (left)
3015// -1,-1,-1, -1,-1, 1, -1, 1, 1, // v7-v2-v1
3016//
3017// -1,-1,-1, 1,-1,-1, 1,-1, 1, // v7-v4-v3 (bottom)
3018// 1,-1, 1, -1,-1, 1, -1,-1,-1, // v3-v2-v7
3019//
3020// 1,-1,-1, -1,-1,-1, -1, 1,-1, // v4-v7-v6 (back)
3021// -1, 1,-1, 1, 1,-1, 1,-1,-1
3022// }; // v6-v5-v4
3023//
3024// Cube() {
3025// }
3026// Cube(float x1, float y1, float z1, float r1=1.0) {
3027// x = x1;
3028// y = y1;
3029// z = z1;
3030// r = r1;
3031// }
3032//
3033// void draw() {
3034// glEnable(GL_DEPTH_TEST);
3035// glLightfv(GL_LIGHT0, GL_DIFFUSE, WHITE);
3036// glLightfv(GL_LIGHT0, GL_SPECULAR, RED);
3037// glMaterialfv(GL_FRONT, GL_SPECULAR, MAGENTA);
3038// glMaterialf(GL_FRONT, GL_SHININESS, 10);
3039// glEnable(GL_LIGHTING);
3040// glEnable(GL_LIGHT0);
3041//
3042// GLfloat lightPosition[] = {4, 3, 7, 1};
3043// glLightfv(GL_LIGHT0, GL_POSITION, lightPosition);
3044// glNormal3d(0, 1, 0);
3045// // enble and specify pointers to vertex arrays
3046// glEnableClientState(GL_VERTEX_ARRAY);
3047// glVertexPointer(3, GL_FLOAT, 0, vertices);
3048// glPushMatrix();
3049// glDrawArrays(GL_TRIANGLES, 0, 36);
3050//
3051// glPopMatrix();
3052// glDisableClientState(GL_VERTEX_ARRAY); // disable vertex arrays
3053// }
3054//}; // end class Clube
3055//
3056// TODO: delete it
3057//class SimpleCoordinate {
3058//public:
3059// SimpleCoordinate() {
3060// }
3061//public:
3062// void draw(float width = 1.0, int num=10) {
3063// glBegin(GL_LINES);
3064// float delta = width/num;
3065// glColor3f(0.0f, width, 0.0f);
3066// for(int i=-num; i<=num; i++) {
3067// glVertex3f(-width, 0.0f, delta*i);
3068// glVertex3f(width, 0.0f, delta*i);
3069// }
3070//
3071// glColor3f(0.3f,0.7f,0.0f);
3072// for(int i=-num; i<=num; i++) {
3073// glVertex3f(-width, delta*i, 0.0f);
3074// glVertex3f(width, delta*i, 0.0f);
3075// }
3076//
3077// glColor3f(width, 0.0f,0.0f);
3078// for(int i=-num; i<=num; i++) {
3079// glVertex3f(0.0f, -width, delta*i);
3080// glVertex3f(0.0f, width, delta*i);
3081// }
3082//
3083// glColor3f(0.4f, 0.4f,0.1f);
3084// for(int i=-num; i<=num; i++) {
3085// glVertex3f(delta*i, -width, 0.0f);
3086// glVertex3f(delta*i, width, 0.0f);
3087// }
3088//
3089// glColor3f(0.0f, 0.0f, width);
3090// for(int i=-num; i<=num; i++) {
3091// glVertex3f(delta*i, 0.0f, -width);
3092// glVertex3f(delta*i, 0.0f, width);
3093// }
3094//
3095// glColor3f(0.0f, 0.5f, 0.5f);
3096// for(int i=-num; i<=num; i++) {
3097// glVertex3f(0.0f, delta*i, -width);
3098// glVertex3f(0.0f, delta*i, width);
3099// }
3100// glEnd();
3101// }
3102//
3103//}; // end class SimpleCoordinate
3104
3105
3106
3107
3108
3109
3116namespace SpaceComplex {
3117class Complex {
3118public:
3119 double x;
3120 double y;
3121
3126 x = 0.0;
3127 y = 0.0;
3128 }
3132 Complex(double x_, double y_) {
3133 x = x_;
3134 y = y_;
3135 }
3136
3141 Complex co;
3142 co.x = x + c.x;
3143 co.y = y + c.y;
3144 return co;
3145 }
3146
3151 Complex co;
3152 co.x = x - c.x;
3153 co.y = y - c.y;
3154 return co;
3155 }
3163 Complex c1(x*c.x - y*c.y, x*c.y + y*c.x);
3164 return c1;
3165 }
3166
3170 bool operator==(const Complex& c) {
3171 return x == c.x && y == c.y;
3172 }
3173 Complex conjugate() {
3174 Complex c1(x, -y);
3175 return c1;
3176 }
3177
3178 double norm(Complex& c) {
3179 return sqrt(c.x*c.x + c.y*c.y);
3180 }
3181
3182 std::pair<double, double> polar() {
3183 double radius = norm(*this);
3184 double radian = acos(x/radius);
3185 std::pair<double, double> pair = std::make_pair(radius, radian);
3186 return pair;
3187 }
3188
3189
3195 friend Complex operator/(const Complex& c1, const Complex& c2) {
3196 double xx = (c1.x*c2.x + c1.y*c2.y)/(c2.x*c2.x + c2.y*c2.y);
3197 double yy = (c2.x*c1.y - c1.x*c2.y)/(c2.x*c2.x + c2.y*c2.y);
3198 Complex c(xx, yy);
3199 return c;
3200 }
3201
3202
3206 void print() {
3207 printf("[%1.2f][%1.2f]\n", x, y);
3208 }
3209};
3210
3216Complex rectangular(std::pair<double, double> p) {
3217 Complex c( p.first*cos(p.second), p.first*sin(p.second) );
3218 return c;
3219}
3220
3221
3222
3223}; // end SpaceComplex
3224
3231namespace MatrixVector {
3232class row;
3233class mat;
3234
3244template<typename T>
3245T** allocateTemp(int ncol, int nrow) {
3246 T** arr = (T**)new T*[ncol];
3247 for(int c = 0; c < ncol; c++)
3248 arr[c] = (T*) new T[nrow];
3249 return arr;
3250}
3251
3258template<typename T>
3259T** allocate(int ncol, int nrow) {
3260 T** arr = (T**)new T*[ncol];
3261 for(int c = 0; c < ncol; c++)
3262 arr[c] = (T*) new T[nrow];
3263 return arr;
3264}
3265
3271template<typename T>
3272T** vecVecToArrArr(vector< vector<T> > vv) {
3273 int ncol = vv.size();
3274 assert(ncol > 0);
3275 int nrow = vv[0].size();
3276 T** arr = allocateTemp<T>(ncol, nrow);
3277 for(int c=0; c<ncol; c++) {
3278 for(int r=0; r<nrow; r++) {
3279 arr[c][r] = vv[c][r];
3280 }
3281 }
3282 return arr;
3283}
3284
3315template<typename T>
3316vector< vector<T> > arrArrToVecVec(T** arr, int ncol, int nrow) {
3317 vector< vector<T> > v;
3318 for(int c=0; c<ncol; c++) {
3319 vector<T> v1;
3320 for(int r=0; r<nrow; r++) {
3321 v1.push_back(arr[c][r]);
3322 }
3323 v.push_back(v1);
3324 }
3325 return v;
3326}
3327
3328
3329
3330mat concat(mat m1, mat m2);
3331
3332class vec {
3333public:
3334 int nrow;
3335 int ncol;
3336 float **arr;
3337 vec();
3338 vec(int r, int c);
3339 vec(const vec &v);
3340 vec(const vector<float> &v);
3341 ~vec();
3342 vec operator+(vec v);
3343 bool operator==(const vec &v);
3344 vec& operator=(const vec &v);
3345 vec operator-(vec &v);
3346 mat operator*(row r);
3347 mat toMatrix();
3348 void print();
3349 row tran();
3350 mat multi();
3351 void createVec(float* arr, int len);
3352 vector<float> toVector();
3353 vector<float> toVec();
3354 int size();
3355};
3356
3357class row {
3358public:
3359 int ncol;
3360 int nrow;
3361 float** arr;
3362public:
3363 row();
3364 ~row();
3365 vec tran();
3366 float dot(vec& r);
3367 row(int row);
3368 row(const vector<float>& vec);
3369 row(int col, int row);
3370 row(const row& r);
3371 void createRow(float* array, int len);
3372 bool operator==(const row& v);
3373 row operator=(const row& r);
3374 float operator*(vec& v);
3375 row operator+(row& r);
3376 row operator-(row& r);
3377 row operator/(float f);
3378 vector<float> toVector();
3379 vector<float> toVec();
3380
3381 void print();
3382};
3383
3384vec::vec() {}
3385
3386// copy constructor
3387vec::vec(const vec& v) {
3388 ncol = v.ncol;
3389 nrow = v.nrow;
3390 arr = allocate<float>(ncol, nrow);
3391 for(int i=0; i<ncol; i++){
3392 arr[i][0] = v.arr[i][0];
3393 }
3394}
3395
3396vec::vec(const vector<float> &v){
3397 ncol = v.size();
3398 nrow = 1;
3399 arr = allocate<float>(ncol, nrow);
3400 cout<<"nrow="<<nrow<<endl;
3401 cout<<"ncol="<<ncol<<endl;
3402 for(int i=0; i < ncol; i++){
3403 arr[i][0] = v[i];
3404 }
3405}
3406
3410vec::vec(int col, int row=1) {
3411 ncol = col;
3412 nrow = row;
3413 arr = allocate<float>(ncol, nrow);
3414}
3415vec::~vec() {
3416 for(int i=0; i<ncol; i++) {
3417 if(arr[i] != NULL){
3418 delete[] arr[i];
3419 }
3420 }
3421 if(arr != NULL){
3422 delete[] arr;
3423 }
3424}
3425
3426int vec::size(){
3427 return ncol;
3428}
3432vector<float> vec::toVector() {
3433 vector<float> vec;
3434 for(int i=0; i<ncol; i++) {
3435 vec.push_back(arr[i][0]);
3436 }
3437 return vec;
3438}
3439vector<float> vec::toVec() {
3440 return toVector();
3441}
3442
3443vec vec::operator+(vec v) {
3444 assert(ncol == v.ncol);
3445 vec* v1 = new vec(ncol);
3446 for(int i=0; i<ncol; i++){
3447 v1->arr[i][0] = arr[i][0] + v.arr[i][0];
3448 }
3449 return *v1;
3450}
3451
3452vec vec::operator-(vec& v) {
3453 assert(ncol == v.ncol);
3454 vec* v1 = new vec(ncol);
3455 for(int i=0; i<ncol; i++)
3456 v1->arr[i][0] = arr[i][0] - v.arr[i][0];
3457
3458 return *v1;
3459}
3460
3461
3462bool vec::operator==(const vec& v) {
3463 bool ret = ncol == v.ncol;
3464 for(int i=0; i<ncol && ret; i++) {
3465 ret = arr[i][0] == v.arr[i][0];
3466 }
3467 return ret;
3468}
3469
3470// return reference for chaining. e.g. (a = (b = c))
3471vec& vec::operator=(const vec& v) {
3472 assert(ncol == v.ncol);
3473 // same object?
3474 if (this != &v) {
3475 arr = allocate<float>(v.ncol, v.nrow);
3476 for(int i=0; i<ncol; i++) {
3477 arr[i][0] = v.arr[i][0];
3478 }
3479 }
3480 return *this;
3481}
3482
3483void vec::createVec(float* array, int len) {
3484 for(int i=0; i<len; i++) {
3485 arr[i][0] = array[i];
3486 }
3487}
3488void vec::print() {
3489 for(int i=0; i<ncol; i++) {
3490 cout<<arr[i][0]<<std::endl;
3491 }
3492}
3493
3494row::row() {
3495}
3496row::row(int col, int row) {
3497 ncol = col;
3498 nrow = row;
3499 arr = allocate<float>(ncol, nrow);
3500}
3501row::row(int row) {
3502 ncol = 1;
3503 nrow = row;
3504 arr = allocate<float>(ncol, nrow);
3505}
3506row::row(const vector<float>& vec) {
3507 ncol = 1;
3508 nrow = (int)vec.size();
3509 arr = allocate<float>(ncol, nrow);
3510 for(int i=0; i<nrow; i++) {
3511 arr[0][i] = vec[i];
3512 }
3513}
3514row::~row() {
3515 for(int i=0; i<ncol; i++) {
3516 if(arr[i] != NULL)
3517 delete[] arr[i];
3518 }
3519 if(arr != NULL)
3520 delete[] arr;
3521}
3522// copy constructor
3523row::row(const row& rw) {
3524 ncol = rw.ncol;
3525 nrow = rw.nrow;
3526 arr = allocate<float>(ncol, nrow);
3527 for(int r=0; r<nrow; r++) {
3528 arr[0][r] = rw.arr[0][r];
3529 }
3530}
3531
3532row vec::tran() {
3533 row rw(nrow, ncol);
3534 for(int i=0; i<nrow; i++) {
3535 for(int j=0; j<ncol; j++) {
3536 rw.arr[i][j] = arr[j][i];
3537 }
3538 }
3539 return rw;
3540}
3541
3542vec row::tran() {
3543 vec v = vec(nrow, ncol);
3544 for(int i=0; i<ncol; i++) {
3545 for(int j=0; j<nrow; j++) {
3546 v.arr[j][i] = arr[i][j];
3547 }
3548 }
3549 return v;
3550}
3551
3556vector<float> row::toVector() {
3557 vector<float> vec;
3558 for(int i=0; i<nrow; i++) {
3559 vec.push_back(arr[0][i]);
3560 }
3561 return vec;
3562}
3563
3564vector<float> row::toVec() {
3565 return toVector();
3566}
3567
3568void row::print() {
3569 for(int i=0; i<nrow; i++) {
3570 cout<<arr[0][i]<<" ";
3571 }
3572 cout<<endl;
3573}
3574
3575
3576bool row::operator==(const row& r) {
3577 assert(nrow == r.nrow);
3578 bool ret = true;
3579 for(int i=0; i<nrow && ret; i++) {
3580 ret = arr[0][i] == r.arr[0][i];
3581 }
3582 return ret;
3583}
3584
3585row row::operator=(const row& r) {
3586 ncol = r.ncol;
3587 nrow = r.nrow;
3588 arr = allocate<float>(ncol, nrow);
3589 for(int i=0; i<nrow; i++) {
3590 arr[0][i] = r.arr[0][i];
3591 }
3592 return *this;
3593}
3594
3595void row::createRow(float* array, int len) {
3596 for(int i=0; i<len; i++) {
3597 arr[0][i] = array[i];
3598 }
3599}
3600
3601// Thu 15 Jun 10:35:28 2023
3602// TODO: Use template<typename T>
3603// T** arr
3604class mat {
3605public:
3606 int ncol;
3607 int nrow;
3608 float** arr;
3609 mat();
3610
3611 // copy constructor
3612 // called: mat m = m1 + m2;
3613 // mat m(ncol, nrow);
3614 mat(const mat& m);
3615 ~mat();
3616 mat(const int col, const int row);
3617 mat(vector< vector<float> > v2);
3618 mat(const int col, const int row, vector<float> v);
3629 class Loader{
3630 public:
3631 mat& m;
3632 int ix;
3633 Loader(mat& m, int ix) : m(m), ix(ix) {}
3634 Loader operator , (float x){
3635 assert(ix < m.ncol * m.nrow);
3636
3637 int u = ix / m.nrow;
3638 int v = ix % m.nrow;
3639 m.arr[u][v] = x;
3640 return Loader(m, ix + 1);
3641 }
3642 };
3643 Loader operator << (float x){
3644 assert(ncol > 0 && nrow > 0);
3645 arr[0][0] = x;
3646 return Loader(*this, 1);
3647 }
3648
3649 vector<vector<float>> toVecVec();
3650 vec getVec(int n);
3651 row getRow(int n);
3652 vec operator*(vec& v);
3653 mat operator*(mat m);
3654 mat operator=(const mat& m);
3655 bool operator==(const mat& m);
3656 mat operator+(mat m);
3657 mat operator-(const mat& m);
3658 mat operator/(float f);
3659 mat operator*(float f);
3660 mat removeRow(int index);
3661 mat removeVec(int index);
3662 mat insertVecNext(int index, vec v);
3663 mat insertVecPrevious(int index, vec v);
3664 mat clone();
3665 mat concat(mat m);
3666
3667
3668 mat rowMultiScala(int index, float f);
3669 mat vecMultiScala(int index, float f);
3670 mat swapRow(int inx1, int inx2);
3671
3672 // TODO: move to as normal functions
3673 void geneMat(int init);
3674
3675 // TODO: the method should be removed, there is geneMatRandom(int ncol, nrow, int fst, int snd)
3676 void geneMatRandom(int fst, int snd);
3677
3678 void print();
3679 string toStr();
3680 void print2();
3681 void zero();
3682 void identity();
3683 // check if the matrix is an identity matrix
3684 bool isId();
3685 // check if the matrix is zero matrix
3686 bool isZero();
3687 float det();
3688
3689 mat id();
3690
3697 mat subMatrix(int colIndex, int rowIndex);
3698
3704 mat transpose();
3705
3706 /*
3707 1 2 3 block(1, 1, 1, 2) => 5 6
3708 4 5 6
3709 */
3710 mat block(int colIndex, int clen, int rowIndex, int rlen);
3711 mat take(int len);
3712 mat drop(int len);
3713 mat init();
3714 mat tail();
3715// mat addVecAfter(int index, float f);
3716// mat rowAdd(int index, float f);
3717// mat rowSub(int index, float f);
3718// mat vecSub(int index, float f);
3719// mat subVec(int index, vec v);
3720// mat subRow(int index, row r);
3721// mat upperTri();
3722// mat lowerTri();
3723// bool isSymmetric();
3724// float trace();
3725// mat subMatrix(int col, int row);
3726
3727};
3728
3729mat::mat() {
3730 ncol = 0;
3731 nrow = 0;
3732 arr = NULL;
3733 cout<<"empty matrix";
3734}
3735void mat::zero() {
3736 for(int c=0; c<ncol; c++) {
3737 for(int r=0; r<nrow; r++) {
3738 arr[c][r] = 0;
3739 }
3740 }
3741}
3742
3743mat mat::id() {
3744 assert(ncol == nrow);
3745 mat m(nrow, ncol);
3746 m.identity();
3747 return m;
3748}
3749
3750// identity matrix
3751void mat::identity() {
3752 assert(ncol == nrow);
3753 for(int c=0; c<ncol; c++) {
3754 for(int r=0; r<nrow; r++) {
3755 if( c == r)
3756 arr[c][r] = 1;
3757 else
3758 arr[c][r] = 0;
3759 }
3760 }
3761}
3762
3763// m1 = [[1, 2],
3764// [3, 4]]
3765// m2 = [[1, 0],
3766// [0, 1]]
3767// m = concat(m1, m2)
3768// m = [[1, 2, 1, 0],
3769// [3, 4, 0, 1]]
3770mat::mat(const mat& m) {
3771 ncol = m.ncol;
3772 nrow = m.nrow;
3773 arr = allocate<float>(ncol, nrow);
3774 for(int c=0; c<ncol; c++) {
3775 for(int r=0; r<nrow; r++) {
3776 arr[c][r] = m.arr[c][r];
3777 }
3778 }
3779}
3780mat::mat(int col, int row) {
3781 ncol = col;
3782 nrow = row;
3783 arr = allocate<float>(ncol, nrow);
3784}
3785mat::mat(vector< vector<float> > v2){
3786 assert(v2.size() > 0 && v2[0].size() > 0);
3787 ncol = v2.size();
3788 nrow = v2[0].size();
3789 arr = allocate<float>(ncol, nrow);
3790 for(int c=0; c<ncol; c++){
3791 for(int r=0; r<nrow; r++)
3792 arr[c][r] = v2[c][r];
3793 }
3794}
3795mat::mat(int col, int row, vector<float> v){
3796 ncol = col;
3797 nrow = row;
3798 assert(ncol >= 0 && nrow >= 0 && v.size() == ncol*nrow);
3799 arr = allocate<float>(ncol, nrow);
3800 for(int c=0; c<ncol; c++){
3801 for(int r=0; r<nrow; r++)
3802 arr[c][r] = v[nrow*c + r];
3803 }
3804}
3805
3806mat::~mat() {
3807 for(int i=0; i<ncol; i++)
3808 delete[] arr[i];
3809
3810 delete[] arr;
3811}
3812
3813mat vec::toMatrix() {
3814 mat m(ncol, 1);
3815 for(int c=0; c<ncol; c++) {
3816 for(int r=0; r<nrow; r++) {
3817 m.arr[c][r] = arr[c][r];
3818 }
3819 }
3820 return m;
3821}
3822
3841 vector<int> vmax;
3842 for(int i = 0; i < nrow; i++){
3843 vector<int> vm;
3844 for(int j = 0; j < ncol; j++){
3845 vm.push_back(len(toStrVar(arr[j][i])));
3846 }
3847 vmax.push_back(max(vm));
3848 }
3849
3850 vector<vector<string>> vv;
3851 string pad = " ";
3852 for(int i = 0; i < nrow; i++){
3853 vector<string> vs;
3854 for(int j = 0; j < ncol; j++){
3855 string s = padRight(toStrVar(arr[j][i]), pad, vmax[i] + 1);
3856 vs.push_back(s);
3857 }
3858 vv.push_back(vs);
3859 }
3860 vector<vector<string>> rv = ::transpose(vv);
3861 ::print(rv);
3862}
3863
3864
3865
3866string mat::toStr() {
3867 string ret = "";
3868 for(int c=0; c<ncol; c++) {
3869 for(int r=0; r<nrow; r++) {
3870 ret += toStr2(arr[c][r]) + " ";
3871 // cout<<arr[c][r]<<" ";
3872 }
3873 ret += "\n";
3874 }
3875 return ret;
3876}
3877 vector<vector<float>> mat::toVecVec(){
3878 vector<vector<float>> vv;
3879 for(int c=0; c<ncol; c++) {
3880 vector<float> tv;
3881 for(int r=0; r<nrow; r++) {
3882 tv.push_back(arr[c][r]);
3883 }
3884 vv.push_back(tv);
3885 }
3886 return vv;
3887 }
3888
3889void mat::print2() {
3890 for(int c=0; c<ncol; c++) {
3891 for(int r=0; r<nrow; r++) {
3892 printf("[%*f]", 10, arr[c][r]);
3893 }
3894 printf("\n");
3895 }
3896}
3897
3902 assert(0 <= n && n < nrow);
3903 vec v(ncol);
3904 for(int i=0; i<ncol; i++) {
3905 v.arr[i][0] = arr[i][n];
3906 }
3907 return v;
3908}
3909
3913row mat::getRow(int index) {
3914 row r(1, nrow);
3915 for(int i=0; i<nrow; i++) {
3916 r.arr[0][i] = arr[index][i];
3917 }
3918 return r;
3919}
3920
3925 assert(nrow > 0 && index >= 0 && index < nrow);
3926 mat m(ncol, nrow - 1);
3927 for(int c=0; c<ncol; c++) {
3928 int k = 0;
3929 for(int r=0; r<nrow; r++) {
3930 if(index != r) {
3931 m.arr[c][k] = arr[c][r];
3932 k++;
3933 }
3934 }
3935 }
3936 return m;
3937}
3938
3943 assert(ncol == v.ncol && 0 <= index && index < nrow);
3944 mat mv = v.toMatrix();
3945 mat left = take(index + 1);
3946 mat right = drop(index + 1);
3947 mat cat = left.concat(mv).concat(right);
3948 return cat;
3949}
3950
3951/*
3952Add vector to the left of index
3953Shoud I change the name to insertVecLeft()
3954'left' is shorter than 'previous'
3955*/
3956mat mat::insertVecPrevious(int index, vec v) {
3957 assert(ncol == v.ncol && 0 <= index && index < nrow);
3958 mat mv = v.toMatrix();
3959 if (index == 0) {
3960 return mv.concat(*this);
3961 } else {
3962 mat left = take(index);
3963 mat right = drop(index);
3964 return left.concat(mv).concat(right);
3965 }
3966}
3967
3968mat mat::removeRow(int index) {
3969 assert(ncol > 0 && index >= 0 && index < ncol);
3970 mat m(ncol - 1, nrow);
3971 int k = 0;
3972 for(int c=0; c<ncol; c++) {
3973 if(index != c) {
3974 for(int r=0; r<nrow; r++) {
3975 m.arr[k][r] = arr[c][r];
3976 }
3977 k++;
3978 }
3979 }
3980 return m;
3981}
3982mat mat::operator+(mat m) {
3983 mat m1(ncol, nrow);
3984 for(int c=0; c<ncol; c++) {
3985 for(int r=0; r<nrow; r++) {
3986 m1.arr[c][r] = arr[c][r] + m.arr[c][r];
3987 }
3988 }
3989 return m1;
3990}
3991
3992mat mat::operator-(const mat &m) {
3993 mat m1(ncol, nrow);
3994 for(int c=0; c<ncol; c++) {
3995 for(int r=0; r<nrow; r++) {
3996 m1.arr[c][r] = arr[c][r] - m.arr[c][r];
3997 }
3998 }
3999 return m1;
4000}
4001mat mat::operator/(float f) {
4002 mat m1(ncol, nrow);
4003 for(int c=0; c<ncol; c++) {
4004 for(int r=0; r<nrow; r++) {
4005 m1.arr[c][r] = arr[c][r]/f;
4006 }
4007 }
4008 return m1;
4009}
4010
4011mat mat::operator*(float f) {
4012 mat m1(ncol, nrow);
4013 for(int c=0; c<ncol; c++) {
4014 for(int r=0; r<nrow; r++) {
4015 m1.arr[c][r] = arr[c][r]*f;
4016 }
4017 }
4018 return m1;
4019}
4020
4021
4029mat mat::subMatrix(int cStart, int rStart) {
4030 assert(cStart < ncol && rStart < nrow);
4031 int ncolt = ncol - cStart;
4032 int nrowt = nrow - rStart;
4033 mat m(ncolt, nrowt);
4034 for(int c=0; c<m.ncol; c++) {
4035 for(int r=0; r<m.nrow; r++) {
4036 m.arr[c][r] = arr[c + cStart][r + rStart];
4037 }
4038 }
4039 return m;
4040}
4041
4050 mat m = block(0, ncol, 0, len);
4051 return m;
4052}
4053
4062 mat m = block(0, ncol, len, nrow - len);
4063 return m;
4064}
4081 assert(ncol > 0 && nrow > 0);
4082 mat m = take(nrow - 1);
4083 return m;
4084}
4102 assert(ncol > 0 && nrow > 0);
4103 mat m = drop(1);
4104 return m;
4105}
4106
4107
4117mat mat::block(int cIndex, int clen, int rIndex, int rlen) {
4118 mat m(clen, rlen);
4119 for(int c=0; c<m.ncol; c++) {
4120 for(int r=0; r<m.nrow; r++) {
4121 m.arr[c][r] = arr[cIndex + c][rIndex + r];
4122 }
4123 }
4124 return m;
4125}
4126
4138 mat m(nrow, ncol);
4139 for(int c=0; c<ncol; c++) {
4140 for(int r=0; r<nrow; r++) {
4141 m.arr[r][c] = arr[c][r];
4142 }
4143 }
4144 return m;
4145}
4146
4147// two empty matrices are equal
4148bool mat::operator==(const mat& m) {
4149 bool ret = ncol == m.ncol && nrow == m.nrow ? true : false;
4150 for(int c=0; c<ncol && ret; c++) {
4151 for(int r=0; r<nrow && ret; r++) {
4152 ret = arr[c][r] == m.arr[c][r];
4153 }
4154 }
4155 return ret;
4156}
4157
4166void mat::geneMat(int init) {
4167 int n = init;
4168 for(int c=0; c<ncol; c++) {
4169 for(int r=0; r<nrow; r++) {
4170 arr[c][r] = n;
4171 n++;
4172 }
4173 }
4174}
4175
4189void mat::geneMatRandom(int fst, int snd){
4190 long r0 = 9947;
4191 long max = (long)(snd - fst);
4192 for(int c=0; c<ncol; c++) {
4193 for(int i=0; i<nrow; i++) {
4194 long r1 = lcgRandom(r0) + fst;
4195 arr[c][i] = r1;
4196 r0 = r1;
4197 }
4198 }
4199}
4200
4201mat vec::operator*(row rw) {
4202 // M(m,n) M(n,h) => M(m,h)
4203 assert(nrow == rw.ncol);
4204 mat m(ncol, rw.nrow);
4205 for(int c=0; c<m.ncol; c++) {
4206 for(int r=0; r<m.nrow; r++) {
4207 m.arr[c][r] = arr[c][0]*rw.arr[0][r];
4208 }
4209 }
4210 return m;
4211}
4212
4213mat vec::multi() {
4214 mat m(2, 2);
4215 return m;
4216}
4217
4218vec mat::operator*(vec &v) {
4219 assert(nrow == v.ncol);
4220 vec v1(ncol);
4221 for(int c=0; c<ncol; c++) {
4222 v1.arr[c][0] = getRow(c)*v;
4223 }
4224 return v1;
4225}
4226mat mat::operator*(mat m) {
4227 assert(nrow == m.ncol);
4228 mat m1(ncol, m.nrow);
4229 m1.zero();
4230 for(int r=0; r<nrow; r++) {
4231 m1 = m1 + getVec(r) * m.getRow(r);
4232 }
4233 return m1;
4234}
4235// c = (a = b) ?
4236mat mat::operator=(const mat& m) {
4237 if (this != &m) {
4238 ncol = m.ncol;
4239 nrow = m.nrow;
4240 arr = allocate<float>(ncol, nrow);
4241 for(int c=0; c<ncol; c++) {
4242 for(int r=0; r<nrow; r++) {
4243 arr[c][r] = m.arr[c][r];
4244 }
4245 }
4246 }
4247 return *this;
4248}
4249
4250mat mat::clone() {
4251 mat m(ncol, nrow);
4252 for(int c=0; c<ncol; c++) {
4253 for(int r=0; r<nrow; r++) {
4254 m.arr[c][r] = arr[c][r];
4255 }
4256 }
4257 return m;
4258}
4259// concate two matrices
4260mat mat::concat(mat m) {
4261 assert(ncol == m.ncol);
4262 mat m1(ncol, nrow + m.nrow);
4263 for(int c=0; c < ncol; c++) {
4264 for(int r=0; r < nrow + m.nrow; r++) {
4265 if (r < nrow)
4266 m1.arr[c][r] = arr[c][r];
4267 else {
4268 m1.arr[c][r] = m.arr[c][r - nrow];
4269 }
4270 }
4271 }
4272 return m1;
4273
4274// nrow = nrow + m.nrow;
4275// arr = allocate<float>(ncol, nrow);
4276// for(int c=0; c < ncol; c++){
4277// for(int r=0; r < nrow; r++){
4278// arr[c][r] = m1.arr[c][r];
4279// }
4280// }
4281}
4282
4283mat mat::rowMultiScala(int index, float f) {
4284 mat m(ncol, nrow);
4285 for(int c=0; c < ncol; c++) {
4286 for(int r=0; r < nrow; r++) {
4287 if(index != c) {
4288 m.arr[c][r] = arr[c][r];
4289 } else {
4290 m.arr[c][r] = arr[c][r]*f;
4291 }
4292 }
4293 }
4294 return m;
4295}
4296
4297mat mat::vecMultiScala(int index, float f) {
4298 mat m(ncol, nrow);
4299 for(int c=0; c < ncol; c++) {
4300 for(int r=0; r < nrow; r++) {
4301 if(r != index) {
4302 m.arr[c][r] = arr[c][r];
4303 } else {
4304 m.arr[c][r] = arr[c][r]*f;
4305 }
4306 }
4307 }
4308 return m;
4309}
4310
4314mat mat::swapRow(int inx1, int inx2){
4315 assert(0 <= inx1 && inx1 < ncol && 0 <= inx2 && inx2 < ncol);
4316 row r1 = getRow(inx1);
4317 row r2 = getRow(inx2);
4318 mat m(ncol, nrow);
4319 for(int c=0; c < ncol; c++) {
4320 for(int r=0; r < nrow; r++) {
4321 if(c == inx1){
4322 m.arr[c][r] = r2.arr[0][r];
4323 }else if(c == inx2){
4324 m.arr[c][r] = r1.arr[0][r];
4325 }else{
4326 m.arr[c][r] = arr[c][r];
4327 }
4328 }
4329 }
4330 return m;
4331}
4332
4333float row::dot(vec& v) {
4334 assert(nrow == v.ncol);
4335 float ret = 0.0;
4336 for(int i=0; i<nrow; i++) {
4337 ret += arr[0][i]*v.arr[i][0];
4338 }
4339 return ret;
4340}
4341
4342
4343
4344float row::operator*(vec& v) {
4345 return dot(v);
4346}
4347row row::operator+(row& r) {
4348 assert(nrow == r.nrow);
4349 row rw(ncol, nrow);
4350
4351 for(int i=0; i<nrow; i++) {
4352 rw.arr[0][i] = arr[0][i] + r.arr[0][i];
4353 }
4354 return rw;
4355}
4356row row::operator-(row& r) {
4357 assert(nrow == r.nrow);
4358 row rw(ncol, nrow);
4359
4360 for(int i=0; i<nrow; i++) {
4361 rw.arr[0][i] = arr[0][i] - r.arr[0][i];
4362 }
4363 return rw;
4364}
4365row row::operator/(float f) {
4366 row rw(ncol, nrow);
4367 for(int i=0; i<nrow; i++) {
4368 rw.arr[0][i] = arr[0][i]/f;
4369 }
4370 return rw;
4371}
4372mat concat(mat m1, mat m2) {
4373 assert(m1.ncol == m2.ncol);
4374
4375 mat m(m1.ncol, m1.nrow + m2.nrow);
4376 for(int c=0; c < m1.ncol; c++) {
4377 for(int r=0; r < m1.nrow + m2.nrow; r++) {
4378 if (r < m1.nrow)
4379 m.arr[c][r] = m1.arr[c][r];
4380 else {
4381 m.arr[c][r] = m2.arr[c][r - m1.nrow];
4382 }
4383 }
4384 }
4385 return m;
4386}
4387
4388mat identity(int n) {
4389 mat m(n, n);
4390 for(int c=0; c<n; c++) {
4391 for(int r=0; r<n; r++) {
4392 if( c == r)
4393 m.arr[c][r] = 1;
4394 else
4395 m.arr[c][r] = 0;
4396 }
4397 }
4398 return m;
4399}
4400
4417 assert(a.ncol == a.nrow && a.nrow == b.ncol);
4418
4419 vec x(a.ncol);
4420 for(int c=a.ncol - 1; c >= 0; c--) {
4421 float s = 0.0;
4422 for(int r= a.nrow - 1; r >=c; r--) {
4423 if(r == c) {
4424 x.arr[r][0] = (b.arr[c][0] - s)/a.arr[c][r];
4425 } else {
4426 s += a.arr[c][r]*x.arr[r][0];
4427 }
4428 }
4429 }
4430 return x;
4431}
4432
4460mat ltri(mat m, int index) {
4461 assert(0 <= index && index < m.nrow);
4462 mat im = identity(m.nrow);
4463 vec v = m.getVec(index);
4464
4465 // assume m.arr[index][index] != 0
4466 for(int c=m.ncol-1; c > index; c--) {
4467 im.arr[c][index] = - m.arr[c][index]/m.arr[index][index];
4468 }
4469 return im;
4470}
4471
4477std::pair<mat, mat> utri(mat m) {
4478 mat m4;
4479 mat m2 = m4;
4480 mat m1 = m;
4481 mat l = identity(m.ncol);
4482 for(int r = 0; r < m.nrow - 1; r++) {
4483 mat mt = ltri(m1, r);
4484 pl("what");
4485 l = mt*l; // L_k..L2L1
4486 m1 = l*m; // L_k..L2 (L1 A)
4487 }
4488 return std::make_pair(l, l*m);
4489}
4490
4491mat geneMat(int ncol, int nrow, int init){
4492 mat m(ncol, nrow);
4493 int count = init;
4494 for(int c=0; c<ncol; c++){
4495 for(int r=0; r<nrow; r++){
4496 m.arr[c][r] = count;
4497 count++;
4498 }
4499 }
4500 return m;
4501}
4502
4507mat geneMatRandom(int ncol, int nrow, int fst, int snd){
4508 mat m(ncol, nrow);
4509 for(int c=0; c<ncol; c++) {
4510 for(int r=0; r<nrow; r++) {
4511 m.arr[c][r] = random(snd - fst) + fst;
4512 // m.arr[c][r] = 9.7;
4513 }
4514 }
4515 m.print();
4516 return m;
4517}
4518
4519
4520
4521
4522}; // end MatrixVector
4523
4528namespace SpaceVector4 {
4529class Vector4 {
4530 float column[4];
4531public:
4532 const float e1[4] = {1.0f, 0.0f, 0.0f, 0.0f};
4533 const float e2[4] = {0.0f, 1.0f, 0.0f, 0.0f};
4534 const float e3[4] = {0.0f, 0.0f, 1.0f, 0.0f};
4535 const float e4[4] = {0.0f, 0.0f, 0.0f, 1.0f};
4536public:
4537
4542 column[0] = column[1] = column[2] = column[3] = 0.0f;
4543 }
4544
4545 Vector4(const Vector4& other) {
4546 this->column[0] = other.column[0];
4547 this->column[1] = other.column[1];
4548 this->column[2] = other.column[2];
4549 this->column[3] = other.column[3];
4550 }
4551
4552 Vector4(float x, float y, float z, float w = 1.0f) {
4553 this->column[0] = x;
4554 this->column[1] = y;
4555 this->column[2] = z;
4556 this->column[3] = w;
4557 }
4558 Vector4(const float arr[4]) {
4559 this->column[0] = arr[0];
4560 this->column[1] = arr[1];
4561 this->column[2] = arr[2];
4562 this->column[3] = arr[3];
4563 }
4564 Vector4(float arr[4]) {
4565 this->column[0] = arr[0];
4566 this->column[1] = arr[1];
4567 this->column[2] = arr[2];
4568 this->column[3] = arr[3];
4569 }
4570 bool operator==(const Vector4& rhs) {
4571 bool b0 = column[0] == rhs.column[0];
4572 bool b1 = column[1] == rhs.column[1];
4573 bool b2 = column[2] == rhs.column[2];
4574 bool b3 = column[3] == rhs.column[3];
4575 return (b0 && b1 && b2 && b3);
4576 }
4577 Vector4& operator=(const Vector4& rhs) {
4578 this->column[0] = rhs.column[0];
4579 this->column[1] = rhs.column[1];
4580 this->column[2] = rhs.column[2];
4581 this->column[3] = rhs.column[3];
4582 return *this;
4583 }
4584
4585 Vector4 operator+(Vector4& rhs) {
4586 Vector4 v;
4587 v.column[0] = this->column[0] + rhs.column[0];
4588 v.column[1] = this->column[1] + rhs.column[1];
4589 v.column[2] = this->column[2] + rhs.column[2];
4590 v.column[3] = 0.0f;
4591 return v;
4592 }
4593
4594 Vector4 operator-(Vector4& rhs) {
4595 Vector4 v;
4596 v.column[0] = this->column[0] - rhs.column[0];
4597 v.column[1] = this->column[1] - rhs.column[1];
4598 v.column[2] = this->column[2] - rhs.column[2];
4599 v.column[3] = 0.0f;
4600 return v;
4601 }
4602
4603 Vector4 operator/(float n) {
4604 Vector4 v;
4605 v.column[0] = column[0]/n;
4606 v.column[1] = column[1]/n;
4607 v.column[2] = column[2]/n;
4608 return v;
4609 }
4610
4611 float dot(Vector4& rhs) {
4612 Vector4 v;
4613 v.column[0] = column[0] * rhs.column[0];
4614 v.column[1] = column[1] * rhs.column[1];
4615 v.column[2] = column[2] * rhs.column[2];
4616 v.column[3] = column[3] * rhs.column[3];
4617 return v[0] + v[1] + v[2] + v[3];
4618 }
4619
4620 float cross(Vector4& rhs) {
4621 return 0.0;
4622 }
4623
4624 Vector4 normal() {
4625 Vector4 v;
4626 float norm = column[0]*column[0] +
4627 column[1]*column[1] +
4628 column[2]*column[2];
4629 float n = sqrtf(norm);
4630 return (*this)/n;
4631 }
4632
4633 // [] can't modify member variables
4634 const float& operator[](int index) const {
4635 return column[index];
4636 }
4637
4638 // [] can modify member variables
4639 float& operator[](int index) {
4640 return column[index];
4641 }
4642
4643 void pp() {
4644 print();
4645 }
4646 void print() {
4647 printf("x=[%1.2f]\ny=[%1.2f]\nz=[%1.2f]\nw=[%1.2f]\n\n", column[0], column[1], column[2], column[3]);
4648 }
4649};
4650}; // end SpaceVector4
4651
4652// C++14 only
4653// http://localhost:8080/snippet?id=s+c%2B%2B
4654#if __cplusplus >= 201402
4655
4705namespace SpaceMatrix4 {
4706using namespace SpaceVector4;
4707using namespace Utility;
4708
4709class Matrix4 {
4710 Vector4 mat[4];
4711public:
4712 Matrix4() {
4713 mat[0] = mat[1] = mat[2] = mat[3] = Vector4();
4714 }
4715
4716 // copy constructor
4717 Matrix4(const Matrix4& matrix) {
4718 mat[0] = matrix[0];
4719 mat[1] = matrix[1];
4720 mat[2] = matrix[2];
4721 mat[3] = matrix[3];
4722 }
4723
4724 Matrix4(Vector4 v0, Vector4 v1, Vector4 v2, Vector4 v3) {
4725 mat[0] = v0;
4726 mat[1] = v1;
4727 mat[2] = v2;
4728 mat[3] = v3;
4729 }
4730 Matrix4(float m[16]) {
4731 Vector4 v1({ m[0], m[1], m[2], m[3]});
4732 Vector4 v2({ m[4], m[5], m[6], m[7]});
4733 Vector4 v3({ m[8], m[9], m[10], m[11]});
4734 Vector4 v4({ m[12], m[13], m[14], m[15]});
4735 mat[0] = v1;
4736 mat[1] = v2;
4737 mat[2] = v3;
4738 mat[3] = v4;
4739 }
4740 Matrix4& operator=(const Matrix4& matrix) {
4741 mat[0] = matrix[0];
4742 mat[1] = matrix[1];
4743 mat[2] = matrix[2];
4744 mat[3] = matrix[3];
4745 return *this;
4746 }
4747
4748 bool operator==(const Matrix4& matrix) {
4749 bool b0 = mat[0] == matrix[0];
4750 bool b1 = mat[1] == matrix[1];
4751 bool b2 = mat[2] == matrix[2];
4752 bool b3 = mat[3] == matrix[3];
4753 return (b0 && b1 && b2 && b3);
4754 }
4755 // overload [] , const => member variables CAN NOT be modified
4756 const Vector4& operator[](int index) const {
4757 return mat[index];
4758 }
4759
4760 // overload [] , no const => member variables CAN be modified
4761 Vector4& operator[](int index) {
4762 return mat[index];
4763 }
4764 Matrix4 operator+(Matrix4& rhs) {
4765 Matrix4 m;
4766 m[0] = mat[0] + rhs[0];
4767 m[1] = mat[1] + rhs[1];
4768 m[2] = mat[2] + rhs[2];
4769 m[3] = mat[3] + rhs[3];
4770 return m;
4771 }
4772 Matrix4 operator-(Matrix4& rhs) {
4773 Matrix4 m;
4774 m[0] = mat[0] - rhs[0];
4775 m[1] = mat[1] - rhs[1];
4776 m[2] = mat[2] - rhs[2];
4777 m[3] = mat[3] - rhs[3];
4778 return m;
4779 }
4780
4781 // column vector
4782 Vector4 operator*(Vector4& vect4) {
4783 Vector4 row0(mat[0][0], mat[1][0], mat[2][0], mat[3][0]);
4784 Vector4 row1(mat[0][1], mat[1][1], mat[2][1], mat[3][1]);
4785 Vector4 row2(mat[0][2], mat[1][2], mat[2][2], mat[3][2]);
4786 Vector4 row3(mat[0][3], mat[1][3], mat[2][3], mat[3][3]);
4787
4788 row0.print();
4789 row1.print();
4790 row2.print();
4791 row3.print();
4792
4793 vect4.print();
4794 cout<<"["<<row0.dot(vect4)<<"]"<<std::endl;
4795 cout<<"["<<row1.dot(vect4)<<"]"<<std::endl;
4796 cout<<"["<<row2.dot(vect4)<<"]"<<std::endl;
4797 cout<<"["<<row3.dot(vect4)<<"]"<<std::endl;
4798
4799 Vector4 v(row0.dot(vect4), row1.dot(vect4), row2.dot(vect4), row3.dot(vect4));
4800 v.print();
4801 return v;
4802 }
4803
4804 // column vector
4805 Matrix4 operator*(Matrix4& matrix) {
4806 Matrix4 m;
4807 m[0] = (*this)*matrix[0];
4808 m[1] = (*this)*matrix[1];
4809 m[2] = (*this)*matrix[2];
4810 m[3] = (*this)*matrix[3];
4811 return m;
4812 }
4813 // [1, 2, 3, 0] => point at infinite
4814 // [1, 2, 3, 1] => normal point
4815 Matrix4 translate(float x, float y, float z) {
4816 Matrix4 m;
4817 mat[0][0] = 1;
4818 mat[1][1] = 1;
4819 mat[2][2] = 1;
4820 mat[3][3] = 1;
4821
4822 mat[3][0] = x;
4823 mat[3][1] = y;
4824 mat[3][2] = z;
4825 mat[3][3] = 1;
4826 return *this;
4827 }
4828 Matrix4 identity() {
4829 mat[0][0] = 1;
4830 mat[1][1] = 1;
4831 mat[2][2] = 1;
4832 mat[3][3] = 1;
4833 return *this;
4834 }
4835
4836 void pp() {
4837 print();
4838 }
4839 void print() {
4840 printf("[%1.2f][%1.2f][%1.2f][%1.2f]\n", mat[0][0], mat[1][0], mat[2][0], mat[3][0]);
4841 printf("[%1.2f][%1.2f][%1.2f][%1.2f]\n", mat[0][1], mat[1][1], mat[2][1], mat[3][1]);
4842 printf("[%1.2f][%1.2f][%1.2f][%1.2f]\n", mat[0][2], mat[1][2], mat[2][2], mat[3][2]);
4843 printf("[%1.2f][%1.2f][%1.2f][%1.2f]\n", mat[0][3], mat[1][3], mat[2][3], mat[3][3]);
4844 fl();
4845 }
4846};
4847}; // end SpaceMatrix4
4848
4855template<class T>
4856vector<T> interleave(const vector<T>& v1, const vector<T>& v2) {
4857 vector<T> vec;
4858 int len1 = v1.size();
4859 int len2 = v2.size();
4860 // vector<T> vec;
4861 for(int i=0; i<std::min(len1, len2); i++) {
4862 vec.push_back(v1[i]);
4863 vec.push_back(v2[i]);
4864 }
4865 return vec;
4866}
4867
4879using namespace AronPrint;
4880
4888string takeFileName(string path) {
4889 string s;
4890 // it works for MacOS so far, not windows
4891 vector<string> vec = splitStr(path, "/");
4892 if(vec.size() > 0) {
4893 s = AronLambda::last(vec);
4894 }
4895 return s;
4896}
4897
4915string takeDirectory(string path) {
4916 vector<string> vec = splitStr(path, "/");
4917 vector<string> vecDir = AronLambda::init(vec);
4918 vector<string> pathvec;
4919 int len = vecDir.size();
4920 vector<string> vv = interleave(vecDir, repeatVec(len, c2s("/")));
4921 if(!( AronLambda::head(vec).empty() && vecDir.size() == 1)) {
4922 pathvec = AronLambda::init(vv);
4923 } else {
4924 pathvec = vv;
4925 }
4926
4927 return AronLambda::foldr([](auto x, auto y) {
4928 return x + y;
4929 }, c2s(""), pathvec);
4930}
4931
4932
4933
4934template<typename T>
4935vector<T> interleave(vector<T> v1, vector<T> v2, vector<T> v3){
4936 vector<T> vec;
4937 int vlen = std::min(std::min(len(v1), len(v2)), len(v3));
4938 for(int i = 0; i < vlen; i++){
4939 vec.push_back(v1[i]);
4940 vec.push_back(v2[i]);
4941 vec.push_back(v3[i]);
4942 }
4943 return vec;
4944}
4945
4946
4954string takeExtension(string path) {
4955 auto vec = splitStr(path, ".");
4956 string ret;
4957 if(vec.size() > 1) {
4958 string dot(".");
4959 ret = dot + AronLambda::last(vec);
4960 }
4961 return ret;
4962}
4963
4974string join(vector<string>& vec) {
4975 return trimRight( AronLambda::foldr([](auto x, auto y) {
4976 return x + " " + y;
4977 }, c2s(""), vec));
4978}
4979
4980string joinNewLine(vector<string> vec) {
4981 return AronLambda::foldr([](auto x, auto y) {
4982 return x + " " + y;
4983 }, c2s("\n"), vec);
4984}
4985
4996string concatR(vector<string>& vec, string s) {
4997 return AronLambda::foldr([&s](auto x, auto y) {
4998 return x + s + y;
4999 }, c2s(""), vec);
5000}
5001
5013string concatL(vector<string>& vec, string s) {
5014 return AronLambda::foldl([&s](auto x, auto y) {
5015 return x + s + y;
5016 }, c2s(""), vec);
5017}
5018
5028vector<string> readFile(string fname) {
5029 std::ifstream file(fname);
5030 vector<string> retVec;
5031 if (file.is_open()) {
5032 std::string line;
5033 while(getline(file, line)) {
5034 retVec.push_back(line);
5035 }
5036 file.close();
5037 }
5038 return retVec;
5039}
5040
5041
5042vector<string> readFileBackward(string fname, int nline){
5043 vector<string> vec;
5044 char c;
5045 int maxChar = 1000;
5046 std::ifstream myFile(fname,std::ios::ate);
5047 std::streampos size = myFile.tellg();
5048 char* pt = (char*)malloc(maxChar*sizeof(char));
5049 int nx = 0;
5050 int k = 0;
5051 for(int i=1;i<=size && k < nline;i++){
5052 myFile.seekg(-i,std::ios::end);
5053 myFile.get(c);
5054 if(c != '\n'){
5055 pt[nx] = c;
5056 nx++;
5057 if(nx >= maxChar){
5058 printf("ERROR: nx > maxChar\n");
5059 printf("ERROR: readFileBackward(string fname, int nline)\n");
5060 break;
5061 }
5062 }else{
5063 pt[nx] = '\0';
5064 vec.push_back(reverseStr(c2s(pt)));
5065 free(pt);
5066 pt = (char*)malloc(maxChar*sizeof(char));
5067 nx = 0;
5068 k++;
5069
5070 // free(pt) ?
5071 }
5072 }
5073 return reverse(vec);
5074}
5075
5076
5092string readFileStream(const char* fpath){
5093 std::string vertexCode;
5094 std::ifstream vShaderFile;
5095 // ensure ifstream objects can throw exceptions:
5096 vShaderFile.exceptions (std::ifstream::failbit | std::ifstream::badbit);
5097 try {
5098 // open files
5099 vShaderFile.open(fpath);
5100 std::stringstream vShaderStream;
5101 // read file's buffer contents into streams
5102 vShaderStream << vShaderFile.rdbuf();
5103 // close file handlers
5104 vShaderFile.close();
5105 // convert stream into string
5106 vertexCode = vShaderStream.str();
5107 }
5108 catch (std::ifstream::failure& e) {
5109 std::cout << "ERROR::SHADER::FILE_NOT_SUCCESFULLY_READ" << std::endl;
5110 }
5111 return vertexCode;
5112}
5113
5119void listDirToFile(char * path, char* toFile, vector<string>& vec) {
5120 DIR * d = opendir(path);
5121 if( d != NULL) {
5122 struct dirent* dir;
5123 while ((dir = readdir(d)) != NULL) {
5124 if(dir->d_type != DT_DIR) {
5125 char fpath[1000];
5126 sprintf(fpath, "%s/%s", path, dir->d_name);
5127 vec.push_back(c2s(fpath));
5128 if(vec.size() > 1000) {
5129 writeFileAppendVector(c2s(toFile), vec);
5130 vec.clear();
5131 }
5132 } else if(dir -> d_type == DT_DIR && strcmp(dir->d_name,".")!=0 && strcmp(dir->d_name,"..")!=0 ) {
5133 char fpath[1000];
5134 sprintf(fpath, "%s/%s", path, dir->d_name);
5135 listDirToFile(fpath, toFile, vec);
5136 }
5137 }
5138 closedir(d);
5139 }
5140}
5141
5145void listDirToVec(char * path, char* toFile, vector<string>& vec) {
5146 listDirToFile(path, toFile, vec);
5147}
5148
5152vector<string> recurveDirBoost(char* dir) {
5153 vector<string> retVec;
5154 fs::path p(dir);
5155 bool b = exists(p);
5156
5157 if(!exists(p) || !is_directory(p)) {
5158 std::cout << p << " is not a path\n";
5159 return retVec;
5160 }
5161
5162 fs::recursive_directory_iterator begin(p), end;
5163 std::vector<fs::directory_entry> v(begin, end); // vector created here
5164 for(fs::directory_entry& f: v) {
5165 retVec.push_back(f.path().string());
5166 }
5167
5168 return retVec;
5169}
5170
5191void recurveDirToFile(char * path, char* toFile, vector<string>& vec) {
5192 DIR * d = opendir(path);
5193 if( d != NULL) {
5194 struct dirent* dir;
5195 while ((dir = readdir(d)) != NULL) {
5196 if(dir-> d_type != DT_DIR) {
5197 char fpath[500];
5198 sprintf(fpath, "%s/%s", path, dir->d_name);
5199 vec.push_back(c2s(fpath));
5200 if(vec.size() > 1000) {
5201 writeFileAppendVector(c2s(toFile), vec);
5202 vec.clear();
5203 }
5204 } else if(dir -> d_type == DT_DIR && strcmp(dir->d_name,".")!=0 && strcmp(dir->d_name,"..")!=0 ) {
5205 char fpath[500];
5206 sprintf(fpath, "%s/%s", path, dir->d_name);
5207 listDirToFile(fpath, toFile, vec);
5208 } else {
5209 vec.push_back("Unknown_type");
5210 }
5211 }
5212 if(vec.size() > 0) {
5213 writeFileAppendVector(c2s(toFile), vec);
5214 vec.clear();
5215 }
5216 closedir(d);
5217 }
5218}
5219
5225void listDirAll(char * path) {
5226 DIR * d = opendir(path);
5227 if(d != NULL) {
5228 struct dirent* dir;
5229 while ((dir = readdir(d)) != NULL) {
5230 if(dir-> d_type != DT_DIR) { // if the type is not directory just print it with blue
5231 char dpath[1000]; // here I am using sprintf which is safer than strcat
5232 sprintf(dpath, "%s/%s", path, dir->d_name);
5233 printf("%s\n", dpath);
5234 } else if(dir -> d_type == DT_DIR && strcmp(dir->d_name,".")!=0 && strcmp(dir->d_name,"..")!=0 ) {
5235 printf("%s\n", dir->d_name); // print its name in green
5236 char dpath[1000]; // here I am using sprintf which is safer than strcat
5237 sprintf(dpath, "%s/%s", path, dir->d_name);
5238 printf("%s\n", dpath);
5239 listDirAll(dpath); // recall with the new path
5240 } else {
5241 pl("Unknown_type");
5242 }
5243 }
5244 closedir(d); // finally close the directory
5245 }
5246}
5247
5253void listDirToVector(char * path, vector<string>& vec) {
5254 DIR * d = opendir(path);
5255 if( d != NULL) {
5256 struct dirent* dir;
5257 while ((dir = readdir(d)) != NULL) {
5258 if(dir-> d_type != DT_DIR) {
5259 char fullpath[1000];
5260 sprintf(fullpath, "%s/%s", path, dir->d_name);
5261 vec.push_back(c2s(fullpath));
5262 } else if(dir -> d_type == DT_DIR && strcmp(dir->d_name,".")!=0 && strcmp(dir->d_name,"..")!=0 ) {
5263 char fullpath[1000];
5264 sprintf(fullpath, "%s/%s", path, dir->d_name);
5265 listDirToVector(fullpath, vec);
5266 } else {
5267 vec.push_back("Unknown_type");
5268 }
5269 }
5270 closedir(d);
5271 }
5272}
5273
5274string getPWD() {
5275 string ret;
5276 char cwd[PATH_MAX];
5277 if (getcwd(cwd, sizeof(cwd)) != NULL) {
5278 ret = cStringToString(cwd);
5279 } else {
5280 perror("getcwd() error");
5281 }
5282 return ret;
5283}
5284
5289string intToStringLen(int num, int maxlen) {
5290 char buffer[255];
5291 sprintf(buffer, "%d", num);
5292 string zero = AronLambda::take(maxlen - strlen(buffer), repeat(num, "0"));
5293 return zero + c2s(buffer);
5294}
5295
5301std::pair<vector<string>, vector<string>> parseLambda(string s) {
5302 vector<string> vecStr = splitStrRegex(s, "\\s+");
5303 vector<string> vec = AronLambda::filter([](auto& x) {
5304 return trim(x).length() > 0;
5305 }, vecStr);
5306
5307 vector<string> varv;
5308 auto f = [](auto x) {
5309 return x == c2s("->");
5310 };
5311 std::pair<vector<string>, vector<string>> pair = breakVec(f, vec);
5312 return std::make_pair(pair.first, AronLambda::tail(pair.second));
5313}
5314
5315#endif
5316
5322namespace Algorithm {
5323
5324void merge(int* arr, int lo, int mid, int hi) {
5325 int len = hi - lo + 1;
5326 int* list = new int[len];
5327 int i = lo;
5328 int j = mid + 1;
5329 int k = 0;
5330 while(i < mid + 1 || j < hi + 1) {
5331 if (i >= mid + 1) {
5332 list[k] = arr[j];
5333 j++;
5334 } else if(j >= hi + 1) {
5335 list[k] = arr[i];
5336 i++;
5337 } else if (arr[i] < arr[j]) {
5338 list[k] = arr[i];
5339 i++;
5340 } else {
5341 list[k] = arr[j];
5342 j++;
5343 }
5344 k++;
5345 }
5346 for(int i=0; i<len; i++) {
5347 arr[lo + i] = list[i];
5348 }
5349 delete[] list;
5350}
5351
5352void mergeSort(int* arr, int lo, int hi) {
5353 if(lo < hi) {
5354 int m = (lo + hi)/2;
5355 mergeSort(arr, lo, m);
5356 mergeSort(arr, m+1, hi);
5357 merge(arr, lo, m, hi);
5358 }
5359}
5360
5361// TODO: add test cases
5362void swap(int array[], int i, int j) {
5363 int tmp = array[i];
5364 array[i] = array[j];
5365 array[j] = tmp;
5366}
5367
5368
5378int partition(int array[], int lo, int hi) {
5379 if(hi > lo) {
5380 int p = array[hi];
5381 int big = lo;
5382 for(int i=lo; i<=hi; i++) {
5383 if(array[i] <= p) {
5384 swap(array, i, big);
5385 if(i < hi)
5386 big++;
5387 }
5388 }
5389 return big;
5390 }
5391 return -1;
5392}
5393
5394// TODO: add test cases
5395void quickSortArr(int array[], int lo, int hi) {
5396 if(hi > lo) {
5397 int pivot = partition(array, lo, hi);
5398 quickSortArr(array, lo, pivot-1);
5399 quickSortArr(array, pivot+1, hi);
5400 }
5401}
5402
5403// TODO: add lambda fun for more general sorting
5404template<typename T>
5405static vector<T> quickSort(vector<T> vec) {
5406 if (vec.size() <= 1)
5407 return vec;
5408 else {
5409 T pivot = head(vec);
5410 vector<T> rest = drop(1, vec);
5411 vector<T> left = filter<T>([pivot](auto x) {
5412 return x < pivot;
5413 }, rest);
5414 vector<T> right = filter<T>([pivot](auto x) {
5415 return x >= pivot;
5416 }, rest);
5417 return quickSort(left) + con(pivot, quickSort(right));
5418 }
5419}
5420
5421template<typename Fun, typename T>
5422static vector<T> mergeSortList(Fun f, vector<T> v1, vector<T> v2) {
5423 vector<T> empty;
5424 if (v1.size() == 0)
5425 return v2;
5426 if (v2.size() == 0)
5427 return v1;
5428
5429 vector<T> vh1 = take(1, v1);
5430 vector<T> vh2 = take(1, v2);
5431 if (f(vh1.at(0), vh2.at(0))) {
5432 return vh1 + mergeSortList(f, tail(v1), v2);
5433 } else {
5434 return vh2 + mergeSortList(f, v1, tail(v2));
5435 }
5436}
5437
5438} // end Algorithm
5439
5440//string toStr(int e){
5441// string ret;
5442// return ret;
5443//}
5444//string toStr(float e){
5445// string ret;
5446// return ret;
5447//}
5448//string toStr(double e){
5449// string ret;
5450// return ret;
5451//}
5452//string toStr(long e){
5453// string ret;
5454// return ret;
5455//}
5456
5457using namespace MatrixVector;
5458void writeFile(string fname, mat& m) {
5459 for(int i=0; i<m.nrow; i++) {
5460 vector<float> vec = m.getVec(i).toVector();
5461 writeFileAppendVector(fname, vec);
5462 }
5463}
5464
5473template<typename T>
5474T dotProduct(vector<T> v1, vector<T> v2){
5475 T n;
5476 for(int i = 0; i < min(len(v1), len(v2)); i++){
5477 n += v1[i] * v2[i];
5478 }
5479 return n;
5480}
5481
5496template<typename T>
5497T det2(vector<vector<T>> v2){
5498 if (len(v2) == 2 && len(v2[0]) == 2){
5499 T a = v2[0][0];
5500 T b = v2[0][1];
5501 T c = v2[1][0];
5502 T d = v2[1][1];
5503 return a*d - b*c;
5504 }else{
5505 pp("Invalid Input.");
5506 }
5507}
5508
5523template<class T>
5524T det2(vector<T> v1, vector<T> v2){
5525 if (len(v1) == 2 && len(v2) == 2){
5526 T a = v1[0];
5527 T b = v1[1];
5528 T c = v2[0];
5529 T d = v2[1];
5530 return a*d - b*c;
5531 }else{
5532 pp("Invalid Input.");
5533 }
5534}
5535
5536
5562template<class T>
5563vector<T> crossProduct(vector<T> v1, vector<T> v2){
5564 if(len(v1) == len(v2) && len(v1) == 3){
5565 T x;
5566 {
5567 vector<T> v11 = removeIndex(v1, 0);
5568 vector<T> v22 = removeIndex(v2, 0);
5569 x = det2<T>(v11, v22);
5570 }
5571
5572 T y;
5573 {
5574 vector<T> v11 = removeIndex(v1, 1);
5575 vector<T> v22 = removeIndex(v2, 1);
5576 y = (-1)*det2<T>(v11, v22);
5577 }
5578 T z;
5579 {
5580 vector<T> v11 = removeIndex(v1, 2);
5581 vector<T> v22 = removeIndex(v2, 2);
5582 z = det2<T>(v11, v22);
5583 }
5584 return {x, y, z};
5585 }else{
5586 printf("Invalid Input.\n");
5587 }
5588 return {};
5589}
5590
5591void printArr2(float* arr, int len, int width){
5592 vector<vector<float>> vv = arrToVec2(arr, len, width);
5593 mat m1(vv);
5594 m1.print();
5595}
5596
5600template<typename T>
5601vector<T> subtract(vector<T> v1, vector<T> v2){
5602 vector<T> v;
5603 for(int i = 0; i < min(len(v1), len(v2)); i++){
5604 v.push_back(v1[i] - v2[i]);
5605 }
5606 return v;
5607}
5608
5609template<typename T>
5610void print(string s, T t){
5611 fw(s);
5612 print(t);
5613}
5614
5615string padRight(string s, string pad, int maxLen){
5616 int diff = maxLen - len(s);
5617 int padLen = diff > 0 ? diff : 0;
5618 string ret = s + repeat(padLen, pad);
5619 return ret;
5620}
5621
5622string padLeft(string s, string pad, int maxLen){
5623 int diff = maxLen - len(s);
5624 int padLen = diff > 0 ? diff : 0;
5625 string ret = repeat(padLen, pad) + s;
5626 return ret;
5627}
5628
5629//void writeFileRow(string fname, row& r){
5630// auto f = [](auto& x) { return toStr(s);};
5631// vector<float> vec = {0.1, 1.2};
5632// vector<string> s1 = AronLambda::map( f, vec);
5639//}
5640
5641
5642
5643
5644#endif
5645
double intToDouble(int n)
Definition: AronLib.h:1780
const char * s2c(string s)
Convert std::string to char*.
Definition: AronLib.h:1470
vector< vector< T > > geneMatrix(int ncol, int nrow, T init)
Generate ncol x nrow matrix with initial value @init.
Definition: AronLib.h:2338
int random(int n)
random number from 0 to n-1 NOTE: Ubuntu DOES NOT have arc4random_uniform, it works on MacOS only.
Definition: AronLib.h:1410
vector< T > operator+(vector< T > v1, vector< T > v2)
Concate two vectors, both vectors are NOT modified.
Definition: AronLib.h:2111
T partition(vector< T > &vec, int lo, int hi)
partition vector, use [hi] as pivot, like in quicksort
Definition: AronLib.h:2397
void quickSortT(T array[], int lo, int hi)
Definition: AronLib.h:2465
bool compareFloat(double a, double b)
Definition: AronLib.h:1895
uint64_t nowMicroseconds()
Definition: AronLib.h:211
bool containStrRegex(string s, regex rx)
check s contains regex pattern
Definition: AronLib.h:1584
T head(vector< T > vec)
Definition: AronLib.h:919
bool containStr(string str, string pat)
check if str contain pat
Definition: AronLib.h:1599
vector< int > randomNanoSec(int n, int max)
Definition: AronLib.h:1392
void tranmat4(float arr[16])
Definition: AronLib.h:1997
double nthRoot(double c, int n, double epsilon=0.000001)
Compute the nth root of any positive integer, n >= 1.
Definition: AronLib.h:1790
int length(string s)
length of string
Definition: AronLib.h:2174
std::map< char, int > hexMap()
Definition: AronLib.h:335
string concatValidPath(vector< string > vec)
remove adjacent duplicate char from a string
Definition: AronLib.h:2510
void writeFileAppendRow(string fname, std::vector< T > vec)
Write vector to file using space as delimiter.
Definition: AronLib.h:552
int compareCString(char *s1, char *s2)
Definition: AronLib.h:1853
string c2s(const char *pt)
string to char*
Definition: AronLib.h:1570
vector< vector< T > > transpose(vector< vector< T > > mat)
transpose matrix
Definition: AronLib.h:1956
vector< T > replaceVec(T oldVal, T newVal, vector< T > vec)
replace oldVale with newVal in a cloned vector
Definition: AronLib.h:1681
int len(string s)
length of string
Definition: AronLib.h:2192
Complex rectangular(std::pair< double, double > p)
Definition: AronLib.h:3216
vector< int > sumVec(vector< int > v1, vector< int > v2)
sum two int vectors
Definition: AronLib.h:588
vector< std::string > splitStrRegex(const string &s, string rgxStr="\\s+")
Split string with regex.
Definition: AronLib.h:1728
double squareRoot(double a)
Definition: AronLib.h:1766
vector< T > reverseVec(vector< T > vec)
Definition: AronLib.h:2282
vector< T > * moveVec(T a, vector< T > vec)
use std::move, it acts like Java. Create local object, and return it.
Definition: AronLib.h:2139
void printNb(T t)
print no bracket
Definition: AronLib.h:2064
vector< T > removeIndexRange(vector< T > &vec, int fromInx, int toInx)
remove index from to index inclusively.
Definition: AronLib.h:686
vector< T > subtract(vector< T > v1, vector< T > v2)
Definition: AronLib.h:5601
long lcgRandom(long x0)
Linear congruential generator.
Definition: AronLib.h:1369
T last(vector< T > vec)
Definition: AronLib.h:937
vector< T > * append(vector< T > vec, T a)
use std::move, it acts like Java. Create local object, and return it.
Definition: AronLib.h:2162
string toStr(const T &s)
Convert any type to std::string.
Definition: AronLib.h:1494
uint64_t nowNanoseconds()
Definition: AronLib.h:219
vector< T > concatVec(vector< T > v1, vector< T > v2)
Concat two vectors.
Definition: AronLib.h:2100
int maxConsecutiveOne(vector< int > vec)
Definition: AronLib.h:250
vector< int > toBinary(int n)
Definition: AronLib.h:405
int maxConsecutiveChar(char *arr, int size, char c)
Definition: AronLib.h:289
vector< T > operator*(T a, vector< T > vec)
scalar multiply vector
Definition: AronLib.h:2236
vector< string > splitStr(string s, string delim)
Split string with delimiter.
Definition: AronLib.h:1619
std::pair< vector< T >, vector< T > > breakVec(Fun f, vector< T > vec)
break a vector to pair
Definition: AronLib.h:1663
bool isEmpty(string s)
Definition: AronLib.h:1745
vector< T > insertAt(vector< T > vec, int pos, vector< T > insertVec)
Insert vector @insertVec into vec at position @pos.
Definition: AronLib.h:1704
string trim(string str)
trim both ends
Definition: AronLib.h:1547
const char * stringToCString(string s)
Convert std::string to char*, same as s2c(string s)
Definition: AronLib.h:1463
string removeIndex(string s, int inx)
remove char from a string
Definition: AronLib.h:655
T dotProduct(vector< T > v1, vector< T > v2)
Definition: AronLib.h:5474
string cStringToString(const char *pt)
char* to string
Definition: AronLib.h:1557
T det2(vector< vector< T > > v2)
Definition: AronLib.h:5497
const char * toCharPtr(string s)
it is same as s2c but it is better name.
Definition: AronLib.h:1479
std::pair< vector< T >, vector< T > > splitAt(int n, vector< T > vec)
split vector to pair of vector
Definition: AronLib.h:1645
vector< T > crossProduct(vector< T > v1, vector< T > v2)
Definition: AronLib.h:5563
int partitionT(T array[], int lo, int hi)
partition array inline
Definition: AronLib.h:2367
int partitionInline(vector< T > &vec, int lo, int hi)
partition vector inline
Definition: AronLib.h:2434
bool isBST(Node< int > *curr, Node< int > *&prev)
Check whether a Binary Tree is BST.
Definition: AronLib.h:2320
int compareString(string s1, string s2)
Definition: AronLib.h:1861
uint64_t nowMilliseconds()
Definition: AronLib.h:202
string removeAdjacentDuplicateChar(string s, char c)
remove adjacent duplicate char from a string
Definition: AronLib.h:2524
bool binSearch(T key, T arr[], int lo, int hi)
binary search on a sorted array
Definition: AronLib.h:2216
string repeat(int n, string s)
Repeating n copy of s. The function is inspired by Haskell repeat.
Definition: AronLib.h:1831
Definition: AronLib.h:2681
Definition: AronLib.h:2625
Definition: AronLib.h:2738
Definition: AronLib_tmp.h:2619
Definition: DDLinkedList.h:9
Inspired from Eigen Lib.
Definition: AronLib.h:3629
Definition: AronLib.h:3604
mat take(int len)
Take first n columns from a matrix.
Definition: AronLib.h:4049
mat removeVec(int index)
Get an index Column or Vector from a matrix.
Definition: AronLib.h:3924
void geneMatRandom(int fst, int snd)
Generate a random matrix in interval @fst and @snd [fst, snd)
Definition: AronLib.h:4189
mat insertVecNext(int index, vec v)
Add vector to the right of index, Should I change the name to insertVecRight()
Definition: AronLib.h:3942
mat drop(int len)
Drop first n columns from a matrix.
Definition: AronLib.h:4061
mat tail()
Drop the first column from a matrix.
Definition: AronLib.h:4101
void geneMat(int init)
Generate matrix from init to ncol*nrow.
Definition: AronLib.h:4166
mat init()
Drop the last column from a matrix.
Definition: AronLib.h:4080
mat block(int colIndex, int clen, int rowIndex, int rlen)
subblock of a matrix
Definition: AronLib.h:4117
mat transpose()
tranpose matrix
Definition: AronLib.h:4137
row getRow(int n)
Get an index row from a matrix.
Definition: AronLib.h:3913
mat subMatrix(int colIndex, int rowIndex)
/Library/WebServer/Documents/zsurface/pdf/submatrix_get.pdf 1 2 3 subMatrix(1, 0) => 4 5 6 4 5 6
Definition: AronLib.h:4029
void print()
print the matrix
Definition: AronLib.h:3840
mat swapRow(int inx1, int inx2)
Add test cases.
Definition: AronLib.h:4314
vec getVec(int n)
Definition: AronLib.h:3901
Definition: AronLib.h:3357
vector< float > toVector()
Convert row to vector.
Definition: AronLib.h:3556
Definition: AronLib.h:3332
vector< float > toVector()
Definition: AronLib.h:3432
Definition: Node.h:5
Complex(double x_, double y_)
Definition: AronLib.h:3132
Complex operator-(Complex &c)
Definition: AronLib.h:3150
friend Complex operator/(const Complex &c1, const Complex &c2)
division for complex number
Definition: AronLib.h:3195
Complex operator*(const Complex &c)
Definition: AronLib.h:3162
Complex()
Definition: AronLib.h:3125
bool operator==(const Complex &c)
Definition: AronLib.h:3170
void print()
Definition: AronLib.h:3206
Complex operator+(Complex &c)
Definition: AronLib.h:3140
Definition: AronLib.h:4529
Vector4()
Definition: AronLib.h:4541
Definition: AronLib.h:850
Definition: Vector3.h:63
Definition: AronLib_tmp.h:725
include all the sorting algorithms etc.
int partition(int array[], int lo, int hi)
partition array to to left and right, using [hi] as pivot
Definition: AronLib.h:5378
complex number representation and operation number
Two dimensional array represents matrix, column and row vector.
Definition: AronLib.h:3231
T ** vecVecToArrArr(vector< vector< T > > vv)
Convert Vector< Vector<T> > to dynamic T**.
Definition: AronLib.h:3272
std::pair< mat, mat > utri(mat m)
Assume the diagonal entries are not zero, compute the U triangle matrix Lk..(L2 (L1 A))= U TODO: fix ...
Definition: AronLib.h:4477
vector< vector< T > > arrArrToVecVec(T **arr, int ncol, int nrow)
Convert T** arr to vector<vector<T>> v2.
Definition: AronLib.h:3316
vec backwardSubstitute(mat a, vec b)
Backward Substitute.
Definition: AronLib.h:4416
T ** allocate(int ncol, int nrow)
Allocate a matrix: height = ncol, width = nrow.
Definition: AronLib.h:3259
mat geneMatRandom(int ncol, int nrow, int fst, int snd)
Generate random matrix in interval from fst to snd.
Definition: AronLib.h:4507
T ** allocateTemp(int ncol, int nrow)
Allocate ncol, nrow two dimension array for any type, return a pointer.
Definition: AronLib.h:3245
mat ltri(mat m, int index)
Get the L triangle from a matrix.
Definition: AronLib.h:4460
4 dimensions vector
many function can be global actually
int substringFirstIndex(string sub, string s)
find the index of sub in string s
Definition: AronLib.h:2864
bool isSubstring(string sub, string s)
Check whether sub is the substring of s.
Definition: AronLib.h:2825