├── ---code-template-codechef.js ├── .gitattributes ├── .gitignore ├── BIT-fenwick-tree-explanation.md ├── BIT-fenwick-tree.cpp ├── BITS-AND-BYTES.cpp ├── BIT_fenwick_tree_explanation.md ├── MATHEMATICS.MD ├── PRINT-EVERYTHING.cpp ├── README.md ├── RMQ-using-NxN.cpp ├── RMQ-using-cartesian-tree.cpp ├── RMQ-using-sparse-table.cpp ├── RangeMaxQuery-using-segment-tree.cpp ├── avl-self-balancing-tree.cpp ├── basics-a-pow-n.js ├── basics-fact-n.js ├── basics-fibo-n.js ├── basics-gcd-euclidean-algorithm.cpp ├── basics-merge-sort-top-down-recursive.cpp ├── basics-performance-timers.js ├── basics-quicksort-lomuto.cpp ├── cartesian-tree.cpp ├── convex-hull-jarvis.js ├── gccp.bat ├── javascript-deque.js ├── js-backtracking-knight-movement.js ├── js-math-nCr.js ├── js-math-pascal-triangle-simplex-numbers ├── js-min-heap.js ├── js-util-binary-search.js ├── js-util-bits.js ├── js-util-combinations-without-repetition.js ├── js-util-permutation.js ├── js-util-power-set-on-array.js ├── longest-increasing-sequence.cpp ├── main.js ├── minmaxsum.cpp ├── my-statistics-notes.MD ├── nbproject ├── private │ ├── private.properties │ └── private.xml ├── project.properties └── project.xml ├── old-my-datastructures-in-c ├── .gitattributes ├── .gitignore ├── BST.c ├── BST.h ├── ReadMe.txt ├── ReadMe_binarytree_types.txt ├── ReadMe_tree_types.txt ├── _main.c ├── array.c ├── array.h ├── binaryheap.c ├── binaryheap.h ├── binarytree.c ├── binarytree.h ├── common.c ├── common.h ├── datastructures.sln ├── datastructures.vcxproj ├── datastructures.vcxproj.filters ├── datastructures.vcxproj.user ├── linkedlist.c ├── linkedlist.h ├── llqueue.c ├── llqueue.h ├── queue.c ├── queue.h ├── queue_circular_buffer.c ├── queue_circular_buffer.h ├── stack.c └── stack.h ├── package.json ├── primes-offline.cpp ├── sa-lcp-working-to-post.cpp ├── segment-tree-cleaned-up.cpp ├── square-root-decomposition-min-and-second-min.cpp ├── trie-the-dictionary.cpp ├── y-BST.txt ├── y-HEAP.txt └── y-primality.txt /---code-template-codechef.js: -------------------------------------------------------------------------------- 1 | // NODEJS (Node 7.4.0) common template for everyone 2 | 3 | // NOTE: This is common code - MUST be there for all problems below 4 | let inputStr = ""; 5 | const _toInt = (x) => +x; 6 | process.stdin.resume(); 7 | process.stdin.setEncoding("utf8"); 8 | process.stdin.on("data", (chunk) => (inputStr += chunk)); 9 | 10 | // problem https://www.codechef.com/problems/START01 11 | process.stdin.on("end", () => { 12 | console.log(+inputStr); 13 | }); 14 | 15 | // problem https://www.codechef.com/problems/FLOW001 16 | process.stdin.on("end", () => { 17 | const inputLinesArr = inputStr.split("\n"); 18 | 19 | let T = +inputLinesArr[0]; // # of tests 20 | 21 | for (let i = 1; i <= T; i++) { 22 | let [a, b] = inputLinesArr[i].split(" ").map(_toInt); // each test case 23 | 24 | console.log(a + b); 25 | } 26 | }); 27 | 28 | // problem https://www.codechef.com/problems/INTEST 29 | process.stdin.on("end", () => { 30 | const inputLinesArr = inputStr.split("\n"); 31 | 32 | let [n, k] = inputLinesArr[0].split(" ").map(_toInt); 33 | 34 | let count = 0; 35 | 36 | for (let i = 1; i <= n; i++) { 37 | let ti = +inputLinesArr[i]; 38 | if (ti % k === 0) { 39 | count++; 40 | } 41 | } 42 | 43 | console.log(count); 44 | }); 45 | 46 | // problem https://www.codechef.com/problems/HS08TEST 47 | process.stdin.on("end", () => { 48 | let [a, b] = inputStr.split(" ").map(_toInt); // each test case 49 | 50 | let res = b - a - 0.5; 51 | if (a % 5 === 0 && res >= 0) { 52 | // all good 53 | } else { 54 | res = b; 55 | } 56 | 57 | console.log(res); 58 | }); 59 | -------------------------------------------------------------------------------- /.gitattributes: -------------------------------------------------------------------------------- 1 | # Auto detect text files and perform LF normalization 2 | * text=auto 3 | 4 | # Custom for Visual Studio 5 | *.cs diff=csharp 6 | 7 | # Standard to msysgit 8 | *.doc diff=astextplain 9 | *.DOC diff=astextplain 10 | *.docx diff=astextplain 11 | *.DOCX diff=astextplain 12 | *.dot diff=astextplain 13 | *.DOT diff=astextplain 14 | *.pdf diff=astextplain 15 | *.PDF diff=astextplain 16 | *.rtf diff=astextplain 17 | *.RTF diff=astextplain 18 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Windows image file caches 2 | Thumbs.db 3 | ehthumbs.db 4 | 5 | # Folder config file 6 | Desktop.ini 7 | 8 | # Recycle Bin used on file shares 9 | $RECYCLE.BIN/ 10 | 11 | # Windows Installer files 12 | *.cab 13 | *.msi 14 | *.msm 15 | *.msp 16 | 17 | # Windows shortcuts 18 | *.lnk 19 | 20 | # ========================= 21 | # Operating System Files 22 | # ========================= 23 | 24 | # OSX 25 | # ========================= 26 | 27 | .DS_Store 28 | .AppleDouble 29 | .LSOverride 30 | 31 | # Thumbnails 32 | ._* 33 | 34 | # Files that might appear in the root of a volume 35 | .DocumentRevisions-V100 36 | .fseventsd 37 | .Spotlight-V100 38 | .TemporaryItems 39 | .Trashes 40 | .VolumeIcon.icns 41 | 42 | # Directories potentially created on remote AFP share 43 | .AppleDB 44 | .AppleDesktop 45 | Network Trash Folder 46 | Temporary Items 47 | .apdisk 48 | /main/main/nbproject/private/ 49 | /main/main/build/ 50 | /main/build/ 51 | /main/nbproject/private/ -------------------------------------------------------------------------------- /BIT-fenwick-tree-explanation.md: -------------------------------------------------------------------------------- 1 |
  2 | 
  3 | Sources:
  4 | https://en.wikipedia.org/wiki/Fenwick_tree
  5 | http://www.geeksforgeeks.org/binary-indexed-tree-range-update-range-queries/
  6 | https://cs.stackexchange.com/questions/33014/range-update-range-query-with-binary-indexed-trees
  7 | 
  8 | 
  9 | =====
 10 | Logic for Point & Range update
 11 | =====
 12 | Since this is in progress, if you already forked this repository, you would need to merge new changes from here to your forked ones in future if you need new changes. Obviously, if you liked this, click the Star above will help others find this page.
 13 | =====
 14 | 
 15 | ====================
 16 | > Section 1
 17 | ====================
 18 | Point Update
 19 | ====================
 20 | i            0  1  2  3  4  5  6  7   8   9
 21 | A[i]         0  0  0  0  0  0  0  0   0   0
 22 | SumTill[i]   0  0  0  0  0  0  0  0   0   0
 23 | ___
 24 | Now +5 to [3]
 25 | ___
 26 | i            0  1  2  3  4  5  6  7   8   9
 27 | A[i]         0  0  0  0 +5  0  0  0   0   0
 28 | SumTill[i]   0  0  0  0  5  5  5  5   5   5
 29 | ___
 30 | In Point Update form:
 31 | A[3]       += +5
 32 | BITarr[3]  += +5 (and, +5 also proprates to other elements, acc to algorithm of BIT)
 33 | ___
 34 | In Point Update form (in general form)
 35 | A[i]       += +V
 36 | BITarr[i]  += +V (and, +V also proprates to other elements, acc to algorithm of BIT)
 37 | ___
 38 | 
 39 | 
 40 | 
 41 | ====================
 42 | > Section 2
 43 | ====================
 44 | Range Update
 45 | ====================
 46 | Assume
 47 | ___
 48 | i                  0  1  2  3  4  5  6  7   8   9
 49 | A[i]               0  0  0  0  0  0  0  0   0   0
 50 | SumTill[i]         0  0  0  0  0  0  0  0   0   0
 51 | ___
 52 | Now +5 to [3 to 7]
 53 | ___
 54 | i                  0  1  2  3  4  5  6  7   8   9
 55 | A[i]               0  0  0  5  5  5  5  5   0   0
 56 | SumTill[i]         0  0  0  5 10 15 20 25  25  25
 57 | ___
 58 | Here
 59 | ___
 60 | SumTill[i]         0  0  0  5 10 15 20 25  25  25
 61 | is
 62 | i                  0  1  2  3  4  5  6  7   8   9
 63 | X1[i]             *0  0  0  5  5  5  5  5   0   0
 64 | X2[i]             +0  0  0 10 10 10 10 10 -25 -25
 65 | .
 66 | > Tranformation formula
 67 | > Where, SumTill[i] = i * X1[i] - X2[i], This will not be used anywhere below, but is key to derive BIT form
 68 | .
 69 | ___
 70 | Here
 71 | ___
 72 | i                  0  1  2        3  4  5  6   7      8   9
 73 | X1[i]             *0  0  0        5  5  5  5   5      0   0
 74 | X2[i]             +0  0  0       10 10 10 10  10    -25 -25
 75 | ___
 76 | looks like:
 77 | ___
 78 | i                  0  1  2        3  4  5  6   7      8   9
 79 | index names                       3            7    7+1
 80 | -------------------------------------------------------------
 81 | BIT-like-form-X1  *0  0  0       +5  0  0  0   0     -5   0
 82 | BIT-like-form-X2  +0  0  0       10  0  0  0   0    -35   0
 83 | ___
 84 | 
 85 | Above in Point Update form: (see above, Section 1)
 86 | this is
 87 | BITX1[3]   =  +5
 88 | BITX1[7+1] =  -5
 89 | BITX2[3]   = +10
 90 | BITX2[7+1] = -35
 91 | So, +5 to [3 to 7] came down to above.
 92 | These above 4 formulas are for range_update(3,7,5).
 93 | ___
 94 | 
 95 | Exact above (in general form) looks like:
 96 | ___
 97 | index              0  1  2        3  4  5  6   7     8   9
 98 | index names                       i            j   j+1
 99 | -------------------------------------------------------------
100 | BIT-like-form-X1  *0  0  0       +V  0  0  0   0    -V   0
101 | BIT-like-form-X2  +0  0  0  (i-1)*V  0  0  0   0  -j*V   0
102 | ___
103 | Above in Point Update form (in general form): (see above, Section 1)
104 | this is
105 | ___
106 | (in general form)
107 | BITX1[i]   +=        +V
108 | BITX1[j+1] +=        -V
109 | BITX2[i]   +=  +(i-1)*V
110 | BITX2[j+1] +=      -j*V
111 | So, +V to [i to j] came down to above
112 | These above 4 formulas are for range_update(i,j,V).
113 | 
114 | So, you will need two arrays of size A[],
115 | however update of range (i,j)
116 | should be logN for BITX1 &
117 | another logN for BITX2
118 | which is 2*logN, still O(logN), faster than O(N) updating all values of (i,j), so above 'Tranformation formula' is key
119 | ___
120 | 
121 | 
122 | -------------------------------------------------------------------------------- /BITS-AND-BYTES.cpp: -------------------------------------------------------------------------------- 1 | 2 | void know_bits_and_bytes() { 3 | 4 | cout << left << setw(30) << "size of char: " << "-" << pow(2, 8 * sizeof(char) - 1) << " " << pow(2, 8 * sizeof(char) - 1) - 1 << endl; 5 | cout << left << setw(30) << "size of unsigned char: " << " " << 0 << " " << pow(2, 8 * sizeof(unsigned char)) - 1 << endl; 6 | cout << left << setw(30) << "size of short: " << "-" << pow(2, 8 * sizeof(short) - 1) << " " << pow(2, 8 * sizeof(short) - 1) - 1 << endl; 7 | cout << left << setw(30) << "size of unsigned short: " << " " << 0 << " " << pow(2, 8 * sizeof(unsigned short)) - 1 << endl; 8 | cout << left << setw(30) << "size of int: " << "-" << pow(2, 8 * sizeof(int) - 1) << " " << pow(2, 8 * sizeof(int) - 1) - 1 << endl; 9 | cout << left << setw(30) << "size of unsigned int: " << " " << 0 << " " << pow(2, 8 * sizeof(unsigned int)) - 1 << endl; 10 | cout << left << setw(30) << "size of long: " << "-" << pow(2, 8 * sizeof(long) - 1) << " " << pow(2, 8 * sizeof(long) - 1) - 1 << endl; 11 | cout << left << setw(30) << "size of unsigned long: " << " " << 0 << " " << pow(2, 8 * sizeof(unsigned long)) - 1 << endl; 12 | cout << left << setw(30) << "size of long long: " << "-" << pow(2, 8 * sizeof(long long) - 1) << " " << pow(2, 8 * sizeof(long long) - 1) - 1 << endl; 13 | cout << left << setw(30) << "size of unsigned long long: " << " " << 0 << " " << pow(2, 8 * sizeof(unsigned long long)) - 1 << endl; 14 | } 15 | 16 | 17 | /* 18 | hackerrank 19 | size of char: -128 127 20 | size of unsigned char: 0 255 21 | size of short: -32768 32767 // 3 X 10^4 22 | size of unsigned short: 0 65535 // 6 X 10^4 23 | size of int: -2.14748e+09 2.14748e+09 // 2 X 10^9 24 | size of unsigned int: 0 4.29497e+09 // 4 X 10^9 25 | size of long: -9.22337e+18 9.22337e+18 // 9 X 10^18 26 | size of unsigned long: 0 1.84467e+19 // 1 X 10^19 27 | size of long long: -9.22337e+18 9.22337e+18 // 9 X 10^18 28 | size of unsigned long long: 0 1.84467e+19 // 1 X 10^19 29 | 30 | // summary: long and long long are same on hackerrank --- so use (short, int, long) only for integers, signed or unsigned as required 31 | 32 | local machine/ laptop 33 | size of char: -128 127 34 | size of unsigned char: 0 255 35 | size of short: -32768 32767 // 3 X 10^4 36 | size of unsigned short: 0 65535 // 6 X 10^4 37 | size of int: -2.14748e+09 2.14748e+09 // 2 X 10^9 38 | size of unsigned int: 0 4.29497e+09 // 4 X 10^9 39 | size of long: -2.14748e+09 2.14748e+09 // 2 X 10^9 40 | size of unsigned long: 0 4.29497e+09 // 4 X 10^9 41 | size of long long: -9.22337e+18 9.22337e+18 // 9 X 10^18 42 | size of unsigned long long: 0 1.84467e+19 // 1 X 10^19 43 | */ 44 | -------------------------------------------------------------------------------- /BIT_fenwick_tree_explanation.md: -------------------------------------------------------------------------------- 1 |
  2 | 
  3 | Sources:
  4 | https://en.wikipedia.org/wiki/Fenwick_tree
  5 | http://www.geeksforgeeks.org/binary-indexed-tree-range-update-range-queries/
  6 | https://cs.stackexchange.com/questions/33014/range-update-range-query-with-binary-indexed-trees
  7 | 
  8 | 
  9 | =====
 10 | Logic for Point & Range update
 11 | =====
 12 | Since this is in progress, if you already forked this repository, you would need to merge new changes from here to your forked ones in future if you need new changes. Obviously, if you liked this, click the Star above will help others find this page.
 13 | =====
 14 | 
 15 | ====================
 16 | > Section 1
 17 | ====================
 18 | Point Update
 19 | ====================
 20 | i            0  1  2  3  4  5  6  7   8   9
 21 | A[i]         0  0  0  0  0  0  0  0   0   0
 22 | SumTill[i]   0  0  0  0  0  0  0  0   0   0
 23 | ___
 24 | Now +5 to [3]
 25 | ___
 26 | i            0  1  2  3  4  5  6  7   8   9
 27 | A[i]         0  0  0  0 +5  0  0  0   0   0
 28 | SumTill[i]   0  0  0  0  5  5  5  5   5   5
 29 | ___
 30 | In Point Update form:
 31 | A[3]       += +5
 32 | BITarr[3]  += +5 (and, +5 also proprates to other elements, acc to algorithm of BIT)
 33 | ___
 34 | In Point Update form (in general form)
 35 | A[i]       += +V
 36 | BITarr[i]  += +V (and, +V also proprates to other elements, acc to algorithm of BIT)
 37 | ___
 38 | 
 39 | 
 40 | 
 41 | ====================
 42 | > Section 2
 43 | ====================
 44 | Range Update
 45 | ====================
 46 | Assume
 47 | ___
 48 | i                  0  1  2  3  4  5  6  7   8   9
 49 | A[i]               0  0  0  0  0  0  0  0   0   0
 50 | SumTill[i]         0  0  0  0  0  0  0  0   0   0
 51 | ___
 52 | Now +5 to [3 to 7]
 53 | ___
 54 | i                  0  1  2  3  4  5  6  7   8   9
 55 | A[i]               0  0  0  5  5  5  5  5   0   0
 56 | SumTill[i]         0  0  0  5 10 15 20 25  25  25
 57 | ___
 58 | Here
 59 | ___
 60 | SumTill[i]         0  0  0  5 10 15 20 25  25  25
 61 | is
 62 | i                  0  1  2  3  4  5  6  7   8   9
 63 | X1[i]             *0  0  0  5  5  5  5  5   0   0
 64 | X2[i]             +0  0  0 10 10 10 10 10 -25 -25
 65 | .
 66 | > Tranformation formula
 67 | > Where, SumTill[i] = i * X1[i] - X2[i], This will not be used anywhere below, but is key to derive BIT form
 68 | .
 69 | ___
 70 | Here
 71 | ___
 72 | i                  0  1  2        3  4  5  6   7      8   9
 73 | X1[i]             *0  0  0        5  5  5  5   5      0   0
 74 | X2[i]             +0  0  0       10 10 10 10  10    -25 -25
 75 | ___
 76 | looks like:
 77 | ___
 78 | i                  0  1  2        3  4  5  6   7      8   9
 79 | index names                       3            7    7+1
 80 | -------------------------------------------------------------
 81 | BIT-like-form-X1  *0  0  0       +5  0  0  0   0     -5   0
 82 | BIT-like-form-X2  +0  0  0       10  0  0  0   0    -35   0
 83 | ___
 84 | 
 85 | Above in Point Update form: (see above, Section 1)
 86 | this is
 87 | BITX1[3]   =  +5
 88 | BITX1[7+1] =  -5
 89 | BITX2[3]   = +10
 90 | BITX2[7+1] = -35
 91 | So, +5 to [3 to 7] came down to above.
 92 | These above 4 formulas are for range_update(3,7,5).
 93 | ___
 94 | 
 95 | Exact above (in general form) looks like:
 96 | ___
 97 | index              0  1  2        3  4  5  6   7     8   9
 98 | index names                       i            j   j+1
 99 | -------------------------------------------------------------
100 | BIT-like-form-X1  *0  0  0       +V  0  0  0   0    -V   0
101 | BIT-like-form-X2  +0  0  0  (i-1)*V  0  0  0   0  -j*V   0
102 | ___
103 | Above in Point Update form (in general form): (see above, Section 1)
104 | this is
105 | ___
106 | (in general form)
107 | BITX1[i]   +=        +V
108 | BITX1[j+1] +=        -V
109 | BITX2[i]   +=  +(i-1)*V
110 | BITX2[j+1] +=      -j*V
111 | So, +V to [i to j] came down to above
112 | These above 4 formulas are for range_update(i,j,V).
113 | 
114 | So, you will need two arrays of size A[],
115 | however update of range (i,j)
116 | should be logN for BITX1 &
117 | another logN for BITX2
118 | which is 2*logN, still O(logN), faster than O(N) updating all values of (i,j), so above 'Tranformation formula' is key
119 | ___
120 | 
121 | 
122 | -------------------------------------------------------------------------------- /MATHEMATICS.MD: -------------------------------------------------------------------------------- 1 | 2 |
  3 | 
  4 | ====
  5 | This Mathematics Notes is from  khanacademy.org/math
  6 | where I got Ramanujan in 60 actual days - possibly 3 hours of work everyday
  7 | 
  8 | ====
  9 | BODMAS is an acronym and it stands for Bracket, Of, Division, Multiplication, Addition and Subtraction.
 10 | In certain regions,
 11 |   PEDMAS (Parentheses, Exponents, Division, Multiplication, Addition and Subtraction) is the synonym of BODMAS.
 12 | 
 13 | ====
 14 | non-statistical      - single value like age
 15 | statistical question - multiple values - need to gather info about 1+ items/people, etc.
 16 | 
 17 | double number lines - show the ratio
 18 | dot plot - most often/ frequent, helps finding median, more than x, max and specific - below x
 19 | bar graph/histogram - helps finding more than x, less than (some are good, some dont tell)
 20 | box & whiskers plot - helps finding median
 21 | 
 22 | distribution
 23 |   left-tailed - decreasing towards left   (approximate: skewed to the left:  mean is to the left  of median and mode)
 24 |   right-tailed - decreasing towards right (approximate: skewed to the right: mean is to the right of median and mode)
 25 |   approximately symmetrical - both left-tailed & right-tailed - median will be close to center
 26 |  
 27 |   for dot plot (only?) we can see below:
 28 |     outlier = an end element that is far to the right/left - isolated one data point (unusually low or unusually high)
 29 |     cluster = grouping of data, between two data points, from x to y, saying 100 to 200
 30 |     peak = most frequent data item
 31 |     gap = (no values)?
 32 | 
 33 | mean    (a+b+c+d)/4
 34 | median  mid element, OR average(2 mid elements)
 35 | mode    most often
 36 | range = max - min
 37 | 
 38 | . interquartile range (IQR)
 39 | .     sort asc
 40 | .     find median
 41 | .     IQR = lower half's median - upper half's median
 42 | 
 43 | box plot
 44 | min        Q1                     median    Q3                max
 45 | min        lower quartile         median    upper quartile    max
 46 | 
 47 | range = max - min
 48 | 4     = 15    - 11
 49 |                             // 0?     ??
 50 | min     median      max
 51 | 11?     13          15?
 52 | 
 53 | |a - b| = |a| - |b|
 54 | |a - b| = |b - a|
 55 | 
 56 | . Mean absolute deviation (MAD)
 57 | .     find mean
 58 | .     average (abs each ele - mean)
 59 | 
 60 | ====
 61 | algebra
 62 |     variables
 63 |     expressions
 64 |     equations = a statement that two expressions are equal
 65 |         value of the variable that makes a true equation is called a solution to the equation
 66 | we always have to do the same thing to both sides of an equation to keep it true
 67 | Addition and subtraction are inverse operations
 68 | 
 69 | inverse operation of addition is subtraction
 70 | inverse operation of subtraction is addition
 71 | 
 72 | Multiplication and division are inverse operations
 73 | inverse operation of division is multiplication
 74 | inverse operation of multiplication is division
 75 | 
 76 | Inequalities show the relation between two expressions that are not equal.
 77 | 
 78 | >  open circle and arrow
 79 | >= closed circle and arrow
 80 | 
 81 | independent variable is a variable that represents a quantity that is being manipulated in an experiment
 82 | dependent variable represents a quantity whose value depends on how the independent variable is manipulated
 83 | 
 84 | ====
 85 | 0 is neither -ve or +ve
 86 | 0/n=0         where n != 0 
 87 | n/0=undefined
 88 | 0/0=undefined
 89 | 
 90 | 1*n = n
 91 | 
 92 | 1*0 = 0
 93 | 1*1 = 1
 94 | 
 95 | n^1 = n
 96 | n^0 = 1       where n != 0
 97 | 0^n=0         where n != 0
 98 | 0^0 = undefined
 99 | 
100 | ====
101 | 25% of 600 is 150
102 | 25% . 600 = 150
103 | percent . base = amount
104 | 
105 | 10% = 10/100 = 1/10 = 0.1
106 | 
107 | ~  approximately equal
108 | 
109 | ====
110 | shares of stock = how much a person (shareholder) owns in a company
111 |     profits (dividends) can be equal or not
112 | 
113 | ====
114 | polyhedron
115 | polyhedra
116 |     3d shape
117 |     flat surfaces
118 |     straight edges
119 | Surface area is   the amount of space covering the outside of a three-dimensional shape.
120 | 
121 | ====
122 | TIPS for khanacademy.org/math
123 | 
124 | use your calculator instead of given calculator - its a bit cramped
125 | 
126 | How to work?
127 |     instead of doing only arithmetic, OR geometry
128 |     i would do 1st class, then 2nd class,
129 | 		this looks a bit slow but they are better in understanding many things at little bit each
130 | 
131 | verify
132 |     after each answer
133 |     i verify in a different way
134 |         if 2+4+5 is given
135 |             first,               i will add 2+4 then add 5    = 11
136 |             for verification,    i will add 4+5 then add 2    = 11
137 |     if both are same, i will Check/ Submit
138 | 
139 | viewed videos at
140 |     X2 speed, possibly after viewing few videos
141 |         1st 1 or 2 videos are at 1.5 video speed rate
142 |         later videos are at 2 video speed rate
143 | 
144 | if its text box
145 |     that does not give the symbols input
146 |     then you can press ENTER to submit answer
147 | 
148 | if from desktop
149 |     you can view all videos at once, continuously
150 | 
151 | From 6th grade the volume of video seems very slow
152 |     GOOD PLUGIN
153 |         I used Volume Booster extension of Chrome browser
154 | 		listen to video/audio sound a bit louder
155 | 		https://chrome.google.com/webstore/detail/volume-booster/ejkiikneibegknkgimmihdpcbcedgmpo/related
156 |     BAD PLUGIN
157 |         I installed another chrome extension
158 | 		https://chrome.google.com/webstore/detail/youtube-playback-speed-co/hdannnflhlmdablckfkjpleikpphncik/reviews?hl=en
159 | 		and went at 2.25 speed
160 | 		remembers speed 2.00    Options > Settings tab > 'Remember Playback Speed For All Videos'
161 | 		but 2.25 failed
162 | 		This failed as the points were not coming as usual
163 | 
164 | ====
165 | 
166 | -------------------------------------------------------------------------------- /PRINT-EVERYTHING.cpp: -------------------------------------------------------------------------------- 1 | 2 | 3 | void print() { 4 | 5 | printf("%c", 'c'); 6 | 7 | cout << endl; // ok 8 | cout << "\n"; // better sometimes for performance 9 | 10 | cout << 'a' << "\n"; 11 | cout << "abc" << "\n"; 12 | cout << 1 << "\n"; 13 | 14 | cout << "[" << 100 << "," << 200 << "]" << "\n"; 15 | 16 | cout << setw(10) << 100 << "\n"; 17 | cout << setw(10) << setfill('-') << 100 << "\n"; 18 | 19 | 20 | string s1 = "hello"; 21 | cout << s1 << "\n"; 22 | 23 | stringstream output1; 24 | output1 << "hello" << "\n"; 25 | output1 << "world" << "\n"; 26 | cout << output1.str(); 27 | } 28 | 29 | 30 | template 31 | void printA(T *A, size_t N, bool bNewLine = true) { // print A[] 32 | for (size_t i = 0; i < N; i++) { 33 | cout << A[i] << " "; 34 | } 35 | if (bNewLine) { 36 | cout << "\n"; 37 | } 38 | } 39 | 40 | template 41 | void printVD(T c1, bool bNewLine = true) { // print vector, deque 42 | for (size_t i = 0; i < c1.size(); i++) { 43 | cout << c1[i] << " "; 44 | } 45 | if (bNewLine) { 46 | cout << "\n"; 47 | } 48 | } 49 | 50 | template 51 | static void printVVDD(T vv1, bool bNewLine = true) { // print vector>, deque> 52 | for (size_t i = 0; i < vv1.size(); i++) { 53 | printVD(vv1[i], bNewLine); 54 | } 55 | if (bNewLine) { 56 | cout << "\n"; 57 | } 58 | } 59 | 60 | template 61 | static void printM(const T &m1, bool bNewLine = true) { // print map 62 | for (auto kv1 : m1) { 63 | cout << kv1.first << " " << kv1.second << endl; 64 | } 65 | if (bNewLine) { 66 | cout << "\n"; 67 | } 68 | } 69 | 70 | 71 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | 2 | Advanced DataStructures & Algorithms 3 | 4 | These were created while learning 5 | NOTE: The old ones could be more buggy :-). Please note to check before using these. 6 | 7 | 8 | # Run as below: 9 | 10 | Example: 11 | g++ quicksort_lomuto.cpp 12 | 13 | 14 | # Star or Fork 15 | If you like, click on Star or click on Fork to suggest changes 16 | 17 | 18 | # Some Useful links 19 | 20 | - Leetcode contest rating predictor - all contests : https://lccn.lbao.site/ 21 | - Leetcode contest rating predictor - specific contest : https://lccn.lbao.site/predicted/weekly-contest-332 22 | 23 | -------------------------------------------------------------------------------- /RMQ-using-NxN.cpp: -------------------------------------------------------------------------------- 1 | // 2 | // beautiful code 3 | // 4 | 5 | #include // min 6 | #include 7 | #include // assert 8 | #include 9 | #include 10 | #include // deque 11 | #include // ifstream 12 | #include // greater 13 | #include // setw, setfill 14 | #include 15 | #include // numeric_limits 16 | #include // map, multimap 17 | #include 18 | #include // priority_queue (greatest on top, by default, use greater for smallest on top) 19 | #include // set 20 | #include // stringstream 21 | #include // stack 22 | #include // tuple 23 | #include 24 | #include // unordered_set 25 | #include // vector 26 | 27 | using namespace std; 28 | 29 | 30 | bool ON = 1; 31 | bool OFF = 0; 32 | 33 | #ifdef DEBUGG 34 | bool DEBUG_MODE = ON; 35 | bool LOGS = ON; 36 | #else 37 | bool DEBUG_MODE = OFF; 38 | bool LOGS = OFF; 39 | #endif 40 | 41 | template 42 | void debug(Arg&& arg, Args&&... args) { 43 | 44 | if (LOGS) { 45 | std::ostream& out = std::cout; 46 | out << std::forward(arg); 47 | using expander = int[]; 48 | ( 49 | 50 | void)expander { 51 | 0, (void(out << ' ' << std::forward(args)), 0)... 52 | }; 53 | } 54 | } 55 | 56 | template 57 | ostream & operator<<(ostream &o1, const vector &v1) { 58 | for (auto it = v1.begin(); it != v1.end(); it++) { 59 | o1 << setw(4) << *it << " "; 60 | } 61 | return o1; 62 | } 63 | 64 | template 65 | vector range(T N1, T N2) { 66 | vector numbers(N2 - N1); 67 | iota(numbers.begin(), numbers.end(), N1); 68 | return numbers; 69 | } 70 | 71 | template 72 | vector zero_till(T N) { 73 | vector numbers(N); 74 | iota(numbers.begin(), numbers.end(), 0); 75 | return numbers; 76 | } 77 | 78 | template 79 | vector one_till(T N) { 80 | vector numbers(N); 81 | iota(numbers.begin(), numbers.end(), 1); 82 | return numbers; 83 | } 84 | 85 | // ----------------------------------- 86 | // ----------------------------------- 87 | // ----------------------------------- 88 | 89 | // #define PTypeVal short // 1 to 50 90 | // 91 | //#define NTypeValue int // 1 to 10^5 92 | //#define MTypeValue int // 1 to 10^5 93 | //#define XTypeValue int // 1 to 10^9 94 | //#define VTypeValue int // 0 to 10^6 95 | //#define TypeValue unsigned long long // 0 to 10^6 96 | //#define PTypeVal unsigned long long 97 | //#define VTypeVal unsigned short // long long 98 | //#define PTypeVal long long 99 | //#define DTypeVal long long 100 | //#define TTypeVal unsigned long long 101 | //#define LTypeVal unsigned long long 102 | //#define SumOfLTypeVal unsigned long long 103 | 104 | // #define PTypeVal unsigned long long 105 | #define NTypeVal int 106 | #define EleTypeVal int 107 | #define EleTypeVeryLargVal unsigned long long 108 | // #define SizeT unsigned int 109 | // ----------------------------------- 110 | 111 | /* 112 | struct Node 113 | { 114 | NTypeVal i; 115 | EleTypeVal d; 116 | Node *l, *r, *p; // left, right, parent 117 | }; 118 | */ 119 | 120 | template 121 | class NxN { 122 | 123 | NType N; 124 | EleType Ai; 125 | deque v1; // input array, with N+1 elements - element at index 0, is not used 126 | 127 | deque v_seg; // v_seg array, with N+1 elements - element at index 0, is not used 128 | deque> v_seg2; // v_seg array, with N+1 elements - element at index 0, is not used 129 | 130 | // unordered_set s1; 131 | // unordered_multimap > m1; 132 | // unordered_map , EleTypeVal> m1; 133 | 134 | // unordered_multimap > 135 | // pair least_gr_eq; 136 | 137 | //NType least_gr_eq_ri; 138 | //EleType least_gr_eq_rmin; 139 | 140 | public: 141 | 142 | NxN(istream &cin) { 143 | cin >> N; 144 | 145 | // v1.reserve(N); 146 | 147 | // get arr 148 | for (NType i = 0; i <= N - 1; i++) { 149 | cin >> Ai; 150 | v1.push_back(Ai); 151 | } 152 | 153 | ///////// cout << one_till(N) << endl; 154 | // cout << v1 << endl; 155 | // cout << setw(4) << Ai << " "; 156 | } 157 | 158 | void build_for_NxN_RMQ_wrapper() { 159 | v_seg2.resize(N); 160 | for (int i = 0; i <= N - 1; i++) { 161 | v_seg2[i].resize(N); 162 | fill(v_seg2[i].begin(), v_seg2[i].end(), numeric_limits::max()); 163 | } 164 | build_for_NxN_RMQ(); 165 | } 166 | 167 | void build_for_NxN_RMQ() { 168 | 169 | for (NType ql = 0; ql <= N - 1; ql++) { 170 | v_seg2[ql][ql] = v1[ql]; 171 | } 172 | 173 | for (NType ql = 0; ql <= N - 1; ql++) { 174 | for (NType qh = ql + 1; qh <= N - 1; qh++) { 175 | v_seg2[ql][qh] = min(v_seg2[ql][qh - 1], v1[qh]); 176 | } 177 | } 178 | 179 | } 180 | 181 | void NxN_RMQ() { 182 | for (NType ql = 0; ql <= N - 1; ql++) { 183 | for (NType qh = ql; qh <= N - 1; qh++) { 184 | 185 | cout << "[" << ql << "," << qh << "] = " << v_seg2[ql][qh] << endl; 186 | } 187 | } 188 | } 189 | 190 | void doMain() { 191 | 192 | build_for_NxN_RMQ_wrapper(); 193 | NxN_RMQ(); 194 | 195 | } 196 | }; 197 | 198 | // testsss 199 | #define ReturnCountTypeValue char 200 | vector < pair < vector, vector>> tests = { 201 | /* { 202 | { 203 | "5", 204 | "5 10 40 30 28" 205 | }, 206 | { 0, 0, 0, 0, 0, 0, 0, 0 } // 4(new) 3 (old) 207 | }, */ 208 | /* 209 | */ 210 | { 211 | { 212 | "11", 213 | "9 3 7 1 8 12 10 20 15 18 5" 214 | }, 215 | { 0, 0, 0, 0, 0, 0, 0, 0 } // 4(new) 3 (old) 5*10 = 50 216 | }, 217 | /* 218 | { 219 | { 220 | "12", 221 | "9 3 7 1 8 12 12 10 20 15 18 5" 222 | }, 223 | { 0, 0, 0, 0, 0, 0, 0, 0 } // 4(new) 3 (old) 6*10 = 50 224 | }, 225 | 226 | { 227 | { 228 | "5", 229 | "1 2 3 4 5" 230 | }, 231 | { 0, 0, 0, 0, 0, 0, 0, 0 } // 4(new) 3 (old) 232 | }*/ 233 | }; 234 | 235 | // template 236 | template 237 | class Cls1 { 238 | 239 | // HNType n; 240 | // MType m; 241 | // deque > p1; 242 | // XType x; 243 | // string S; 244 | // LenType k; 245 | // TType type; 246 | // HVType v; 247 | // VType v; 248 | // PType P; 249 | // DType D; 250 | // KType K; 251 | // Heap> h1; 252 | // multiset se1; 253 | // deque p1; 254 | 255 | public: 256 | 257 | Cls1() { 258 | // LOGS = OFF; 259 | } 260 | 261 | 262 | vector testFunction(istream & cin) { 263 | // debug("testFunction - begin\n\n"); 264 | vector res; 265 | // -------------------- 266 | 267 | // LOGS = 0; 268 | 269 | 270 | NxN o1(cin); 271 | o1.doMain(); 272 | 273 | 274 | auto actual_result = 0; 275 | res.push_back(actual_result); 276 | 277 | return res; 278 | } 279 | 280 | }; 281 | 282 | 283 | int main() { 284 | 285 | if (!DEBUG_MODE) { 286 | 287 | Cls1 o; 288 | o.testFunction(cin); 289 | 290 | return 0; 291 | } 292 | else { 293 | 294 | for (unsigned long i = 0; i < tests.size(); i++) { 295 | // debug("----------------------- input getting ready ----------------------------- ", "\n"); 296 | 297 | auto input = tests[i].first; 298 | auto expected_output = tests[i].second; 299 | 300 | std::stringstream ss; 301 | istream &cin = ss; 302 | 303 | for (size_t i = 0; i < input.size(); i++) { 304 | // debug(input[i], "\n"); 305 | ss << input[i] << endl; 306 | } 307 | 308 | /* 309 | ifstream ifs; 310 | // ifs.open("../lr_input09_dummy.txt"); 311 | ifs.open("../lr_input09.txt"); 312 | string temp; 313 | vector a; 314 | getline(ifs, temp); ss << temp << endl; 315 | getline(ifs, temp); ss << temp << endl; 316 | */ 317 | 318 | 319 | // debug("----------------------- input ready ----------------------------- ", "\n"); 320 | 321 | Cls1 o; 322 | // Cls1 o; 323 | // Cls1 o; 324 | // auto actual_result = o.testFunction(cin, q)[0]; 325 | auto actual_result = o.testFunction(cin)[0]; 326 | 327 | // for (PTypeVal k = 0; k < q; k++) { 328 | // Cls1 o; 329 | // // // debug("\tactual_result ", actual_result, " ", "expected_output ", expected_output[k], "\n"); 330 | // 331 | // // assert(actual_result == expected_output[k]); 332 | // } 333 | 334 | // break; 335 | 336 | } // for tests.size() 337 | 338 | return 0; 339 | } 340 | 341 | return 0; 342 | } 343 | -------------------------------------------------------------------------------- /RMQ-using-cartesian-tree.cpp: -------------------------------------------------------------------------------- 1 | // 2 | // beautiful code 3 | // 4 | 5 | #include "stdafx.h" 6 | 7 | #include // min 8 | #include 9 | #include // assert 10 | #include 11 | #include 12 | #include // deque 13 | #include // ifstream 14 | #include // greater 15 | #include // setw, setfill 16 | #include 17 | #include // numeric_limits 18 | #include // map, multimap 19 | #include 20 | #include // priority_queue (greatest on top, by default, use greater for smallest on top) 21 | #include // set 22 | #include // stringstream 23 | #include // stack 24 | #include // tuple 25 | #include 26 | #include // unordered_set 27 | #include // vector 28 | 29 | using namespace std; 30 | 31 | 32 | bool ON = 1; 33 | bool OFF = 0; 34 | 35 | #ifdef DEBUGG 36 | bool DEBUG_MODE = ON; 37 | bool LOGS = ON; 38 | #else 39 | bool DEBUG_MODE = OFF; 40 | bool LOGS = OFF; 41 | #endif 42 | 43 | template 44 | void debug(Arg&& arg, Args&&... args) { 45 | 46 | if (LOGS) { 47 | std::ostream& out = std::cout; 48 | out << std::forward(arg); 49 | using expander = int[]; 50 | ( 51 | 52 | void)expander { 53 | 0, (void(out << ' ' << std::forward(args)), 0)... 54 | }; 55 | } 56 | } 57 | 58 | template 59 | ostream & operator<<(ostream &o1, const vector &v1) { 60 | for (auto it = v1.begin(); it != v1.end(); it++) { 61 | o1 << setw(4) << *it << " "; 62 | } 63 | return o1; 64 | } 65 | 66 | template 67 | vector range(T N1, T N2) { 68 | vector numbers(N2 - N1); 69 | iota(numbers.begin(), numbers.end(), N1); 70 | return numbers; 71 | } 72 | 73 | template 74 | vector zero_till(T N) { 75 | vector numbers(N); 76 | iota(numbers.begin(), numbers.end(), 0); 77 | return numbers; 78 | } 79 | 80 | template 81 | vector one_till(T N) { 82 | vector numbers(N); 83 | iota(numbers.begin(), numbers.end(), 1); 84 | return numbers; 85 | } 86 | 87 | // ----------------------------------- 88 | // ----------------------------------- 89 | // ----------------------------------- 90 | 91 | // #define PTypeVal short // 1 to 50 92 | // 93 | //#define NTypeValue int // 1 to 10^5 94 | //#define MTypeValue int // 1 to 10^5 95 | //#define XTypeValue int // 1 to 10^9 96 | //#define VTypeValue int // 0 to 10^6 97 | //#define TypeValue unsigned long long // 0 to 10^6 98 | //#define PTypeVal unsigned long long 99 | //#define VTypeVal unsigned short // long long 100 | //#define PTypeVal long long 101 | //#define DTypeVal long long 102 | //#define TTypeVal unsigned long long 103 | //#define LTypeVal unsigned long long 104 | //#define SumOfLTypeVal unsigned long long 105 | 106 | // #define PTypeVal unsigned long long 107 | #define NTypeVal long 108 | #define EleTypeVal long 109 | // #define SizeT unsigned int 110 | // #define VeryLargeTypeVal unsigned long long 111 | // ----------------------------------- 112 | 113 | 114 | struct Node 115 | { 116 | NTypeVal i; 117 | EleTypeVal d; 118 | Node *l, *r, *p; // left, right, parent 119 | }; 120 | 121 | 122 | template 123 | class cartesian_tree { 124 | 125 | // https://apps.topcoder.com/forums/?module=RevisionHistory&messageID=1352447 126 | // https://apps.topcoder.com/forums/?module=Thread&threadID=715842&start=0&mc=8 127 | // http://zobayer.blogspot.in/2013/11/various-usage-of-bit.html 128 | // https://www.hackerearth.com/notes/binary-indexed-tree-made-easy-2/ 129 | // http://www.geeksforgeeks.org/binary-indexed-tree-or-fenwick-tree-2/ 130 | // https://www.topcoder.com/community/data-science/data-science-tutorials/binary-indexed-trees/ 131 | 132 | NType N; 133 | vector v1; // input array, with N+1 elements - element at index 0, is not used 134 | vector BITree; // BITree array, with N+1 elements - element at index 0, is not used 135 | 136 | unordered_multimap > m1; 137 | // unordered_map , EleTypeVal> m1; 138 | 139 | // unordered_multimap > 140 | // pair least_gr_eq; 141 | 142 | //NType least_gr_eq_ri; 143 | //EleType least_gr_eq_rmin; 144 | 145 | struct Node* getNewNode(EleType &data1, NType &index1) { 146 | struct Node* temp = new Node(); 147 | 148 | temp->i = index1; 149 | temp->d = data1; 150 | 151 | temp->l = NULL; 152 | temp->r = NULL; 153 | temp->p = NULL; 154 | 155 | return temp; 156 | } 157 | 158 | struct Node *root = NULL, *right_most = NULL; 159 | 160 | public: 161 | 162 | cartesian_tree(istream &cin) { 163 | cin >> N; 164 | 165 | ///////// cout << one_till(N) << endl; 166 | // cout << v1 << endl; 167 | 168 | EleType Ai; 169 | for (NType i = 1; i <= N; i++) { 170 | cin >> Ai; 171 | 172 | ///////// cout << setw(4) << Ai << " "; 173 | 174 | auto new1 = getNewNode(Ai, i); 175 | if (root == NULL) { 176 | root = new1; 177 | right_most = new1; 178 | } 179 | else { 180 | while (right_most->r) { 181 | right_most = right_most->r; 182 | } 183 | 184 | 185 | struct Node* temp = right_most; 186 | while (temp && 187 | (temp->d >= new1->d)) { 188 | temp = temp->p; 189 | } 190 | 191 | if (temp) { 192 | new1->l = temp->r; 193 | temp->r = new1; 194 | 195 | 196 | new1->p = temp; 197 | if (new1->l) { 198 | new1->l->p = new1; 199 | } 200 | 201 | right_most = new1; 202 | } 203 | else { 204 | new1->l = root; 205 | root = new1; 206 | 207 | if (new1->l) { 208 | new1->l->p = new1; 209 | } 210 | 211 | right_most = root; 212 | } 213 | 214 | } 215 | } 216 | ///////// cout << endl; 217 | 218 | build__rmq_from_bfs_treelevelorder(root); 219 | } 220 | 221 | void build__rmq_from_bfs_treelevelorder(struct Node *root) { 222 | if (!root) { 223 | return; 224 | } 225 | 226 | deque q1; 227 | q1.push_back(root); 228 | 229 | NType l, r; 230 | 231 | auto temp = root; 232 | 233 | auto min = temp->d; 234 | l = 1; r = N; 235 | 236 | m1.insert({ l,{ r, min } }); 237 | 238 | while (!q1.empty()) { 239 | 240 | temp = q1.front(); 241 | 242 | min = temp->d; 243 | l = r = temp->i; 244 | 245 | 246 | 247 | if (l == 2) { 248 | int iii = 0; 249 | } 250 | 251 | 252 | 253 | q1.pop_front(); 254 | 255 | // to self is must - [l,l]=min 256 | m1.insert({ l,{ r, min } }); 257 | 258 | if (temp->l) { 259 | q1.push_back(temp->l); 260 | l = temp->l->i; 261 | } 262 | else { 263 | } 264 | 265 | if (temp->r) { 266 | q1.push_back(temp->r); 267 | r = temp->r->i; 268 | } 269 | 270 | // l to right is next 271 | if (l != temp->i) { 272 | m1.insert({ l,{ temp->i, min } }); 273 | } 274 | if (r != temp->i) { 275 | m1.insert({ temp->i,{ r, min } }); 276 | } 277 | 278 | /* 279 | max 3 per l 280 | [?,l] 281 | [l,l] 282 | [l,?] 283 | */ 284 | 285 | // m1.insert(make_pair(l, make_pair(r, min))); 286 | // unordered_multimap > m1; 287 | // m1.insert(l, pair); 288 | // m1[l] = { r, min }; 289 | // m1[0] = { 0, 0 }; 290 | 291 | delete temp; 292 | } 293 | 294 | // cout << endl; 295 | } 296 | 297 | pair * find_rmq(const NType &l, const NType &r) { 298 | 299 | pair *p_least_gr_eq = NULL; 300 | 301 | /* 302 | if (l == 5 && r == 10) { 303 | int iii = 0; 304 | } 305 | if (l == 1 && r == 1) { 306 | int iii = 0; 307 | }*/ 308 | 309 | 310 | NType i; 311 | 312 | for (auto x : { l, r }) { 313 | 314 | // ##1 ok place 315 | auto it = m1.find(x); // it_r_val 316 | /* 317 | max 3 per x 318 | [?,x] 319 | [x,x] 320 | [x,?] 321 | */ 322 | 323 | if ((*it).second.first <= r) { 324 | if (x == l) { 325 | p_least_gr_eq = &((*it).second); 326 | // least_gr_eq_ri = (*it).second.first; 327 | // least_gr_eq_rmin = (*it).second.second; 328 | } 329 | else { 330 | if ((*it).second.second < p_least_gr_eq->second) { 331 | p_least_gr_eq = &((*it).second); 332 | } 333 | } 334 | } 335 | 336 | i = 1; 337 | while (i <= 3) { 338 | 339 | // if there are more 340 | ++it; 341 | if (it == m1.end()) { 342 | break; 343 | } 344 | 345 | // range starting with x 346 | if ((*it).first != x) { 347 | break; 348 | } 349 | 350 | // comments outdated 351 | // on the, or right of the r 352 | // lesser than previous one - LCA!!!!!!!! 353 | if ((*it).second.first <= r) { 354 | p_least_gr_eq = &((*it).second); 355 | } 356 | 357 | i++; 358 | } 359 | 360 | } 361 | 362 | // least_gr_eq = *p_least_gr_eq; 363 | 364 | return p_least_gr_eq; 365 | } 366 | 367 | void print_array_indexes() { 368 | stringstream output; 369 | output << "index: "; 370 | for (int i = 1; i <= N; i++) { output << left << setw(4) << i; } 371 | cout << output.str() << endl; 372 | } 373 | 374 | void doMain() { 375 | // TODO 376 | //////// CHECK EQUAL ELEMENTS 377 | 378 | EleType minTillNow; 379 | 380 | pair *p_least_gr_eq = NULL; 381 | 382 | for (NType l = 1; l <= N; l++) { 383 | minTillNow = numeric_limits::max(); 384 | 385 | for (NType r = l; r <= N; r++) { 386 | 387 | p_least_gr_eq = find_rmq(l, r); 388 | minTillNow = min(minTillNow, p_least_gr_eq->second); 389 | 390 | cout << "[" << l << "," << r << "] = " << minTillNow << endl; 391 | } 392 | } 393 | 394 | return; 395 | } 396 | }; 397 | 398 | /* 399 | struct Node* temp = root; 400 | while (temp) { 401 | if (temp->i < l) { 402 | temp = temp->r; 403 | } 404 | else if (temp->i > r) { 405 | temp = temp->l; 406 | } 407 | else { 408 | break; 409 | 410 | /// if ((l <= temp->i) && (temp->i <= r)) { 411 | /// // we have i between li & ri 412 | /// // found LCA 413 | /// break; 414 | /// } 415 | } 416 | } 417 | 418 | EleType min = 0; 419 | if (temp) { 420 | min = temp->d; 421 | } 422 | */ 423 | 424 | 425 | // testsss 426 | #define ReturnCountTypeValue char 427 | vector < pair < vector, vector>> tests = { 428 | /* { 429 | { 430 | "5", 431 | "5 10 40 30 28" 432 | }, 433 | { 0, 0, 0, 0, 0, 0, 0, 0 } // 4(new) 3 (old) 434 | }, */ 435 | /* 436 | { 437 | { 438 | "11", 439 | "9 3 7 1 8 12 10 20 15 18 5" 440 | }, 441 | { 0, 0, 0, 0, 0, 0, 0, 0 } // 4(new) 3 (old) 5*10 = 50 442 | }, 443 | */ 444 | { 445 | { 446 | "12", 447 | "9 3 7 1 8 12 12 10 20 15 18 5" 448 | }, 449 | { 0, 0, 0, 0, 0, 0, 0, 0 } // 4(new) 3 (old) 6*10 = 50 450 | }, 451 | 452 | /* 453 | { 454 | { 455 | "5", 456 | "1 2 3 4 5" 457 | }, 458 | { 0, 0, 0, 0, 0, 0, 0, 0 } // 4(new) 3 (old) 459 | }*/ 460 | }; 461 | 462 | template 463 | class ClsMain1 { 464 | NType N; 465 | // deque p1; 466 | public: 467 | 468 | ClsMain1() { 469 | } 470 | 471 | void doMain(istream &cin) { 472 | cartesian_tree o1(cin); 473 | o1.doMain(); 474 | } 475 | }; 476 | 477 | // template 478 | 479 | template 480 | class Cls1 { 481 | 482 | // HNType n; 483 | // MType m; 484 | // deque > p1; 485 | // XType x; 486 | // string S; 487 | // LenType k; 488 | // TType type; 489 | // HVType v; 490 | // VType v; 491 | // PType P; 492 | // DType D; 493 | // KType K; 494 | // Heap> h1; 495 | // multiset se1; 496 | // deque p1; 497 | 498 | public: 499 | 500 | Cls1() { 501 | // LOGS = OFF; 502 | } 503 | 504 | 505 | vector testFunction(istream & cin) { 506 | // debug("testFunction - begin\n\n"); 507 | vector res; 508 | // -------------------- 509 | 510 | // LOGS = 0; 511 | 512 | 513 | ClsMain1 p1; 514 | p1.doMain(cin); 515 | 516 | 517 | auto actual_result = 0; 518 | res.push_back(actual_result); 519 | 520 | return res; 521 | } 522 | 523 | }; 524 | 525 | 526 | ifstream ifs; 527 | int main() { 528 | 529 | if (DEBUG_MODE) { 530 | 531 | for (unsigned long i = 0; i < tests.size(); i++) { 532 | // debug("----------------------- input getting ready ----------------------------- ", "\n"); 533 | 534 | 535 | 536 | /*{ 537 | }*/ 538 | 539 | auto input = tests[i].first; 540 | auto expected_output = tests[i].second; 541 | 542 | std::stringstream ss; 543 | istream &cin = ss; 544 | 545 | for (size_t i = 0; i < input.size(); i++) { 546 | // debug(input[i], "\n"); 547 | ss << input[i] << endl; 548 | } 549 | 550 | /* 551 | // ifs.open("../lr_input09_dummy.txt"); 552 | ifs.open("../lr_input09.txt"); 553 | string temp; 554 | vector a; 555 | getline(ifs, temp); ss << temp << endl; 556 | getline(ifs, temp); ss << temp << endl; 557 | */ 558 | 559 | 560 | // debug("----------------------- input ready ----------------------------- ", "\n"); 561 | 562 | Cls1 o; 563 | // Cls1 o; 564 | // Cls1 o; 565 | // auto actual_result = o.testFunction(cin, q)[0]; 566 | auto actual_result = o.testFunction(cin)[0]; 567 | 568 | // for (PTypeVal k = 0; k < q; k++) { 569 | // Cls1 o; 570 | // // // debug("\tactual_result ", actual_result, " ", "expected_output ", expected_output[k], "\n"); 571 | // 572 | // // assert(actual_result == expected_output[k]); 573 | // } 574 | 575 | // break; 576 | } 577 | } 578 | else { 579 | 580 | // PTypeVal q; 581 | // cin >>q; 582 | 583 | Cls1 o; 584 | // Cls1 o; 585 | // Cls1 o; 586 | o.testFunction(cin); 587 | 588 | } 589 | 590 | return 0; 591 | } 592 | -------------------------------------------------------------------------------- /RMQ-using-sparse-table.cpp: -------------------------------------------------------------------------------- 1 | // 2 | // beautiful code 3 | // 4 | 5 | #include // max, max 6 | #include 7 | #include // assert 8 | #include 9 | #include 10 | #include // deque 11 | #include // ifstream 12 | #include // greater 13 | #include // setw, setfill 14 | #include 15 | #include // numeric_limits 16 | #include // map, multimap 17 | #include 18 | #include // priority_queue (greatest on top, by default, use greater for smallest on top) 19 | #include // set 20 | #include // stringstream 21 | #include // stack 22 | #include // tuple 23 | #include 24 | #include // unordered_set 25 | #include // vector 26 | 27 | using namespace std; 28 | 29 | 30 | bool ON = 1; 31 | bool OFF = 0; 32 | 33 | #ifdef DEBUGG 34 | bool DEBUG_MODE = ON; 35 | bool LOGS = ON; 36 | #else 37 | bool DEBUG_MODE = OFF; 38 | bool LOGS = OFF; 39 | #endif 40 | 41 | template 42 | void debug(Arg&& arg, Args&&... args) { 43 | 44 | if (LOGS) { 45 | std::ostream& out = std::cout; 46 | out << std::forward(arg); 47 | using expander = int[]; 48 | ( 49 | 50 | void)expander { 51 | 0, (void(out << ' ' << std::forward(args)), 0)... 52 | }; 53 | } 54 | } 55 | 56 | template 57 | ostream & operator<<(ostream &o1, const vector &c) { 58 | for (auto it = c.begin(); it != c.end(); it++) { 59 | o1 << setw(4) << *it << " "; 60 | } 61 | return o1; 62 | } 63 | 64 | template 65 | ostream & operator<<(ostream &o1, const deque &c) { 66 | for (auto it = c.begin(); it != c.end(); it++) { 67 | o1 << setw(4) << *it << " "; 68 | } 69 | return o1; 70 | } 71 | 72 | template 73 | vector range(T N1, T N2) { 74 | vector numbers(N2 - N1); 75 | iota(numbers.begin(), numbers.end(), N1); 76 | return numbers; 77 | } 78 | 79 | template 80 | vector zero_till(T N) { 81 | vector numbers(N); 82 | iota(numbers.begin(), numbers.end(), 0); 83 | return numbers; 84 | } 85 | 86 | template 87 | vector one_till(T N) { 88 | vector numbers(N); 89 | iota(numbers.begin(), numbers.end(), 1); 90 | return numbers; 91 | } 92 | 93 | // ----------------------------------- 94 | // ----------------------------------- 95 | // ----------------------------------- 96 | 97 | // #define PTypeVal short // 1 to 50 98 | // 99 | //#define NTypeValue int // 1 to 10^5 100 | //#define MTypeValue int // 1 to 10^5 101 | //#define XTypeValue int // 1 to 10^9 102 | //#define VTypeValue int // 0 to 10^6 103 | //#define TypeValue unsigned long long // 0 to 10^6 104 | //#define PTypeVal unsigned long long 105 | //#define VTypeVal unsigned short // long long 106 | //#define PTypeVal long long 107 | //#define DTypeVal long long 108 | //#define TTypeVal unsigned long long 109 | //#define LTypeVal unsigned long long 110 | //#define SumOfLTypeVal unsigned long long 111 | 112 | /* 113 | struct Node 114 | { 115 | NTypeVal i; 116 | EleTypeVal d; 117 | Node *l, *r, *p; // lefti, righti, parent 118 | }; 119 | */ 120 | 121 | // #define PTypeVal unsigned long long 122 | // #define EleTypeVal unsigned long long 123 | // #define EleTypeVeryLargVal unsigned long long 124 | // #define SizeT unsigned int 125 | 126 | #define NTypeVal unsigned int 127 | #define EleTypeVal unsigned long 128 | #define NTypeValBig unsigned long 129 | #define EleTypeValBig unsigned long 130 | 131 | template 132 | class sparse_table { 133 | 134 | NType N, i, j; // ai * aj <= max (ai .. aj), i v1; // input array, with N elements 138 | vector> _sparse_table_; // _sparse_table_ array, with N elements // all initially 0, it does not matter what values they have as they will be filled from v1 139 | 140 | vector _log2floor_table_; 141 | 142 | // unordered_set s1; 143 | // unordered_multimap > m1; 144 | // unordered_map , EleTypeVal> m1; 145 | // unordered_multimap > 146 | // pair least_gr_eq; 147 | // NType least_gr_eq_ri; 148 | // EleType least_gr_eq_rmax; 149 | 150 | public: 151 | 152 | sparse_table(istream &cin) { 153 | /* 154 | cout << left << setw(30) << "size of char: " << "-" << pow(2, 8 * sizeof(char) - 1) << " " << pow(2, 8 * sizeof(char) - 1) - 1 << endl; 155 | cout << left << setw(30) << "size of unsigned char: " << " " << 0 << " " << pow(2, 8 * sizeof(unsigned char)) - 1 << endl; 156 | cout << left << setw(30) << "size of short: " << "-" << pow(2, 8 * sizeof(short) - 1) << " " << pow(2, 8 * sizeof(short) - 1) - 1 << endl; 157 | cout << left << setw(30) << "size of unsigned short: " << " " << 0 << " " << pow(2, 8 * sizeof(unsigned short)) - 1 << endl; 158 | cout << left << setw(30) << "size of int: " << "-" << pow(2, 8 * sizeof(int) - 1) << " " << pow(2, 8 * sizeof(int) - 1) - 1 << endl; 159 | cout << left << setw(30) << "size of unsigned int: " << " " << 0 << " " << pow(2, 8 * sizeof(unsigned int)) - 1 << endl; 160 | cout << left << setw(30) << "size of long: " << "-" << pow(2, 8 * sizeof(long) - 1) << " " << pow(2, 8 * sizeof(long) - 1) - 1 << endl; 161 | cout << left << setw(30) << "size of unsigned long: " << " " << 0 << " " << pow(2, 8 * sizeof(unsigned long)) - 1 << endl; 162 | cout << left << setw(30) << "size of long long: " << "-" << pow(2, 8 * sizeof(long long) - 1) << " " << pow(2, 8 * sizeof(long long) - 1) - 1 << endl; 163 | cout << left << setw(30) << "size of unsigned long long: " << " " << 0 << " " << pow(2, 8 * sizeof(unsigned long long)) - 1 << endl; 164 | 165 | cout << left << setw(30) << "size of char: " << "-" << 1 << (sizeof(char)) << " " << 1 << (sizeof(char)) - 1 << endl; 166 | cout << left << setw(30) << "size of unsigned char: " << " " << 0 << " " << 1 << (sizeof(unsigned char)) - 1 << endl; 167 | cout << left << setw(30) << "size of short: " << "-" << 1 << (sizeof(short)) << " " << 1 << (sizeof(short)) - 1 << endl; 168 | cout << left << setw(30) << "size of unsigned short: " << " " << 0 << " " << 1 << (sizeof(unsigned short)) - 1 << endl; 169 | cout << left << setw(30) << "size of int: " << "-" << 1 << (sizeof(int)) << " " << 1 << (sizeof(int)) - 1 << endl; 170 | cout << left << setw(30) << "size of unsigned int: " << " " << 0 << " " << 1 << (sizeof(unsigned int)) - 1 << endl; 171 | cout << left << setw(30) << "size of long: " << "-" << 1 << (sizeof(long)) << " " << 1 << (sizeof(long)) - 1 << endl; 172 | cout << left << setw(30) << "size of unsigned long: " << " " << 0 << " " << 1 << (sizeof(unsigned long)) - 1 << endl; 173 | cout << left << setw(30) << "size of long long: " << "-" << 1 << (sizeof(long long)) << " " << 1 << (sizeof(long long)) - 1 << endl; 174 | cout << left << setw(30) << "size of unsigned long long: " << " " << 0 << " " << 1 << (sizeof(unsigned long long)) - 1 << endl; 175 | */ 176 | 177 | // c( 178 | 179 | cin >> N; 180 | // v1.resize(N); 181 | 182 | 183 | 184 | // v1 = { 1,3,5,7,9,11 }; 185 | // v1 = { 5,6,4 ,1,7, 1,3,2 }; 186 | // v1 = { 1,4,2,3 }; 187 | // cout << one_till(N) << endl; 188 | // cout << v1 << endl; 189 | // cout << setw(4) << ai << " "; 190 | 191 | build___sparse_table_ment_tree__for_Range_Query_Max__wrapper(cin); 192 | //for (NType i = 0; i < _sparse_table_.size(); i++) { 193 | // cout << _sparse_table_[i] << endl; 194 | //} 195 | } 196 | 197 | void build___sparse_table_ment_tree__for_Range_Query_Max__wrapper(istream &cin) { 198 | build__sparse_table__for_Range_Max_Query(cin); 199 | } 200 | 201 | ///////// TODO 202 | //////////// when vector or deque? 203 | ///////// TODO 204 | 205 | 206 | 207 | // alefti, arighti & a_mid are indexes of array 208 | // sposi is index of _sparse_table_tree array 209 | // NOTE: sposi runs as if it is BFS 210 | void build__sparse_table__for_Range_Max_Query(istream &cin) { 211 | 212 | // b( 213 | 214 | // create log table - begin 215 | // See: http://www.rapidtables.com/math/algebra/logarithm/Logarithm_Table.htm 216 | _log2floor_table_.resize(N + 1, 0); 217 | for (NType i = 2; i < _log2floor_table_.size(); i++) { 218 | _log2floor_table_[i] = _log2floor_table_[i / 2] + 1; 219 | } 220 | // create log table - end 221 | 222 | _sparse_table_.resize(_log2floor_table_[N] + 1, vector(N)); // _sparse_table_.resize(4 * N); 223 | 224 | // _sparse_table_.resize(_log2floor_table_[N] + 1); 225 | 226 | // _sparse_table_[0].resize(N); 227 | for (NType i = 0; i <= N - 1; i++) { 228 | cin >> _sparse_table_[0][i]; 229 | } 230 | 231 | for (NType row = 1; row < _sparse_table_.size(); row++) { // 1, 2, 3, 4 232 | // _sparse_table_[row].resize(N - ((1 << row) - 1)); 233 | 234 | for (NType i = 0; i + (1 << row) <= N; i++) { 235 | _sparse_table_[row][i] = max(_sparse_table_[row - 1][i], _sparse_table_[row - 1][i + (1 << (row - 1))]); 236 | } 237 | } 238 | } 239 | 240 | void range_max_query__all() { 241 | } 242 | 243 | EleType range_max_query(const NType &qli, const NType &qri) { 244 | 245 | // q( 246 | 247 | EleType max1 = max( 248 | _sparse_table_[_log2floor_table_[qri - qli + 1]][qli], 249 | _sparse_table_[_log2floor_table_[qri - qli + 1]][qri - (1 << _log2floor_table_[qri - qli + 1]) + 1] 250 | ); 251 | return max1; 252 | } 253 | 254 | void doMain(istream & cin) { 255 | 256 | // m( 257 | 258 | // range_max_query__all(); 259 | // EleType max = range_max_query(0, 6, 0, N - 1, 0); 260 | 261 | for (NType i = 0; i <= N - 1; i++) { 262 | for (NType j = i + 1; j <= N - 1; j++) { 263 | 264 | EleType max = range_max_query(i, j); 265 | cout << "[" << i << "," << j << "] = " << max << endl; 266 | 267 | // build___sparse_table_ment_tree__for_Range_Query_Max__wrappe r(); 268 | // range_update__wrapper(i, j, ai); 269 | // range_max_query__all(); 270 | } 271 | } 272 | cout << endl; 273 | 274 | /* 275 | for (NType len = 0; len <= N - 1; len++) { 276 | 277 | for (NType i = 0; i + len <= N - 1; i++) { 278 | 279 | // expanding on X - 1,1 2,2 3,3 .. then 1,2 2,3 3,4 280 | EleType max1 = range_max_query(i, i + len); 281 | cout << "[" << i << "," << i + len << "]=" << max1 << " "; 282 | 283 | } 284 | cout << endl; 285 | } 286 | cout << endl; 287 | */ 288 | 289 | 290 | // range_max_query__all(); 291 | // cout << _sparse_table_[0][0] << endl; 292 | } 293 | }; 294 | 295 | // testsss 296 | #define ReturnCountTypeValue char 297 | vector < pair < vector, vector>> tests = { 298 | 299 | 300 | 301 | 302 | 303 | /* 304 | even 305 | 5 2 4 7 6 3 1 2 306 | 307 | 2powlen 1 -> 5 2 4 7 6 3 1 2 308 | 2powlen 2 -> * 2 2 * 4 6 3 1 1 309 | 2powlen 4 -> * 2 + 2 3 1 1 + 310 | 2powlen 8 -> 1 + 311 | */ 312 | 313 | { 314 | { 315 | "8", 316 | "5 2 4 7 6 3 1 2" 317 | }, 318 | { 0, 0, 0, 0, 0, 0, 0, 0 } // 4(new) 3 (old) 5*10 = 50 319 | }, 320 | 321 | 322 | /* 323 | odd 324 | 325 | 5 2 4 6 3 1 2 326 | 327 | 2powlen 1 -> 5 2 4 6 3 1 2 328 | 2powlen 2 -> * 2 2 * 4 3 1 1 329 | 2powlen 4 -> * 2 2 1 1 330 | 2powlen 8 -> 331 | 332 | */ 333 | 334 | 335 | /* 336 | { 337 | { 338 | "5", 339 | "1 1 2 4 2" 340 | }, 341 | { 0, 0, 0, 0, 0, 0, 0, 0 } // 4(new) 3 (old) 5*10 = 50 342 | }, 343 | */ 344 | 345 | 346 | 347 | 348 | 349 | /* 350 | { 351 | { 352 | "7", 353 | "5 2 4 6 3 1 2" 354 | }, 355 | { 0, 0, 0, 0, 0, 0, 0, 0 } // 4(new) 3 (old) 5*10 = 50 356 | },*/ 357 | /* 358 | { 359 | { 360 | "5", 361 | "1 1 2 4 2" 362 | }, 363 | { 0, 0, 0, 0, 0, 0, 0, 0 } // 4(new) 3 (old) 5*10 = 50 364 | }, 365 | { 366 | { 367 | "5", 368 | "5 10 40 30 28" 369 | }, 370 | { 0, 0, 0, 0, 0, 0, 0, 0 } // 4(new) 3 (old) 371 | }, */ 372 | /* 373 | */ 374 | /* { 375 | { 376 | "4 3", 377 | "0 3 3", 378 | "0 3 1", 379 | "0 0 2" 380 | }, 381 | { 0, 0, 0, 0, 0, 0, 0, 0 } // 4(new) 3 (old) 5*10 = 50 382 | }, 383 | { 384 | { 385 | "8 3", 386 | "0 3 3", 387 | "0 3 1", 388 | "0 0 2" 389 | }, 390 | { 0, 0, 0, 0, 0, 0, 0, 0 } // 4(new) 3 (old) 5*10 = 50 391 | },*/ 392 | /* 393 | { 394 | { 395 | "12", 396 | "9 3 7 1 8 12 12 10 20 15 18 5" 397 | }, 398 | { 0, 0, 0, 0, 0, 0, 0, 0 } // 4(new) 3 (old) 6*10 = 50 399 | }, 400 | 401 | { 402 | { 403 | "5", 404 | "1 2 3 4 5" 405 | }, 406 | { 0, 0, 0, 0, 0, 0, 0, 0 } // 4(new) 3 (old) 407 | }*/ 408 | }; 409 | 410 | class Cls1 { 411 | 412 | // HNType n; 413 | // MType m; 414 | // deque > p1; 415 | // XType x; 416 | // string S; 417 | // LenType ai; 418 | // TType type; 419 | // HVType v; 420 | // VType v; 421 | // PType P; 422 | // DType D; 423 | // KType K; 424 | // Heap> h1; 425 | // multiset se1; 426 | // deque p1; 427 | 428 | public: 429 | 430 | Cls1() { 431 | // LOGS = OFF; 432 | } 433 | 434 | 435 | vector testFunction(istream & cin) { 436 | // debug("testFunction - begin\n\n"); 437 | vector res; 438 | // -------------------- 439 | 440 | // LOGS = 0; 441 | 442 | 443 | 444 | sparse_table o1(cin); 445 | o1.doMain(cin); 446 | 447 | 448 | auto actual_result = 0; 449 | res.push_back(actual_result); 450 | 451 | return res; 452 | } 453 | 454 | }; 455 | 456 | 457 | int main() { 458 | 459 | if (!DEBUG_MODE) { 460 | 461 | Cls1 o; 462 | o.testFunction(cin); 463 | 464 | return 0; 465 | } 466 | else { 467 | 468 | for (unsigned long i = 0; i < tests.size(); i++) { 469 | // debug("----------------------- input getting ready ----------------------------- ", "\n"); 470 | 471 | auto input = tests[i].first; 472 | auto expected_output = tests[i].second; 473 | 474 | std::stringstream ss; 475 | istream &cin = ss; 476 | 477 | for (size_t i = 0; i < input.size(); i++) { 478 | // debug(input[i], "\n"); 479 | ss << input[i] << endl; 480 | } 481 | 482 | /* 483 | ifstream ifs; 484 | // ifs.open("../lr_input09_dummy.txt"); 485 | ifs.open("../lr_input09.txt"); 486 | string temp; 487 | vector a; 488 | getline(ifs, temp); ss << temp << endl; 489 | getline(ifs, temp); ss << temp << endl; 490 | */ 491 | 492 | 493 | // debug("----------------------- input ready ----------------------------- ", "\n"); 494 | 495 | Cls1 o; 496 | // auto actual_result = o.testFunction(cin, q)[0]; 497 | auto actual_result = o.testFunction(cin)[0]; 498 | 499 | // for (PTypeVal ai = 0; ai < q; ai++) { 500 | // Cls1 o; 501 | // // // debug("\tactual_result ", actual_result, " ", "expected_output ", expected_output[ai], "\n"); 502 | // 503 | // // assert(actual_result == expected_output[ai]); 504 | // } 505 | 506 | // break; 507 | 508 | } // for tests.size() 509 | 510 | return 0; 511 | } 512 | 513 | return 0; 514 | } 515 | -------------------------------------------------------------------------------- /RangeMaxQuery-using-segment-tree.cpp: -------------------------------------------------------------------------------- 1 | // 2 | // beautiful code 3 | // 4 | 5 | #include // min 6 | #include 7 | #include // assert 8 | #include 9 | #include 10 | #include // deque 11 | #include // ifstream 12 | #include // greater 13 | #include // setw, setfill 14 | #include 15 | #include // numeric_limits 16 | #include // map, multimap 17 | #include 18 | #include // priority_queue (greatest on top, by default, use greater for smallest on top) 19 | #include // set 20 | #include // stringstream 21 | #include // stack 22 | #include // tuple 23 | #include 24 | #include // unordered_set 25 | #include // vector 26 | 27 | using namespace std; 28 | 29 | 30 | bool ON = 1; 31 | bool OFF = 0; 32 | 33 | #ifdef DEBUGG 34 | bool DEBUG_MODE = ON; 35 | bool LOGS = ON; 36 | #else 37 | bool DEBUG_MODE = OFF; 38 | bool LOGS = OFF; 39 | #endif 40 | 41 | template 42 | void debug(Arg&& arg, Args&&... args) { 43 | 44 | if (LOGS) { 45 | std::ostream& out = std::cout; 46 | out << std::forward(arg); 47 | using expander = int[]; 48 | ( 49 | 50 | void)expander { 51 | 0, (void(out << ' ' << std::forward(args)), 0)... 52 | }; 53 | } 54 | } 55 | 56 | template 57 | ostream & operator<<(ostream &o1, const vector &v1) { 58 | for (auto it = v1.begin(); it != v1.end(); it++) { 59 | o1 << setw(4) << *it << " "; 60 | } 61 | return o1; 62 | } 63 | 64 | template 65 | vector range(T N1, T N2) { 66 | vector numbers(N2 - N1); 67 | iota(numbers.begin(), numbers.end(), N1); 68 | return numbers; 69 | } 70 | 71 | template 72 | vector zero_till(T N) { 73 | vector numbers(N); 74 | iota(numbers.begin(), numbers.end(), 0); 75 | return numbers; 76 | } 77 | 78 | template 79 | vector one_till(T N) { 80 | vector numbers(N); 81 | iota(numbers.begin(), numbers.end(), 1); 82 | return numbers; 83 | } 84 | 85 | // ----------------------------------- 86 | // ----------------------------------- 87 | // ----------------------------------- 88 | 89 | // #define PTypeVal short // 1 to 50 90 | // 91 | //#define NTypeValue int // 1 to 10^5 92 | //#define MTypeValue int // 1 to 10^5 93 | //#define XTypeValue int // 1 to 10^9 94 | //#define VTypeValue int // 0 to 10^6 95 | //#define TypeValue unsigned long long // 0 to 10^6 96 | //#define PTypeVal unsigned long long 97 | //#define VTypeVal unsigned short // long long 98 | //#define PTypeVal long long 99 | //#define DTypeVal long long 100 | //#define TTypeVal unsigned long long 101 | //#define LTypeVal unsigned long long 102 | //#define SumOfLTypeVal unsigned long long 103 | 104 | /* 105 | struct Node 106 | { 107 | NTypeVal i; 108 | EleTypeVal d; 109 | Node *l, *r, *p; // left, right, parent 110 | }; 111 | */ 112 | 113 | // #define PTypeVal unsigned long long 114 | // #define EleTypeVal unsigned long long 115 | // #define EleTypeValBig unsigned long long 116 | // #define SizeT unsigned int 117 | 118 | #define NTypeVal unsigned int 119 | #define NTypeValBig unsigned long long 120 | #define EleTypeVal unsigned long 121 | #define EleTypeValBig unsigned long long 122 | 123 | template 124 | class seg_tree_lazy { 125 | bool is_lazy; 126 | 127 | NType N, i, j; 128 | vector v1; // input array, with N elements 129 | vector seg; // seg array, with N elements // all initially 0, it does not matter what values they have as they will be filled from v1 130 | vector lazy; // lazy seg array, with N elements // same as above 131 | 132 | public: 133 | 134 | seg_tree_lazy(istream &cin) { 135 | 136 | is_lazy = true; 137 | 138 | cin >> N; 139 | 140 | v1.resize(N); 141 | 142 | for (NType i = 0; i <= N - 1; i++) { 143 | cin >> v1[i]; 144 | } 145 | 146 | build__segment_tree_for_range_max_query_wrapper(); 147 | } 148 | 149 | void build__segment_tree_for_range_max_query_wrapper() { 150 | 151 | seg.resize(4 * N); 152 | if (is_lazy) { 153 | lazy.resize(4 * N); 154 | } 155 | 156 | // fill(seg.begin(), seg.end(), numeric_limits::min()); 157 | 158 | build__segment_tree_for_range_max_query(0, N - 1, 0); 159 | } 160 | 161 | // aaaaaaaaaaaaaaaa 162 | // aaaaaaaaaaaaaaaa 163 | // aaaaaaaaaaaaaaaa 164 | 165 | // aleft, aright & amid are indexes of array 166 | // spos is index of segtree array. NOTE: spos runs as if it is BFS 167 | void build__segment_tree_for_range_max_query(const NType &aleft, const NType &aright, const NType &spos) { 168 | 169 | // not possible 170 | if (aleft > aright) { 171 | return; 172 | } 173 | 174 | // leaf node 175 | if (aleft == aright) { 176 | seg[spos] = v1[aleft]; 177 | return; 178 | } 179 | 180 | NType amid = aleft + (aright - aleft) / 2; 181 | 182 | // build left and right seg trees 183 | build__segment_tree_for_range_max_query(aleft, amid, 2 * spos + 1); // spos * 2 + 1 is left child (1 initially) 184 | build__segment_tree_for_range_max_query(amid + 1, aright, 2 * spos + 2); // spos * 2 + 2 is right child (2 initially) 185 | 186 | // update parent in seg tree from its children 187 | seg[spos] = max(seg[2 * spos + 1], seg[2 * spos + 2]); 188 | } 189 | 190 | void range_update__wrapper(const NType &uleft, const NType &uright, const EleType &ele) { 191 | range_update(uleft, uright, ele, 0, N - 1, 0); 192 | } 193 | 194 | void range_update( 195 | const NType &uleft, const NType &uright, const EleType &ele, 196 | const NType &sleft, const NType &sright, const NType &spos) { 197 | 198 | // not possible 199 | if (sleft > sright) { 200 | return; 201 | } 202 | 203 | // propogate any pending updates, from previous update 204 | // to current, move accumulate from lazy to seg 205 | // to children, from lazy, further down 206 | if (lazy[spos]) { 207 | seg[spos] += lazy[spos]; 208 | if (sleft != sright) { 209 | lazy[2 * spos + 1] += lazy[spos]; 210 | lazy[2 * spos + 2] += lazy[spos]; 211 | } 212 | lazy[spos] = 0; 213 | } 214 | 215 | // seg has no overlap 216 | if (sright < uleft || // current seg position is outside left of queried range 217 | uright < sleft // current seg position is outside right of queried range 218 | ) { 219 | return; 220 | } 221 | 222 | // seg has full overlap 223 | // current seg position (range in array) is inside queried range, so return that aggregate 224 | if (uleft <= sleft && sright <= uright) { 225 | seg[spos] += ele; 226 | if (sleft != sright) { 227 | lazy[2 * spos + 1] += ele; 228 | lazy[2 * spos + 2] += ele; 229 | } 230 | return; 231 | } 232 | 233 | // seg has partial overlap 234 | NType smid = sleft + (sright - sleft) / 2; 235 | range_update(uleft, uright, ele, sleft, smid, 2 * spos + 1); 236 | range_update(uleft, uright, ele, smid + 1, sright, 2 * spos + 2); 237 | 238 | seg[spos] = max( 239 | seg[2 * spos + 1], 240 | seg[2 * spos + 2] 241 | ); 242 | } 243 | 244 | EleType range_max_query( 245 | const NType &qleft, const NType &qright, // query low high 246 | const NType &sleft, const NType &sright, // seg array low high 247 | const NType &spos // seg array position 248 | ) { 249 | 250 | // not possible 251 | if (sright < sleft) { 252 | return numeric_limits::min(); 253 | } 254 | 255 | if (is_lazy) { /////////////////// LAZY REQUIRED 256 | 257 | // propogate any pending updates 258 | if (lazy[spos]) { 259 | seg[spos] += lazy[spos]; 260 | if (sleft != sright) { 261 | lazy[2 * spos + 1] += lazy[spos]; 262 | lazy[2 * spos + 2] += lazy[spos]; 263 | } 264 | lazy[spos] = 0; 265 | } 266 | } 267 | 268 | // seg has no overlap 269 | if (sright < qleft || // current seg position is outside left of queried range 270 | qright < sleft // current seg position is outside right of queried range 271 | ) { 272 | return numeric_limits::min(); 273 | } 274 | 275 | // seg has full overlap 276 | // current seg position (range in array) is inside queried range, so return that aggregate 277 | if (qleft <= sleft && sright <= qright) { 278 | return seg[spos]; 279 | } 280 | 281 | // seg has partial overlap, so get max of both 282 | NType smid = (sleft + sright) / 2; 283 | 284 | return max( 285 | range_max_query(qleft, qright, sleft, smid, 2 * spos + 1), // spos * 2 + 1 is left child (1 initially) 286 | range_max_query(qleft, qright, smid + 1, sright, 2 * spos + 2) // spos * 2 + 2 is right child (2 initially) 287 | ); 288 | 289 | } 290 | 291 | void doMain(istream & cin) { 292 | 293 | // range_update__wrapper(1, 2, 3); 294 | // range_update__wrapper(i, j, 3); 295 | 296 | // range_max_query__all(); 297 | 298 | for (NType qleft = 0; qleft <= N - 1; qleft++) { 299 | for (NType qright = qleft + 1; qright <= N - 1; qright++) { 300 | 301 | EleType max = range_max_query(qleft, qright, 0, N - 1, 0); 302 | cout << "[" << qleft << "," << qright << "] = " << max << endl; 303 | } 304 | } 305 | 306 | cout << seg[0] << endl; 307 | } 308 | }; 309 | 310 | // testsss 311 | // testsss 312 | // testsss 313 | // testsss 314 | 315 | #define ReturnCountTypeValue char 316 | vector < pair < vector, vector>> tests = { 317 | /* { 318 | { 319 | "5", 320 | "5 10 40 30 28" 321 | }, 322 | { 0, 0, 0, 0, 0, 0, 0, 0 } // 4(new) 3 (old) 323 | }, */ 324 | /* 325 | */ 326 | /* { 327 | { 328 | "4 3", 329 | "0 3 3", 330 | "0 3 1", 331 | "0 0 2" 332 | }, 333 | { 0, 0, 0, 0, 0, 0, 0, 0 } // 4(new) 3 (old) 5*10 = 50 334 | }, 335 | { 336 | { 337 | "8 3", 338 | "0 3 3", 339 | "0 3 1", 340 | "0 0 2" 341 | }, 342 | { 0, 0, 0, 0, 0, 0, 0, 0 } // 4(new) 3 (old) 5*10 = 50 343 | },*/ 344 | { 345 | { 346 | "5", 347 | "1 1 2 4 2" 348 | }, 349 | { 0, 0, 0, 0, 0, 0, 0, 0 } // 4(new) 3 (old) 5*10 = 50 350 | }, 351 | /* 352 | { 353 | { 354 | "12", 355 | "9 3 7 1 8 12 12 10 20 15 18 5" 356 | }, 357 | { 0, 0, 0, 0, 0, 0, 0, 0 } // 4(new) 3 (old) 6*10 = 50 358 | }, 359 | 360 | { 361 | { 362 | "5", 363 | "1 2 3 4 5" 364 | }, 365 | { 0, 0, 0, 0, 0, 0, 0, 0 } // 4(new) 3 (old) 366 | }*/ 367 | }; 368 | 369 | class Cls1 { 370 | 371 | // HNType n; 372 | // MType m; 373 | // deque > p1; 374 | // XType x; 375 | // string S; 376 | // TType type; 377 | // HVType v; 378 | // VType v; 379 | // PType P; 380 | // DType D; 381 | // KType K; 382 | // Heap> h1; 383 | // multiset se1; 384 | // deque p1; 385 | 386 | public: 387 | 388 | Cls1() { 389 | // LOGS = OFF; 390 | } 391 | 392 | 393 | vector testFunction(istream & cin) { 394 | // debug("testFunction - begin\n\n"); 395 | vector res; 396 | // -------------------- 397 | 398 | // LOGS = 0; 399 | 400 | 401 | seg_tree_lazy o1(cin); 402 | o1.doMain(cin); 403 | 404 | 405 | auto actual_result = 0; 406 | res.push_back(actual_result); 407 | 408 | return res; 409 | } 410 | 411 | }; 412 | 413 | 414 | int main() { 415 | 416 | if (!DEBUG_MODE) { 417 | 418 | Cls1 o; 419 | o.testFunction(cin); 420 | 421 | return 0; 422 | } 423 | else { 424 | 425 | for (unsigned long i = 0; i < tests.size(); i++) { 426 | // debug("----------------------- input getting ready ----------------------------- ", "\n"); 427 | 428 | auto input = tests[i].first; 429 | auto expected_output = tests[i].second; 430 | 431 | std::stringstream ss; 432 | istream &cin = ss; 433 | 434 | for (size_t i = 0; i < input.size(); i++) { 435 | // debug(input[i], "\n"); 436 | ss << input[i] << endl; 437 | } 438 | 439 | /* 440 | ifstream ifs; 441 | // ifs.open("../lr_input09_dummy.txt"); 442 | ifs.open("../lr_input09.txt"); 443 | string temp; 444 | vector a; 445 | getline(ifs, temp); ss << temp << endl; 446 | getline(ifs, temp); ss << temp << endl; 447 | */ 448 | 449 | 450 | // debug("----------------------- input ready ----------------------------- ", "\n"); 451 | 452 | Cls1 o; 453 | // auto actual_result = o.testFunction(cin, q)[0]; 454 | auto actual_result = o.testFunction(cin)[0]; 455 | 456 | // for (PTypeVal k = 0; k < q; k++) { 457 | // Cls1 o; 458 | // // // debug("\tactual_result ", actual_result, " ", "expected_output ", expected_output[k], "\n"); 459 | // 460 | // // assert(actual_result == expected_output[k]); 461 | // } 462 | 463 | // break; 464 | 465 | } // for tests.size() 466 | 467 | return 0; 468 | } 469 | 470 | return 0; 471 | } 472 | -------------------------------------------------------------------------------- /basics-a-pow-n.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | class sol { 4 | 5 | x_pow_n(X, n) { 6 | // O(N) 7 | 8 | let prod = 1; 9 | while (n > 0) { 10 | prod *= X; 11 | n--; 12 | sol.a++; 13 | } 14 | return prod; 15 | } 16 | 17 | x_pow_n_rec(X, n) { 18 | // O(N) 19 | 20 | if (n === 0) { // since, X pow 0 21 | return 1; // is 1 22 | } 23 | 24 | sol.b++; 25 | return X * this.x_pow_n_rec(X, n - 1); 26 | } 27 | 28 | x_pow_n_rec_faster(X, n) { 29 | // O(logN) 30 | 31 | if (n === 0) { // since, X pow 0 32 | return 1; // is 1 33 | } else if (n % 2 === 0) { 34 | sol.c++;// even power 35 | let single = this.x_pow_n_rec_faster(X, n / 2); // get the power half 36 | return single * single; // square it 37 | } else { 38 | sol.c++;// odd power 39 | return X * this.x_pow_n_rec_faster(X, n - 1); // make it even power 40 | } 41 | } 42 | 43 | modular_exponentiation__x_pow_n_modulo_m(X, n, M) { 44 | // O(logN) 45 | 46 | // (a * b) % M = (a%M * b%M) % M 47 | // (X pow n) = (X pow n/2) * (X pow n/2), if n is even 2 pow 4 is 2pow2 * 2pow2 48 | // (X pow n) = (X) * (X pow n-1), if n is odd 2 pow 5 is 2 * 2pow4 49 | // so, 50 | // (X pow n) % M = 51 | // if n is 0, is 1 52 | // if n is even, ( (x pow N/2) % M * (x pow N/2) % M ) % M 53 | // if n is odd, ( (x) % M * (x pow N-1) % M ) % M 54 | 55 | 56 | if (n === 0) { // since, X pow 0 57 | return 1; // is 1 58 | } else if (n % 2 === 0) { 59 | sol.d++;// even power 60 | let single = this.modular_exponentiation__x_pow_n_modulo_m(X, n / 2, M); // get the power half 61 | return (single * single) % M; // square it 62 | } else { 63 | sol.d++;// odd power 64 | return (X % M * this.modular_exponentiation__x_pow_n_modulo_m(X, n - 1, M)) % M; // make it even power 65 | } 66 | } 67 | 68 | runTests() { 69 | process.env.CS_TIME_LOGS = '1'; 70 | // console.time('TIME TAKEN: test: '); 71 | // console.timeEnd('TIME TAKEN: test: '); 72 | // console.time('TIME TAKEN: test: '); 73 | // console.timeEnd('TIME TAKEN: test: '); 74 | 75 | console.time('TIME TAKEN: x_pow_n: '); 76 | console.log("x_pow_n(13, 131): " + this.x_pow_n(13, 131)); 77 | console.timeEnd('TIME TAKEN: x_pow_n: '); 78 | console.log('a=' + sol.a); 79 | console.log('\n'); 80 | 81 | console.time('TIME TAKEN: x_pow_n_rec: '); 82 | console.log("x_pow_n_rec(13, 131): " + this.x_pow_n_rec(13, 131)); 83 | console.timeEnd('TIME TAKEN: x_pow_n_rec: '); 84 | console.log('b=' + sol.b); 85 | console.log('\n'); 86 | 87 | console.time('TIME TAKEN: x_pow_n_rec: '); 88 | console.log("x_pow_n_rec_faster(13, 131): " + this.x_pow_n_rec_faster(13, 131)); 89 | console.timeEnd('TIME TAKEN: x_pow_n_rec: '); 90 | console.log('c=' + sol.c); 91 | console.log('\n'); 92 | 93 | 94 | console.time('TIME TAKEN: x_pow_n_rec: '); 95 | // console.log("modular_exponentiation__x_pow_n_modulo_m(5, 2, 7): " + this.modular_exponentiation__x_pow_n_modulo_m(5, 2, 7)); // 4 96 | // console.log("modular_exponentiation__x_pow_n_modulo_m(5, 3, 7): " + this.modular_exponentiation__x_pow_n_modulo_m(5, 3, 7)); // 6 97 | console.log("modular_exponentiation__x_pow_n_modulo_m(5, 3, 7): " + this.modular_exponentiation__x_pow_n_modulo_m(13, 131, 7)); // 6 98 | console.timeEnd('TIME TAKEN: x_pow_n_rec: '); 99 | console.log('d=' + sol.d); 100 | console.log('\n'); 101 | } 102 | 103 | } 104 | sol.a = 0; 105 | sol.b = 0; 106 | sol.c = 0; 107 | sol.d = 0; 108 | 109 | 110 | module.exports = sol; 111 | -------------------------------------------------------------------------------- /basics-fact-n.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | class sol { 4 | 5 | n_factorial(n) { 6 | // O(N) 7 | 8 | let prod = 1; 9 | while (n > 0) { 10 | prod = prod * n; 11 | n--; 12 | 13 | sol.a++; 14 | } 15 | return prod; 16 | } 17 | 18 | n_factorial_rec(n) { 19 | // O(N) 20 | 21 | if (n === 0) { // since, X pow 0 22 | return 1; // is 1 23 | } 24 | 25 | sol.b++; 26 | return n * this.n_factorial_rec(n - 1); 27 | } 28 | 29 | runTests() { 30 | process.env.CS_TIME_LOGS = '1'; 31 | // console.time('TIME TAKEN: test: '); 32 | // console.timeEnd('TIME TAKEN: test: '); 33 | // console.time('TIME TAKEN: test: '); 34 | // console.timeEnd('TIME TAKEN: test: '); 35 | 36 | console.time('TIME TAKEN: n_factorial: '); 37 | console.log("n_factorial(13): " + this.n_factorial(5)); 38 | console.timeEnd('TIME TAKEN: n_factorial: '); 39 | console.log('a=' + sol.a + '\n'); 40 | 41 | console.time('TIME TAKEN: n_factorial_rec: '); 42 | console.log("n_factorial_rec(13): " + this.n_factorial_rec(5)); 43 | console.timeEnd('TIME TAKEN: n_factorial_rec: '); 44 | console.log('b=' + sol.b + '\n'); 45 | 46 | } 47 | 48 | } 49 | sol.a = 0; 50 | sol.b = 0; 51 | sol.c = 0; 52 | sol.d = 0; 53 | 54 | 55 | module.exports = sol; 56 | -------------------------------------------------------------------------------- /basics-fibo-n.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | function Object_values(obj) { 4 | let vals = []; 5 | for (const prop in obj) { 6 | vals.push(obj[prop]); 7 | } 8 | return vals; 9 | } 10 | 11 | class sol { 12 | 13 | fibonacci_series_upto_n(n) { 14 | // O(N) 15 | 16 | let res = []; 17 | 18 | let first = 0; 19 | if (n < first) { // -1 20 | return; 21 | } 22 | res.push(first); 23 | sol.a++; 24 | 25 | let second = 1; 26 | if (n < second) { // 0 27 | return; 28 | } 29 | res.push(second); 30 | sol.a++; 31 | 32 | let third; 33 | while (1) { 34 | third = first + second; 35 | if (n < third) { 36 | break; 37 | } 38 | res.push(third); 39 | 40 | first = second; 41 | second = third; 42 | 43 | sol.a++; 44 | } 45 | 46 | console.log(res.join(', ')); 47 | } 48 | 49 | fibonacci_series_upto_n_rec(i, n, res) { 50 | // a bit less than O(2^N) 51 | 52 | sol.b++; 53 | 54 | if (i < 0) { // -1 55 | return 0; 56 | } 57 | 58 | if (i <= 1) { // 0 and 1 59 | res[i] = i; 60 | return i; 61 | } 62 | 63 | let a = this.fibonacci_series_upto_n_rec(i - 1, n, res); 64 | let b = this.fibonacci_series_upto_n_rec(i - 2, n, res); 65 | if (n < a + b) { 66 | return a + b; 67 | } 68 | 69 | res[i] = a + b; 70 | return a + b; 71 | } 72 | 73 | fibonacci_series_upto_n__with_memoization__rec(i, n, res) { 74 | // a bit less than O(2^N) 75 | // but faster due to memoization 76 | 77 | if (res[i]) { // memoization 78 | return res[i]; 79 | } 80 | 81 | sol.c++; 82 | 83 | if (i < 0) { // -1 84 | return 0; 85 | } 86 | 87 | if (i <= 1) { // 0 and 1 88 | res[i] = i; 89 | return i; 90 | } 91 | 92 | let a = this.fibonacci_series_upto_n__with_memoization__rec(i - 1, n, res); 93 | let b = this.fibonacci_series_upto_n__with_memoization__rec(i - 2, n, res); 94 | if (n < a + b) { 95 | return a + b; 96 | } 97 | 98 | res[i] = a + b; 99 | return a + b; 100 | } 101 | 102 | runTests() { 103 | process.env.CS_TIME_LOGS = '1'; 104 | // console.time('TIME TAKEN: test: '); 105 | // console.timeEnd('TIME TAKEN: test: '); 106 | // console.time('TIME TAKEN: test: '); 107 | // console.timeEnd('TIME TAKEN: test: '); 108 | 109 | console.time('TIME TAKEN: fibonacci_series_upto_n: '); 110 | console.log("fibonacci_series_upto_n(13): "); 111 | this.fibonacci_series_upto_n(13); 112 | console.timeEnd('TIME TAKEN: fibonacci_series_upto_n: '); 113 | console.log('a=' + sol.a + '\n'); 114 | 115 | { 116 | console.time('TIME TAKEN: fibonacci_series_upto_n_rec: '); 117 | let res = {}; 118 | console.log("fibonacci_series_upto_n_rec(13): "); 119 | this.fibonacci_series_upto_n_rec(13, 13, res); 120 | console.log(Object_values(res).join(', ')); // 0, 1, 1, 2, 3, 5, 8, 13 121 | console.timeEnd('TIME TAKEN: fibonacci_series_upto_n_rec: '); 122 | console.log('b=' + sol.b + '\n'); 123 | } 124 | 125 | { 126 | console.time('TIME TAKEN: fibonacci_series_upto_n__with_memoization__rec: '); 127 | let res = {}; 128 | console.log("fibonacci_series_upto_n__with_memoization__rec(13): "); 129 | this.fibonacci_series_upto_n__with_memoization__rec(13, 13, res); 130 | console.log(Object_values(res).join(', ')); // 0, 1, 1, 2, 3, 5, 8, 13 131 | console.timeEnd('TIME TAKEN: fibonacci_series_upto_n__with_memoization__rec: '); 132 | console.log('c=' + sol.c + '\n'); 133 | } 134 | 135 | 136 | } 137 | 138 | } 139 | sol.a = 0; 140 | sol.b = 0; 141 | sol.c = 0; 142 | sol.d = 0; 143 | 144 | 145 | module.exports = sol; 146 | -------------------------------------------------------------------------------- /basics-gcd-euclidean-algorithm.cpp: -------------------------------------------------------------------------------- 1 | #include "iostream" 2 | using namespace std; 3 | 4 | int GcdEuclideanAlgorithm(int x, int y) { 5 | int remainder; 6 | 7 | // while the denominator is not 0 8 | while (y != 0) { 9 | // calc remainder (generally is smaller than denominator) 10 | // copy the denominator (generally is smaller than numerator) into numerator 11 | // copy the remainder (generally is smaller than denominator) into denominator 12 | remainder = x % y; 13 | x = y; 14 | y = remainder; 15 | } 16 | 17 | // what if (numerator is smaller than denominator)?, they get swapped, since remainder becomes numerator 18 | 19 | return x; 20 | } 21 | 22 | void CalcGcd() { 23 | cout << GcdEuclideanAlgorithm(12, 18) << endl; // Output: 6 24 | cout << GcdEuclideanAlgorithm(18, 12) << endl; // Output: 6 25 | cout << GcdEuclideanAlgorithm(14, -4) << endl; // Output: 2 26 | cout << GcdEuclideanAlgorithm(-4, 14) << endl; // Output: 2 27 | } 28 | 29 | int main () { 30 | CalcGcd(); 31 | return 0; 32 | } 33 | -------------------------------------------------------------------------------- /basics-merge-sort-top-down-recursive.cpp: -------------------------------------------------------------------------------- 1 | #include "iostream" // cout 2 | #include "iomanip" // setw 3 | using namespace std; 4 | 5 | void CopyTargetToSource(int source_array[], int ibegin, int iend, int target_array[]) { 6 | for (int i = ibegin; i <= iend; i++) { 7 | source_array[i] = target_array[i]; 8 | } 9 | } 10 | void MergeSortMerge(int source_array[], int ibegin, int imid, int iend, int target_array[]) { 11 | 12 | // start from the ibegin, not 0 13 | int k = ibegin; 14 | 15 | // copy whichever is smaller into target, and move in source sub-arrays 16 | int i = ibegin, j = imid; 17 | while (i < imid && j <= iend) { 18 | if (source_array[i] <= source_array[j]) { 19 | target_array[k++] = source_array[i++]; 20 | } 21 | else { 22 | target_array[k++] = source_array[j++]; 23 | } 24 | } 25 | 26 | // copy any remaining in source sub-array1 to target 27 | while (i < imid) { 28 | target_array[k++] = source_array[i++]; 29 | } 30 | 31 | // copy any remaining in source sub-array2 to target 32 | while (j <= iend) { 33 | target_array[k++] = source_array[j++]; 34 | } 35 | } 36 | void MergeSortTopDownSplit(int source_array[], int ibegin, int iend, int target_array[]) { 37 | // ibegin & iend are both valid indexs in array 38 | 39 | // run size >=2 is good to sort, else it is 1 element array so it is sorted 40 | if (ibegin + 1 <= iend) { // atleast 2 elements 41 | 42 | // int imid = (ibegin + iend) / 2; 43 | int imid = ibegin + (iend - ibegin) / 2; 44 | 45 | // split - recursive 46 | MergeSortTopDownSplit(source_array, ibegin, imid, target_array); 47 | MergeSortTopDownSplit(source_array, imid + 1, iend, target_array); 48 | 49 | // merge into target 50 | MergeSortMerge(source_array, ibegin, imid + 1, iend, target_array); 51 | 52 | // copy target to source 53 | CopyTargetToSource(source_array, ibegin, iend, target_array); 54 | } 55 | } 56 | 57 | void MergeSortTopDownRecursive() { 58 | const int N = 11; int source_array[N] = { 9, 7, 5, 11, 12, 2, 14, 3, 10, 4, 0 }; int target_array[N]; 59 | // 60 | // const int N = 4; int source_array[N] = { 5,7,9,11 }, target_array[N]; 61 | // const int N = 4; int source_array[N] = { 11,9,7,5 }, target_array[N]; 62 | // const int N = 4; int source_array[N] = { 5,5,5,5 }, target_array[N]; 63 | // 64 | // const int N = 3; int source_array[N] = { 5,6,7}, target_array[N]; 65 | // const int N = 3; int source_array[N] = { 7,6,5 }, target_array[N]; 66 | // const int N = 3; int source_array[N] = { 5,5,5 }, target_array[N]; 67 | // 68 | // const int N = 2; int source_array[N] = { 5,6 }, target_array[N]; 69 | // const int N = 2; int source_array[N] = { 6,5 }, target_array[N]; 70 | // const int N = 2; int source_array[N] = { 5,5 }, target_array[N]; 71 | 72 | // const int N = 1; int source_array[N] = { 5 }, target_array[N]; 73 | // const int N = 1; int source_array[N] = { -1 }, target_array[N]; 74 | // const int N = 1; int source_array[N] = { 0 }, target_array[N]; 75 | 76 | if (N == 1) { 77 | target_array[0] = source_array[0]; 78 | } 79 | else { 80 | /* 81 | first split into small sizes 82 | then, merge*/ 83 | MergeSortTopDownSplit(source_array, 0, N - 1, target_array); 84 | } 85 | 86 | // print sorted array 87 | for (int t = 0; t <= N - 1; t++) { 88 | cout << setw(2) << target_array[t] << " "; 89 | } 90 | cout << endl; 91 | } 92 | 93 | int main() { 94 | MergeSortTopDownRecursive(); 95 | return 0; 96 | } 97 | -------------------------------------------------------------------------------- /basics-performance-timers.js: -------------------------------------------------------------------------------- 1 | // for aws, azure, nodejs - performance timers 2 | // time & timeEnd 3 | 4 | let startTimeArray = undefined; 5 | let endTimeArray = undefined; 6 | let strMessage = undefined; 7 | 8 | // ========= 9 | // If you are working on micrsoft azure functions 10 | // then replace all 11 | // context 12 | // to 13 | // context 14 | // ========= 15 | 16 | module.exports = { 17 | time: time, 18 | timeEnd: timeEnd 19 | }; 20 | 21 | function time(strMessage1, context) { 22 | 23 | if (!context) { 24 | context = console; 25 | } 26 | 27 | if (process.env.CS_TIME_LOGS !== '1') { 28 | return; 29 | } 30 | 31 | if (startTimeArray !== undefined) { 32 | context.log.error('Error: timeEnd() was not called, resetting'); 33 | 34 | startTimeArray = undefined; // clear previous timer 35 | } 36 | 37 | startTimeArray = process.hrtime(); // from current time // start new timer 38 | strMessage = strMessage1; 39 | } 40 | 41 | function timeEnd(strMessage1, context) { 42 | if (process.env.CS_TIME_LOGS !== '1') { 43 | return; 44 | } 45 | 46 | if (!context) { 47 | context = console; 48 | } 49 | 50 | if (startTimeArray === undefined) { 51 | context.log.error('Error: time() was not called, resetting'); 52 | 53 | startTimeArray = undefined; // clear previous timer 54 | endTimeArray = undefined; // clear previous timer 55 | return; 56 | } 57 | 58 | if (strMessage !== strMessage1) { 59 | context.log.error('Error: time() & timeEnd() messages don\'t match, resetting'); 60 | 61 | startTimeArray = undefined; // clear previous timer 62 | endTimeArray = undefined; // clear previous timer 63 | return; 64 | } 65 | 66 | endTimeArray = process.hrtime(startTimeArray); // from start time 67 | // [seconds, nanoseconds] 68 | 69 | // context.log(strMessage1 + " " + (endTimeArray[0] + (endTimeArray[1] / 1e9)).toFixed(3) + ' seconds'); 70 | context.log(strMessage1 + " " + (endTimeArray[0] * 1e6 + (endTimeArray[1] / 1e3)).toFixed(3) + ' microseconds'); 71 | // context.log(strMessage1 + " " + (endTimeArray[0] * 1e9 + (endTimeArray[1])) + ' nanoseconds'); 72 | 73 | startTimeArray = undefined; // clear previous timer 74 | endTimeArray = undefined; // clear previous timer 75 | } 76 | 77 | /* 78 | function doMain() { 79 | 80 | context.log('======================='); 81 | context.log('testing positive cases'); 82 | context.log('======================='); 83 | 84 | // case 1: 1 second 85 | time(); 86 | for (let i = 0; i < 1e9; i++) { 87 | } 88 | timeEnd(); 89 | 90 | // case 2: 8 second 91 | time(); 92 | for (let i = 0; i < 3 * 1e9; i++) { 93 | } 94 | timeEnd(); 95 | 96 | 97 | context.log('======================='); 98 | context.log('testing negative cases'); 99 | context.log('======================='); 100 | 101 | // case 3: error scenarios 102 | timeEnd(); 103 | time(); 104 | time(); 105 | context.log('======================='); 106 | } 107 | 108 | doMain(); 109 | */ 110 | -------------------------------------------------------------------------------- /basics-quicksort-lomuto.cpp: -------------------------------------------------------------------------------- 1 | #include "iostream" // cout 2 | #include "iomanip" // setw 3 | using namespace std; 4 | 5 | int DoPartitionGetIndexOfPivotEleLomuto(int array[], int ibegin, int iend) { 6 | 7 | // Goal: Find ipivot, return it 8 | // 9 | // ibegin ipivot iend 10 | // lesser greater 11 | // 12 | // SubGoal I: all eles before ipivot index should be lesser or equal than ele at ipivot 13 | // SubGoal II: all eles after ipivot index should be greater than ele at ipivot 14 | 15 | // Initially, let the pivot_ele be last element 16 | int pivot_ele = array[iend]; 17 | 18 | // ipivot points to first element 19 | // Finally will take the pivot_ele element's index 20 | int ipivot = ibegin; 21 | 22 | // for all elements expcept last ele 23 | for (int i = ibegin; i < iend; i++) { 24 | 25 | // if ele at i is less than pivot_ele (last ele) 26 | // Goal: Place the element before ipivot 27 | // swap ipivot(starts from begin) element with i, and move ipivot ahead 28 | // this way we ensure elements before ipivot are lesser or equal (I: above) 29 | if (array[i] <= array[iend]) { 30 | 31 | // swap i with ipivot // no effect 1st time 32 | int temp = array[ipivot]; 33 | array[ipivot] = array[i]; 34 | array[i] = temp; 35 | 36 | ipivot++; 37 | } 38 | } 39 | 40 | // Now ipivot is somewhere in the middle 41 | // i went till iend-1 42 | // And, elements before ipivot are lesser or equal 43 | // => elements at & after ipivot are greater 44 | // 45 | // since i didnot touch last element at iend 46 | // we did not compare ipivot to iend 47 | // => ele at ipivot is greater than pivot_ele at iend 48 | // so swap ipivot & iend 49 | int temp = array[ipivot]; 50 | array[ipivot] = array[iend]; 51 | array[iend] = temp; 52 | 53 | // Now ipivot has pivot_ele value 54 | // => ipivot has made required partition, eles before it are <=, eles after it are > 55 | // so return ipivot (since both SubGoal I && SubGoal II are satisfied) 56 | 57 | return ipivot; 58 | } 59 | void QuickSortLomuto(int array[], int ibegin, int iend) { 60 | if (ibegin <= iend) { // initially 0 to N-1 61 | int ipivot = DoPartitionGetIndexOfPivotEleLomuto(array, ibegin, iend); // get pivot position 62 | QuickSortLomuto(array, ibegin, ipivot - 1); // call self, for before pivot position subarray 63 | QuickSortLomuto(array, ipivot + 1, iend); // call self, for after pivot position subarray 64 | } 65 | } 66 | void QuickSortLomuto() { 67 | int array[] = { 9, 7, 5, 11, 12, 2, 14, 3, 10, 4, 0 }; 68 | int N = sizeof(array) / sizeof(array[0]); // count = size of all eles/ size of single ele 69 | 70 | int ibegin = 0; 71 | int iend = N - 1; 72 | 73 | QuickSortLomuto(array, ibegin, iend); // send all elements 74 | 75 | // print sorted array 76 | for (int t = 0; t <= N - 1; t++) { 77 | cout << setw(2) << array[t] << " "; 78 | } 79 | cout << endl; 80 | } 81 | 82 | int main() { 83 | QuickSortLomuto(); 84 | return 0; 85 | } 86 | -------------------------------------------------------------------------------- /cartesian-tree.cpp: -------------------------------------------------------------------------------- 1 | // 2 | // beautiful code 3 | // 4 | 5 | #include "stdafx.h" 6 | 7 | #include // min 8 | #include 9 | #include // assert 10 | #include 11 | #include 12 | #include // deque 13 | #include // ifstream 14 | #include // greater 15 | #include // setw, setfill 16 | #include 17 | #include // numeric_limits 18 | #include // map, multimap 19 | #include 20 | #include // priority_queue (greatest on top, by default, use greater for smallest on top) 21 | #include // set 22 | #include // stringstream 23 | #include // stack 24 | #include // tuple 25 | #include 26 | #include // unordered_set 27 | #include // vector 28 | 29 | using namespace std; 30 | 31 | 32 | bool ON = 1; 33 | bool OFF = 0; 34 | 35 | #ifdef DEBUGG 36 | bool DEBUG_MODE = ON; 37 | bool LOGS = ON; 38 | #else 39 | bool DEBUG_MODE = OFF; 40 | bool LOGS = OFF; 41 | #endif 42 | 43 | template 44 | void debug(Arg&& arg, Args&&... args) { 45 | 46 | if (LOGS) { 47 | std::ostream& out = std::cout; 48 | out << std::forward(arg); 49 | using expander = int[]; 50 | ( 51 | 52 | void)expander { 53 | 0, (void(out << ' ' << std::forward(args)), 0)... 54 | }; 55 | } 56 | } 57 | 58 | template 59 | ostream & operator<<(ostream &o1, const vector &v1) { 60 | for (auto it = v1.begin(); it != v1.end(); it++) { 61 | o1 << setw(4) << *it << " "; 62 | } 63 | return o1; 64 | } 65 | 66 | template 67 | vector range(T N1, T N2) { 68 | vector numbers(N2 - N1); 69 | iota(numbers.begin(), numbers.end(), N1); 70 | return numbers; 71 | } 72 | 73 | template 74 | vector zero_till(T N) { 75 | vector numbers(N); 76 | iota(numbers.begin(), numbers.end(), 0); 77 | return numbers; 78 | } 79 | 80 | template 81 | vector one_till(T N) { 82 | vector numbers(N); 83 | iota(numbers.begin(), numbers.end(), 1); 84 | return numbers; 85 | } 86 | 87 | // ----------------------------------- 88 | // ----------------------------------- 89 | // ----------------------------------- 90 | 91 | // #define PTypeVal short // 1 to 50 92 | // 93 | //#define NTypeValue int // 1 to 10^5 94 | //#define MTypeValue int // 1 to 10^5 95 | //#define XTypeValue int // 1 to 10^9 96 | //#define VTypeValue int // 0 to 10^6 97 | //#define TypeValue unsigned long long // 0 to 10^6 98 | //#define PTypeVal unsigned long long 99 | //#define VTypeVal unsigned short // long long 100 | //#define PTypeVal long long 101 | //#define DTypeVal long long 102 | //#define TTypeVal unsigned long long 103 | //#define LTypeVal unsigned long long 104 | //#define SumOfLTypeVal unsigned long long 105 | 106 | // #define PTypeVal unsigned long long 107 | #define NTypeVal long 108 | #define EleTypeVal long long 109 | // #define SizeT unsigned int 110 | // #define VeryLargeTypeVal unsigned long long 111 | // ----------------------------------- 112 | 113 | 114 | struct Node 115 | { 116 | NTypeVal i; 117 | EleTypeVal d; 118 | Node *l, *r, *p; // left, right, parent 119 | }; 120 | 121 | 122 | template 123 | class cartesian_tree { 124 | 125 | // https://apps.topcoder.com/forums/?module=RevisionHistory&messageID=1352447 126 | // https://apps.topcoder.com/forums/?module=Thread&threadID=715842&start=0&mc=8 127 | // http://zobayer.blogspot.in/2013/11/various-usage-of-bit.html 128 | // https://www.hackerearth.com/notes/binary-indexed-tree-made-easy-2/ 129 | // http://www.geeksforgeeks.org/binary-indexed-tree-or-fenwick-tree-2/ 130 | // https://www.topcoder.com/community/data-science/data-science-tutorials/binary-indexed-trees/ 131 | 132 | NType N; 133 | vector v1; // input array, with N+1 elements - element at index 0, is not used 134 | vector BITree; // BITree array, with N+1 elements - element at index 0, is not used 135 | 136 | struct Node* getNewNode(EleType &data1, NType &index1) { 137 | struct Node* temp = new Node(); 138 | 139 | temp->i = index1; 140 | temp->d = data1; 141 | 142 | temp->l = NULL; 143 | temp->r = NULL; 144 | temp->p = NULL; 145 | 146 | return temp; 147 | } 148 | 149 | struct Node *root = NULL, *right_most = NULL; 150 | 151 | public: 152 | 153 | cartesian_tree(istream &cin) { 154 | cin >> N; 155 | 156 | ///////// cout << one_till(N) << endl; 157 | // cout << v1 << endl; 158 | 159 | EleType Ai; 160 | for (NType i = 1; i <= N; i++) { 161 | cin >> Ai; 162 | 163 | ///////// cout << setw(4) << Ai << " "; 164 | 165 | auto new1 = getNewNode(Ai, i); 166 | if (root == NULL) { 167 | root = new1; 168 | right_most = new1; 169 | } 170 | else { 171 | while (right_most->r) { 172 | right_most = right_most->r; 173 | } 174 | 175 | 176 | struct Node* temp = right_most; 177 | while (temp && 178 | (temp->d >= new1->d)) { 179 | temp = temp->p; 180 | } 181 | 182 | if (temp) { 183 | new1->l = temp->r; 184 | temp->r = new1; 185 | 186 | 187 | new1->p = temp; 188 | if (new1->l) { 189 | new1->l->p = new1; 190 | } 191 | 192 | right_most = new1; 193 | } 194 | else { 195 | new1->l = root; 196 | root = new1; 197 | 198 | if (new1->l) { 199 | new1->l->p = new1; 200 | } 201 | 202 | right_most = root; 203 | } 204 | 205 | } 206 | } 207 | ///////// cout << endl; 208 | } 209 | 210 | void print_array_indexes() { 211 | stringstream output; 212 | output << "index: "; 213 | for (int i = 1; i <= N; i++) { output << left << setw(4) << i; } 214 | cout << output.str() << endl; 215 | } 216 | 217 | }; 218 | 219 | 220 | // testsss 221 | #define ReturnCountTypeValue char 222 | vector < pair < vector, vector>> tests = { 223 | /* { 224 | { 225 | "5", 226 | "5 10 40 30 28" 227 | }, 228 | { 0, 0, 0, 0, 0, 0, 0, 0 } // 4(new) 3 (old) 229 | }, */ 230 | { 231 | { 232 | "12", 233 | "9 3 7 1 8 12 12 10 20 15 18 5" 234 | }, 235 | { 0, 0, 0, 0, 0, 0, 0, 0 } // 4(new) 3 (old) 236 | }, 237 | /* 238 | { 239 | { 240 | "5", 241 | "1 2 3 4 5" 242 | }, 243 | { 0, 0, 0, 0, 0, 0, 0, 0 } // 4(new) 3 (old) 244 | }*/ 245 | }; 246 | 247 | template 248 | class ClsMain1 { 249 | NType N; 250 | // deque p1; 251 | public: 252 | 253 | ClsMain1() { 254 | } 255 | 256 | void doMain(istream &cin) { 257 | cartesian_tree o1(cin); 258 | o1.doMain(); 259 | } 260 | }; 261 | 262 | // template 263 | 264 | template 265 | class Cls1 { 266 | 267 | // HNType n; 268 | // MType m; 269 | // deque > p1; 270 | // XType x; 271 | // string S; 272 | // LenType k; 273 | // TType type; 274 | // HVType v; 275 | // VType v; 276 | // PType P; 277 | // DType D; 278 | // KType K; 279 | // Heap> h1; 280 | // multiset se1; 281 | // deque p1; 282 | 283 | public: 284 | 285 | Cls1() { 286 | // LOGS = OFF; 287 | } 288 | 289 | 290 | vector testFunction(istream & cin) { 291 | // debug("testFunction - begin\n\n"); 292 | vector res; 293 | // -------------------- 294 | 295 | // LOGS = 0; 296 | 297 | 298 | ClsMain1 p1; 299 | 300 | 301 | auto actual_result = 0; 302 | res.push_back(actual_result); 303 | 304 | return res; 305 | } 306 | 307 | }; 308 | 309 | 310 | int main() { 311 | 312 | if (DEBUG_MODE) { 313 | 314 | for (unsigned long i = 0; i < tests.size(); i++) { 315 | // debug("----------------------- input getting ready ----------------------------- ", "\n"); 316 | auto input = tests[i].first; 317 | auto expected_output = tests[i].second; 318 | 319 | std::stringstream ss; 320 | istream &cin = ss; 321 | 322 | for (size_t i = 0; i < input.size(); i++) { 323 | // debug(input[i], "\n"); 324 | ss << input[i] << endl; 325 | } 326 | 327 | 328 | 329 | // debug("----------------------- input ready ----------------------------- ", "\n"); 330 | 331 | Cls1 o; 332 | // Cls1 o; 333 | // Cls1 o; 334 | // auto actual_result = o.testFunction(cin, q)[0]; 335 | auto actual_result = o.testFunction(cin)[0]; 336 | 337 | // for (PTypeVal k = 0; k < q; k++) { 338 | // Cls1 o; 339 | // // // debug("\tactual_result ", actual_result, " ", "expected_output ", expected_output[k], "\n"); 340 | // 341 | // // assert(actual_result == expected_output[k]); 342 | // } 343 | 344 | // break; 345 | } 346 | } 347 | else { 348 | 349 | // PTypeVal q; 350 | // cin >>q; 351 | 352 | Cls1 o; 353 | // Cls1 o; 354 | // Cls1 o; 355 | o.testFunction(cin); 356 | 357 | } 358 | 359 | return 0; 360 | } 361 | -------------------------------------------------------------------------------- /convex-hull-jarvis.js: -------------------------------------------------------------------------------- 1 | 2 | class Point { 3 | 4 | constructor(x, y) { 5 | this.x = x; 6 | this.y = y; 7 | console.log(this); 8 | } 9 | 10 | approxDistanceTo(B) { 11 | // actually it is squareRoot, but when we skip for all distances we dont need to do since we company squares instead of sqrt 12 | let dX = Math.abs(B.x - this.x); 13 | let dY = Math.abs(B.y - this.y); 14 | return dX + dY; 15 | } 16 | 17 | closerToB_by(B, C) { 18 | let dB = this.approxDistanceTo(B); // A B approxDistanceTo 19 | let dC = this.approxDistanceTo(C); // A C approxDistanceTo 20 | return (dC - dB); // difference 21 | 22 | // (>0) B is closer than C, to A 23 | // (<0) B is farther than C, to A 24 | // (=0) B & C are equi-distance to A 25 | } 26 | 27 | static C_is_leftOfAB(A, B, C) { // crossProduct will do 28 | let dABx = (A.x - B.x); 29 | let dABy = (A.y - B.y); 30 | 31 | let dACx = (A.x - C.x); 32 | let dACy = (A.y - C.y); 33 | // 34 | // let minOfAll = 35 | // Math.min( 36 | // Math.min(dABx, dACy), 37 | // Math.min(dACx, dABy) 38 | // ); 39 | // 40 | // console.log('\t\t\t\t\t', dABx, dACy, dACx, dABy); 41 | // 42 | // if (minOfAll > 1) { 43 | // console.log('YES_--------------------'); 44 | // minOfAll = minOfAll - 1; 45 | // console.log(minOfAll); 46 | // } else if (minOfAll < 1) { 47 | // console.log('YES_--------------------'); 48 | // minOfAll = minOfAll - 1; 49 | // console.log(minOfAll); 50 | // } else { 51 | // minOfAll = 0; 52 | // } 53 | // 54 | // 55 | // dABx = dABx - minOfAll; 56 | // dACy = dACy - minOfAll; 57 | // dACx = dACx - minOfAll; 58 | // dABy = dABy - minOfAll; 59 | 60 | // let sign1 = 1; 61 | // sign1 = (dACy < 0) ? -1 * sign1 : sign1; 62 | // sign1 = (dABx < 0) ? -1 * sign1 : sign1; 63 | // 64 | // let sign2 = 1; 65 | // sign2 = (dACx < 0) ? -1 * sign2 : sign2; 66 | // sign2 = (dABy < 0) ? -1 * sign2 : sign2; 67 | // 68 | // return sign1 * (dABx + dACy) - sign2 * (dACx + dABy); 69 | return dABx * dACy - dACx * dABy; 70 | 71 | // (<0) C is left of AB 72 | // (>0) C is right of AB 73 | // (=0) C is on AB, collinear 74 | } 75 | 76 | static convexHull__jarvisMarch(parr) { 77 | 78 | if (!parr[0]) { 79 | throw new Error("what??"); 80 | } 81 | 82 | let slmi = 0; 83 | 84 | console.log('parr[slmi]'); 85 | console.log(parr[slmi]); 86 | for (let i = 0; i < parr.length; i++) { 87 | // console.log('\t', parr[slmi].x, parr[i].x); 88 | if (parr[slmi].x > parr[i].x) { 89 | slmi = i; 90 | } 91 | } 92 | console.log('parr[slmi]'); 93 | console.log(parr[slmi]); 94 | 95 | let start_leftmost = parr[slmi]; // copy 96 | console.log('start_leftmost'); 97 | console.log(start_leftmost); 98 | 99 | console.log('parr'); 100 | console.log(parr); 101 | delete parr[slmi]; 102 | console.log('parr'); 103 | console.log(parr); 104 | 105 | 106 | } 107 | 108 | } 109 | 110 | //let A = new Point(-6, -2); 111 | //let B = new Point(4, 6); 112 | //let C = new Point(8, -4); 113 | // 114 | //let dB = A.approxDistanceTo(B); 115 | //let dC = A.approxDistanceTo(C); 116 | //console.log("dB: " + dB); 117 | //console.log("dC: " + dC); 118 | // 119 | //console.log("closerToB_by?" + A.closerToB_by(B, C)); 120 | ////console.log("closerToB_by?" + A.closerToB_by(C, B)); 121 | // 122 | //console.log("---------------"); 123 | //console.log("C_is_leftOfAB?" + Point.C_is_leftOfAB(A, B, C)); 124 | //console.log("C_is_leftOfAB?" + Point.C_is_leftOfAB(A, C, B)); 125 | //console.log("C_is_leftOfAB?" + Point.C_is_leftOfAB(B, C, A)); 126 | // 127 | //console.log("---------------"); 128 | 129 | let parr = [ 130 | new Point(2, 0), 131 | new Point(2, 2), 132 | new Point(0, 2), 133 | new Point(-2, 2), 134 | new Point(0, 0), 135 | new Point(-2, 0), 136 | new Point(-2, -2), 137 | new Point(0, -2), 138 | new Point(2, -2) 139 | ]; 140 | 141 | Point.convexHull__jarvisMarch(parr); 142 | -------------------------------------------------------------------------------- /gccp.bat: -------------------------------------------------------------------------------- 1 | @echo off 2 | echo compiling C++ using -ansi -pedantic-errors -Wall 3 | g++ -ansi -pedantic-errors -Wall %1 %2 %3 4 | -------------------------------------------------------------------------------- /javascript-deque.js: -------------------------------------------------------------------------------- 1 | /* Deque data structure in javascript / js */ 2 | 3 | class Deque { 4 | values = []; 5 | constructor(values) { 6 | if (values) this.values = values; // no copy 7 | // if (values) this.values = [...values]; // copy 8 | } 9 | 10 | get length() { 11 | return this.size(); 12 | } 13 | size = () => this.values.length; 14 | isEmpty = () => this.size() === 0; 15 | 16 | back = () => this.values[this.size() - 1]; 17 | push_back = (x) => this.values.push(x); 18 | pop_back = () => this.values.pop(); 19 | 20 | front = () => this.values[0]; 21 | push_front = (x) => this.values.unshift(x); // to be tested 22 | pop_front = () => this.values.shift(); 23 | } 24 | 25 | function use() { 26 | let q = new Deque(); 27 | 28 | q.push_back(10); 29 | q.push_back(20); 30 | console.log(q.size()); // 2 // output 31 | console.log(q.isEmpty()); // false 32 | console.log(q.front()); // 10 33 | console.log(q.back()); // 20 34 | 35 | console.log(q.pop_front()); // 10 36 | console.log(q.size()); // 1 37 | console.log(q.isEmpty()); // false 38 | console.log(q.front()); // 20 39 | console.log(q.back()); // 20 40 | 41 | console.log(q.pop_back()); // 20 42 | console.log(q.size()); // 0 43 | console.log(q.isEmpty()); // true 44 | console.log(q.front()); // undefined 45 | console.log(q.back()); // undefined 46 | } 47 | 48 | use(); 49 | -------------------------------------------------------------------------------- /js-backtracking-knight-movement.js: -------------------------------------------------------------------------------- 1 | // Knight Tour problem 2 | 3 | // GOAL: 4 | // knight on the top-left corner (0) 5 | // should jump to 6 | // all squares 7 | // on chess board / (8x8) matrix 8 | 9 | /* 10 | 0 59 38 33 30 17 8 63 11 | 37 34 31 60 9 62 29 16 12 | 58 1 36 39 32 27 18 7 13 | 35 48 41 26 61 10 15 28 14 | 42 57 2 49 40 23 6 19 15 | 47 50 45 54 25 20 11 14 16 | 56 43 52 3 22 13 24 5 17 | 51 46 55 44 53 4 21 12 18 | */ 19 | 20 | class KnightTour { 21 | // 22 | 23 | constructor() { 24 | // 25 | 26 | this.N = 8; 27 | this.aa = Array.from({ length: this.N }, () => new Array(this.N)); 28 | 29 | // next moves/ (x, y) coordinates of Knight 30 | this.xMoves = [2, 1, -1, -2, -2, -1, 1, 2]; 31 | this.yMoves = [1, 2, 2, 1, -1, -2, -2, -1]; 32 | 33 | /* 34 | x,y 35 | 1,-2 2,1 36 | 37 | -1,-2 1,2 38 | 39 | -2,-1 -1,2 40 | -2,1 41 | */ 42 | } 43 | 44 | isSafe(x, y) { 45 | return ( 46 | x >= 0 && // 47 | x < this.N && 48 | y >= 0 && 49 | y < this.N && 50 | this.aa[x][y] == -1 51 | ); 52 | } 53 | 54 | // returns fals e, if no complete tour is possible, 55 | // return tru e, prints the tour. 56 | // multiple solutions may exist - after 1 solution found, exit 57 | solveKT() { 58 | // 59 | 60 | for (let x = 0; x < this.N; x++) { 61 | for (let y = 0; y < this.N; y++) { 62 | this.aa[x][y] = -1; 63 | } 64 | } 65 | 66 | // Knight is initially at the first block 67 | this.aa[0][0] = 0; 68 | 69 | /* 70 | 0 -1 -1 -1 -1 -1 -1 -1 71 | -1 -1 -1 -1 -1 -1 -1 -1 72 | -1 -1 -1 -1 -1 -1 -1 -1 73 | -1 -1 -1 -1 -1 -1 -1 -1 74 | -1 -1 -1 -1 -1 -1 -1 -1 75 | -1 -1 -1 -1 -1 -1 -1 -1 76 | -1 -1 -1 -1 -1 -1 -1 -1 77 | -1 -1 -1 -1 -1 -1 -1 -1 78 | */ 79 | 80 | // start from 0,0 and explore all tours 81 | if (this.solveKTUtil(0, 0, 1)) { 82 | this.printSolution(); 83 | } else { 84 | console.log("Solution does not exist"); 85 | } 86 | } 87 | 88 | solveKTUtil(x, y, movei) { 89 | if (movei == this.N * this.N) return true; 90 | 91 | // try all next moves from the current x, y 92 | for (let k = 0; k < this.N; k++) { 93 | // 94 | 95 | let next_x = x + this.xMoves[k]; 96 | let next_y = y + this.yMoves[k]; 97 | 98 | if (this.isSafe(next_x, next_y)) { 99 | // 100 | 101 | this.aa[next_x][next_y] = movei; 102 | /* 103 | // final solution will be 104 | 105 | 0 59 38 33 30 17 8 63 106 | 37 34 31 60 9 62 29 16 107 | 58 1 36 39 32 27 18 7 108 | 35 48 41 26 61 10 15 28 109 | 42 57 2 49 40 23 6 19 110 | 47 50 45 54 25 20 11 14 111 | 56 43 52 3 22 13 24 5 112 | 51 46 55 44 53 4 21 12 113 | */ 114 | 115 | if (this.solveKTUtil(next_x, next_y, movei + 1)) { 116 | // solution is complete 117 | return true; 118 | } else { 119 | // backtracking - goto prev stage 120 | this.aa[next_x][next_y] = -1; 121 | } 122 | } 123 | } 124 | 125 | return false; 126 | } 127 | 128 | printSolution() { 129 | let str = ""; 130 | for (let x = 0; x < this.N; x++) { 131 | str = ""; 132 | for (let y = 0; y < this.N; y++) str += this.aa[x][y] + " "; 133 | console.log(str); 134 | } 135 | } 136 | } 137 | 138 | let a = new KnightTour(); 139 | a.solveKT(); 140 | 141 | /* 142 | 143 | Time Complexity looks like: 144 | 145 | - 1st move 8 possibilities 146 | - From 2nd move <=7 possibilities, since we don't go back to same position. 147 | -- There are 63 moves like 2nd move. 148 | 149 | 8 * 7 * 7 * ... * 7 (*7 is for 63 times) 150 | = 8 * (7 ^ 63) 151 | = 8 * (8-1) ^(64-1) 152 | = 8 * (8-1) ^(r*c-1) 153 | = 8 ^ (r*c) approx -- r and c are # of rows & columns of matrix 154 | 155 | */ 156 | -------------------------------------------------------------------------------- /js-math-nCr.js: -------------------------------------------------------------------------------- 1 | function binomialCoefficient_nCr(n, r) { 2 | // C(n, r) 3 | let prod = 1; 4 | 5 | // since C(n, r) = C(n, n-r) 6 | if (r > n - r) r = n - r; 7 | 8 | // calc [n * (n-1) *---* (n-r+1)] / [r * (r-1) *----* 1] 9 | for (let i = 0; i < r; ++i) { 10 | prod *= n - i; 11 | prod /= i + 1; 12 | } 13 | 14 | // console.log(prod); 15 | return prod; 16 | } 17 | -------------------------------------------------------------------------------- /js-math-pascal-triangle-simplex-numbers: -------------------------------------------------------------------------------- 1 | var pascalTriangleSimplexNumbers = function (n, r) { 2 | // https://en.wikipedia.org/wiki/Pascal%27s_triangle 3 | // https://upload.wikimedia.org/wikipedia/commons/f/f9/Pascal_triangle_simplex_numbers.svg 4 | 5 | // Pascal triangle simplex numbers 6 | // C(N,1) 1 2 3 4 5 6 7 | // Triangular numbers C(N+1,2) 1 3 6 10 15 21 8 | // C(N+2,3) 1 4 10 20 35 56 9 | // Pentatope numbers C(N+3,4) 1 5 15 35 70 10 | // C(N+4,5) 1 6 25 56 11 | // C(N+5,6) 1 7 28 12 | // C(N+6,7) 1 8 13 | // C(N+7,8) 1 14 | 15 | return binomialCoefficient_nCr(n + (r - 2), r - 1); 16 | }; 17 | 18 | 19 | function binomialCoefficient_nCr(n, r) { 20 | // C(n, r) 21 | let prod = 1; 22 | 23 | // since C(n, r) = C(n, n-r) 24 | if (r > n - r) r = n - r; 25 | 26 | // calc [n * (n-1) *---* (n-r+1)] / [r * (r-1) *----* 1] 27 | for (let i = 0; i < r; ++i) { 28 | prod *= n - i; 29 | prod /= i + 1; 30 | } 31 | 32 | // console.log(prod); 33 | return prod; 34 | } 35 | -------------------------------------------------------------------------------- /js-min-heap.js: -------------------------------------------------------------------------------- 1 | // https://en.wikipedia.org/wiki/Heap_(data_structure) 2 | // https://en.wikipedia.org/wiki/Binary_heap 3 | // https://www.g ee ksforgeeks.org/binary-heap/ 4 | 5 | // https://courses.cs.washington.edu/courses/cse373/18wi/files/slides/lecture-14-ann.pdf 6 | // https://users.cs.duke.edu/~reif/courses/alglectures/skiena.lectures/lecture4.pdf 7 | 8 | // https://github.com/manoharreddyporeddy/math-advanced-data-structures-and-algorithms 9 | 10 | /* 11 | min heap1 min heap2 min heap3 MAX heap1 12 | 10 10 1 100 13 | / \ / \ / \ / \ 14 | 20 100 15 30 2 3 19 36 15 | / / \ / \ / \ / \ / \ / \ 16 | 30 40 50 100 40 17 19 36 7 17 3 25 1 17 | / \ / \ 18 | 25 100 2 7 19 | 20 | */ 21 | 22 | // A class for Min Heap 23 | class MinHeap { 24 | // Constructor: Builds a heap from a given array a[] of given size 25 | constructor(capacity) { 26 | // console.log("constructor", capacity); 27 | this.INT_MIN = -2147483648; 28 | 29 | this.size = 0; // Current number of elements in min heap 30 | this.capacity = capacity; // maximum possible size of min heap 31 | this.a = []; // new Array(capacity); // pointer to array of elements in heap 32 | 33 | // console.log("size, capacity, a - ", this.size, this.capacity, this.a); 34 | } 35 | 36 | parent(i) { 37 | return Math.trunc((i - 1) / 2); 38 | } 39 | 40 | leftChild(i) { 41 | return 2 * i + 1; 42 | } 43 | 44 | rightChild(i) { 45 | return 2 * i + 2; 46 | } 47 | 48 | // Inserts a new key 'k' 49 | insertKey(k) { 50 | if (this.size == this.capacity) { 51 | console.log("\nOverflow: Could not insertKey\n"); 52 | return; 53 | } 54 | 55 | // First insert the new key at the end 56 | this.size++; 57 | let i = this.size - 1; 58 | this.a[i] = k; 59 | 60 | // Fix the min heap property if it is violated 61 | while (i != 0 && this.a[this.parent(i)] > this.a[i]) { 62 | [this.a[i], this.a[this.parent(i)]] = [ 63 | this.a[this.parent(i)], 64 | this.a[i], 65 | ]; 66 | i = this.parent(i); 67 | } 68 | 69 | return null; 70 | } 71 | 72 | // Decreases key value of key at index i to new_val 73 | // Decreases value of key at index 'i' to new_val. It is assumed that 74 | // new_val is smaller than this.a[i]. 75 | decreaseKey(i, new_val) { 76 | this.a[i] = new_val; 77 | while (i != 0 && this.a[this.parent(i)] > this.a[i]) { 78 | [this.a[i], this.a[this.parent(i)]] = [ 79 | this.a[this.parent(i)], 80 | this.a[i], 81 | ]; 82 | i = this.parent(i); 83 | } 84 | 85 | return null; 86 | } 87 | 88 | // to extract the root which is the minimum element 89 | // Method to remove minimum element (or root) from min heap 90 | extractMin() { 91 | if (this.size <= 0) return INT_MAX; 92 | if (this.size == 1) { 93 | this.size--; 94 | return this.a[0]; 95 | } 96 | 97 | // Store the minimum value, and remove it from heap 98 | let root = this.a[0]; 99 | this.a[0] = this.a[this.size - 1]; 100 | this.size--; 101 | this.MinHeapify(0); 102 | 103 | return root; 104 | } 105 | 106 | // Returns the minimum key (key at root) from min heap 107 | getMin() { 108 | // console.log(this.a[0], ", arr =", this.a); 109 | return this.a[0]; 110 | } 111 | 112 | // Deletes a key stored at index i 113 | // This function deletes key at index i. It first reduced value to minus 114 | // infinite, then calls extractMin() 115 | deleteKeyAt(i) { 116 | this.decreaseKey(i, this.INT_MIN); 117 | this.extractMin(); 118 | return null; 119 | } 120 | 121 | // // to heapify a subtree with the root at given index 122 | // A recursive method to heapify a subtree with the root at given index 123 | // This method assumes that the subtrees are already heapified 124 | MinHeapify(i) { 125 | let l = this.leftChild(i); 126 | let r = this.rightChild(i); 127 | let smallest = i; 128 | if (l < this.size && this.a[l] < this.a[i]) smallest = l; 129 | if (r < this.size && this.a[r] < this.a[smallest]) smallest = r; 130 | if (smallest != i) { 131 | [this.a[i], this.a[smallest]] = [this.a[smallest], this.a[i]]; 132 | 133 | this.MinHeapify(smallest); 134 | } 135 | } 136 | 137 | test() { 138 | 139 | // new MinHeap().test(); 140 | 141 | let o1 = new MinHeap(11); 142 | 143 | o1.insertKey(3); 144 | console.log("insertKey 3, ", o1.a, ", ", o1.getMin()); 145 | 146 | o1.insertKey(2); 147 | console.log("insertKey 2, ", o1.a, ", ", o1.getMin()); 148 | 149 | o1.deleteKeyAt(1); 150 | console.log("deleteKeyAt 1 , ", o1.a, ", ", o1.getMin()); 151 | 152 | o1.insertKey(15); 153 | console.log("insertKey 15, ", o1.a, ", ", o1.getMin()); 154 | 155 | o1.insertKey(5); 156 | console.log("insertKey 5, ", o1.a, ", ", o1.getMin()); 157 | 158 | o1.insertKey(4); 159 | console.log("insertKey 4, ", o1.a, ", ", o1.getMin()); 160 | 161 | o1.insertKey(45); 162 | console.log("insertKey 45, ", o1.a, ", ", o1.getMin()); 163 | 164 | console.log("extractMin ", o1.extractMin(), "", o1.a, ",", o1.getMin()); 165 | 166 | o1.decreaseKey(2, 1); 167 | console.log("decreaseKey 2,1 , ", o1.a, ", ", o1.getMin()); 168 | 169 | /* 170 | // new MinHeap().test(); 171 | 172 | // operation parameters, arr, getMin 173 | insertKey 3, [ 3 ] , 3 174 | insertKey 2, [ 2, 3 ] , 2 175 | deleteKeyAt 1 , [ 2, 2 ] , 2 176 | insertKey 15, [ 2, 15 ] , 2 177 | insertKey 5, [ 2, 15, 5 ] , 2 178 | insertKey 4, [ 2, 4, 5, 15 ] , 2 179 | insertKey 45, [ 2, 4, 5, 15, 45 ] , 2 180 | extractMin 2 [ 4, 15, 5, 45, 45 ] , 4 181 | decreaseKey 2,1 , [ 1, 15, 4, 45, 45 ] , 1 182 | 183 | */ 184 | } 185 | } 186 | 187 | // new MinHeap().test(); 188 | -------------------------------------------------------------------------------- /js-util-binary-search.js: -------------------------------------------------------------------------------- 1 | 2 | let binary_search = (a, left = 0, right = a.length - 1, trgt = -1) => { 3 | // console.log(a, left, right, trgt); 4 | 5 | while (left <= right) { 6 | let mid = left + Math.trunc((right - left) / 2); 7 | // console.log("mid ", mid); 8 | if (trgt == a[mid]) return mid; 9 | else if (trgt > a[mid]) left = mid + 1; 10 | else right = mid - 1; 11 | } 12 | 13 | return -1; 14 | }; 15 | -------------------------------------------------------------------------------- /js-util-bits.js: -------------------------------------------------------------------------------- 1 | class BitManip { 2 | constructor(n) { 3 | this.n = n; 4 | } 5 | 6 | getNum() { 7 | return this.n; 8 | } 9 | 10 | getBitCount() { 11 | let sum = 0; 12 | while (this.n) { 13 | sum += this.n & 1; 14 | this.n = this.n >> 1; 15 | } 16 | return sum; 17 | } 18 | 19 | getKthIndexBit(k) { 20 | if (k < 0) { 21 | console.log("k -ve invalid - getKthIndexBit"); 22 | return this.n; 23 | } 24 | return (this.n >> k) & 1; 25 | // return this.n & (1 << k); // ---- bitwise AND (&) 26 | } 27 | 28 | setKthIndexBit(k) { 29 | if (k < 0) { 30 | console.log("k -ve invalid - setKthIndexBit"); 31 | return this.n; 32 | } 33 | this.n = this.n | (1 << k); // ---- bitwise OR (|) 34 | return this.n; 35 | } 36 | 37 | unsetKthIndexBit(k) { 38 | if (k < 0) { 39 | console.log("k -ve invalid - unsetKthIndexBit"); 40 | return this.n; 41 | } 42 | 43 | // & this.n, with a number with all set bits except the k'th bit 44 | 45 | this.n = this.n & ~(1 << k); // ---- bitwise AND (&) 46 | return this.n; 47 | } 48 | 49 | // ---------- 50 | 51 | /* 52 | 53 | toggleKthBit(k) { 54 | if (k < 1) return this.n; 55 | 56 | // ^ this.n, with a number with all set bits except the k'th bit 57 | return this.n ^ (1 << k); // ---------------- bitwise AND (&) 58 | } 59 | 60 | */ 61 | } 62 | 63 | 64 | // let o1 = new BitManip(682); 65 | // let act = o1.setKthIndexBit(0); // 683 66 | -------------------------------------------------------------------------------- /js-util-combinations-without-repetition.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {number[][]} points 3 | * @return {number} 4 | */ 5 | var largestTriangleArea = function (points) {}; 6 | 7 | class nCr { 8 | // ht tps://www.geek sforgeeks.org/make-combinations-size-r/ 9 | 10 | // Prints all combinations of size r of numbers from 1 to n. 11 | nCr_wo_repitition(n, r) { 12 | // console.log(n, r); 13 | 14 | let res = []; 15 | let tmp = []; 16 | 17 | function dfs(left, r) { 18 | // Pushing this vector to a vector of vector 19 | if (r == 0) { 20 | // res.push(JSON.parse(JSON.stringify(tmp))); // ---------------- 21 | // console.log("save", tmp); 22 | // console.log(res); 23 | return; 24 | } 25 | 26 | // i iterates from left to n. First time left will be 1 27 | // i <= n 28 | // i + r - 1 <= n 29 | for (let i = left; i + r - 1 <= n; ++i) { 30 | tmp.push(i); 31 | // console.log(tmp, " ", n, i, r); 32 | 33 | dfs(i + 1, r - 1); 34 | 35 | // Popping out last inserted element from the vector 36 | tmp.pop(); 37 | } 38 | } 39 | 40 | dfs(1, r); 41 | // console.log(res); 42 | return res; 43 | } 44 | 45 | // The main function that prints all combinations of size r 46 | // in arr[] of size n. This function mainly uses nCr_wo_reptn() 47 | nCr_wo_repitition_2(n, r) { 48 | /* arr[] ---> Input Array 49 | tmp[] ---> Temporary array to store current combination 50 | start & end ---> Staring and Ending indexes in arr[] 51 | index ---> Current index in tmp[] 52 | r ---> Size of a combination to be printed */ 53 | 54 | let arr = Array.from({ length: n }, (_, i) => i + 1); 55 | // console.log(arr, n, r); 56 | 57 | let res = []; 58 | // A temporary array to store all combination one by one 59 | let tmp = []; // new int[r](); 60 | 61 | function nCr_wo_reptn(tmp, start, end, index, r) { 62 | // Current combination is ready to be printed, print it 63 | if (index == r) { 64 | // res.push(JSON.parse(JSON.stringify(tmp))); // ---------------- 65 | // for (let j = 0; j < r; j++) System.out.print(tmp[j] + " "); 66 | // System.out.println(""); 67 | return; 68 | } 69 | 70 | // replace index with all possible elements. The condition 71 | // "end-i+1 >= r-index" makes sure that including one element 72 | // at index will make a combination with remaining elements 73 | // at remaining positions 74 | for (let i = start; i <= end && end - i + 1 >= r - index; i++) { 75 | tmp[index] = arr[i]; 76 | nCr_wo_reptn(tmp, i + 1, end, index + 1, r); 77 | } 78 | } 79 | 80 | // Print all combination using temprary array 'tmp[]' 81 | nCr_wo_reptn(tmp, 0, n - 1, 0, r); 82 | 83 | return res; 84 | } 85 | 86 | // The main function that prints all combinations of size r 87 | // in arr[] of size n. This function mainly uses nCr_wo_reptn2() 88 | nCr_wo_repitition_3(n, r) { 89 | // ht tps://www.geeks forgeeks.org/print-all-possible-combinations-of-r-elements-in-a-given-array-of-size-n/ 90 | // This method is mainly based on Pascal’s Identity, i.e. ncr = n-1cr + n-1cr-1 91 | 92 | let arr = Array.from({ length: n }, (_, i) => i + 1); 93 | // console.log(arr, n, r); 94 | 95 | /* arr[] ---> Input Array 96 | tmp[] ---> Temporary array to store current combination 97 | start & end ---> Staring and Ending indexes in arr[] 98 | index ---> Current index in tmp[] 99 | r ---> Size of a combination to be printed */ 100 | 101 | let res = []; 102 | // A temporary array to store all combination one by one 103 | let tmp = []; // new int[r](); 104 | 105 | function nCr_wo_reptn2(n, r, index, tmp, i) { 106 | // Current combination is ready to be printed, print it 107 | if (index == r) { 108 | // res.push(JSON.parse(JSON.stringify(tmp))); // ---------------- 109 | // for (let j = 0; j < r; j++) System.out.print(tmp[j] + " "); 110 | // System.out.println(""); 111 | return; 112 | } 113 | 114 | // When no more elements are there to put in tmp[] 115 | if (i >= n) return; 116 | 117 | // current is included, put next at next location 118 | tmp[index] = arr[i]; 119 | nCr_wo_reptn2(n, r, index + 1, tmp, i + 1); 120 | 121 | // current is excluded, replace it with next (Note that 122 | // i+1 is passed, but index is not changed) 123 | nCr_wo_reptn2(n, r, index, tmp, i + 1); 124 | } 125 | 126 | // Print all combination using temprary array 'tmp[]' 127 | nCr_wo_reptn2(n, r, 0, tmp, 0); 128 | 129 | return res; 130 | } 131 | 132 | test() { 133 | // let n = 5; 134 | // let r = 3; 135 | // 136 | // let exp = [ 137 | // [1, 2, 3], 138 | // [1, 2, 4], 139 | // [1, 2, 5], 140 | // [1, 3, 4], 141 | // [1, 3, 5], 142 | // [1, 4, 5], 143 | // [2, 3, 4], 144 | // [2, 3, 5], 145 | // [2, 4, 5], 146 | // [3, 4, 5], 147 | // ]; 148 | // 149 | // let res = this.nCr_wo_repitition(n, r); // [][] 150 | // console.log(res); 151 | // console.log( 152 | // JSON.stringify(res) == JSON.stringify(exp) ? "pass" : "fail" 153 | // ); 154 | 155 | let startTime; 156 | 157 | let MAX_N = 50; 158 | let MAX_R = 3; // MAX_N; 159 | 160 | // 27 - 7/8/9 secs, 28 = time out <--------------------------- lets take this 161 | startTime = new Date().getTime(); 162 | for (let n = 1; n <= MAX_N; n++) { 163 | for (let r = 1; r <= MAX_R; r++) { 164 | let res = this.nCr_wo_repitition(n, r); // [][] 165 | } 166 | } 167 | console.log(new Date().getTime() - startTime, "ms"); 168 | 169 | // 27 - 8/9 secs, 28 = time out 170 | startTime = new Date().getTime(); 171 | for (let n = 1; n <= MAX_N; n++) { 172 | for (let r = 1; r <= MAX_R; r++) { 173 | let res = this.nCr_wo_repitition_2(n, r); 174 | } 175 | } 176 | console.log(new Date().getTime() - startTime, "ms"); 177 | 178 | // 24=8-9 secs, 25=time out 179 | startTime = new Date().getTime(); 180 | for (let n = 1; n <= MAX_N; n++) { 181 | for (let r = 1; r <= MAX_R; r++) { 182 | let res = this.nCr_wo_repitition_3(n, r); 183 | } 184 | } 185 | console.log(new Date().getTime() - startTime, "ms"); 186 | 187 | return 0; 188 | } 189 | } 190 | 191 | new nCr().test(); 192 | -------------------------------------------------------------------------------- /js-util-permutation.js: -------------------------------------------------------------------------------- 1 | class Permutation { 2 | constructor(a) { 3 | if (!a) return; 4 | 5 | this.a = a; 6 | 7 | // NOTE 8 | // --------- sort to get all permutations --------- 9 | a = a.sort((a, b) => a.charCodeAt(0) - b.charCodeAt(0)); 10 | // a = a.sort((a, b) => a - b); 11 | 12 | // console.log(a); 13 | this.first = true; 14 | } 15 | 16 | // find next greater number. modifies original array to store result 17 | next() { 18 | if (this.first) { 19 | this.first = !this.first; 20 | return this.a; 21 | } 22 | 23 | let a = this.a; 24 | 25 | let n = a.length; 26 | 27 | if (!n) return []; 28 | 29 | let i; 30 | 31 | // I) Start from the right most digit and find the first digit that is smaller than the digit next to it. 32 | for (i = n - 1; i > 0; i--) { 33 | if (a[i] > a[i - 1]) { 34 | break; 35 | } 36 | } 37 | 38 | // If no such digit is found, then all digits are in descending order means there cannot be a greater number with same set of digits 39 | if (i == 0) { 40 | // console.log("All done."); 41 | return []; 42 | } 43 | let x = a[i - 1], 44 | min = i; 45 | 46 | // II) Find the smallest digit on right side of (i-1)'th digit that is greater than number[i-1] 47 | for (let j = i + 1; j < n; j++) { 48 | if (a[j] > x && a[j] < a[min]) { 49 | min = j; 50 | } 51 | } 52 | 53 | // III) Swap the above found smallest digit with number[i-1] 54 | // console.log(a); 55 | [a[min], a[i - 1]] = [a[i - 1], a[min]]; 56 | // console.log(a); 57 | 58 | // IV) Sort the digits after (i-1) in ascending order 59 | a = a 60 | .slice(0, i) 61 | .concat( 62 | a.slice(i).sort((a, b) => a.charCodeAt(0) - b.charCodeAt(0)) 63 | ); 64 | // Arrays.sort(a, i, n); 65 | // console.log("Next number with same" + " set of digits is "); 66 | // console.log(a); 67 | 68 | this.a = a; 69 | return this.a; 70 | } 71 | 72 | test() { 73 | { 74 | let a = ["1", "2", "3"]; 75 | let o1 = new Permutation(a); 76 | console.log(o1.next(a)); 77 | } 78 | 79 | { 80 | let a = ["1", "2", "3"]; 81 | let o1 = new Permutation(a); 82 | 83 | let aa = []; 84 | let cc = 0; 85 | 86 | let temp = []; 87 | while ((temp = o1.next()).length) { 88 | aa.push(JSON.parse(JSON.stringify(temp))); 89 | cc++; 90 | } 91 | 92 | console.log(aa); 93 | } 94 | } 95 | } 96 | 97 | let o1 = new Permutation(); 98 | o1.test(); 99 | -------------------------------------------------------------------------------- /js-util-power-set-on-array.js: -------------------------------------------------------------------------------- 1 | class SetElements { 2 | constructor(s) { 3 | this.s = s; 4 | 5 | // NOTE 6 | // this.aa = [[]]; //////// CHECKKK - Empty set is required? 7 | this.aa = []; // Empty set is not required 8 | } 9 | 10 | generate(t, start, pos) { 11 | if (pos == t.length) { 12 | // console.log(t); 13 | this.aa.push(JSON.parse(JSON.stringify(t))); 14 | return true; 15 | } 16 | 17 | for (let i = start; pos < t.length && i < this.s.length; i++) { 18 | t[pos] = this.s[i]; 19 | this.generate(t, i + 1, pos + 1); 20 | } 21 | } 22 | 23 | getPowerSet() { 24 | let s = this.s; 25 | for (let c = 1; c <= s.length; c++) { 26 | this.generate(s.substr(0, c).split(""), 0, 0); 27 | } 28 | return this.aa; 29 | } 30 | 31 | test() { 32 | let o1 = new SetElements("ABC"); 33 | console.log(o1.getPowerSet()); 34 | } 35 | } 36 | 37 | let o1 = new SetElements(); 38 | o1.test(); 39 | -------------------------------------------------------------------------------- /longest-increasing-sequence.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | Let L be the list, that contains N elements, say, from 0 to N-1 4 | Make one pass from left to right of list L, from 0th index element to N-1 index element 5 | 6 | Save the 1st element (0th index) in List S, continue the pass with 2nd element (1st index) 7 | Also, SAVE, from which element this element came from (possibly index) (##), into list fromIndexL (for first element the value is -1) (#$) 8 | 9 | While the pass is still on: 10 | If next is increasing of current 11 | SAVE into S, and then continue the pass, with next element in list (NOTE: S list has increasing elements)(#) 12 | Also, SAVE, from which element this next element came from (possibly index) (##), into list fromIndexL 13 | else: 14 | Find the next's position in S, using binary search (see, NOTE above, S list is ascending order) 15 | If S is found: 16 | nothing to do 17 | else: 18 | it is possible that next is not found, but you will find the element that is > next, say it nextOfnext 19 | REPLACE nextOfnext with next, in S list (REPLACE is similar to SAVE above, #) 20 | Also, SAVE, from which element this next element came from (possibly index), into list fromIndexL - similar to (##) above - this will be same as from which element nextOfnext came from 21 | 22 | NOTE: From the above while, for each element (~N elements), there is binary search done (~ log N elements), so it is O(N * log N) runtime complexity 23 | 24 | Now, we have 2 lists populated, list S, and list fromIndexL. 25 | Take the last element of S list, print it, see from where it came from in fromIndexL list 26 | print that element, and see from where that element it came from in fromIndexL list 27 | continue this until we see from element as -1 (see #$ above) 28 | 29 | We have printed longest increasing sequence 30 | */ 31 | -------------------------------------------------------------------------------- /main.js: -------------------------------------------------------------------------------- 1 | 2 | // this is for all basics files 3 | // 4 | 5 | 6 | // (new (require('./basics_a_pow_n'))()).runTests(); 7 | // (new (require('./basics_fact_n'))()).runTests(); 8 | (new (require('./basics_fibo_n'))()).runTests(); 9 | -------------------------------------------------------------------------------- /minmaxsum.cpp: -------------------------------------------------------------------------------- 1 | 2 | // Contributed by: https://github.com/jupiterrocks 3 | 4 | #include 5 | using namespace std; 6 | int main() 7 | { 8 | long long int A[5],sum; int i,j; long long max,min; 9 | 10 | for(i=0;i<5;i++) 11 | { 12 | cin>>A[i]; 13 | } 14 | max=0; 15 | min=A[0]+A[1]+A[2]+A[3]+A[4]; 16 | for(i=0;i<5;i++) 17 | { sum=0; 18 | for(j=0;j<5;j++) 19 | { 20 | if(i!=j) 21 | { 22 | sum+=A[j]; 23 | } 24 | } 25 | if(maxsum) 30 | { 31 | min=sum; 32 | } 33 | } 34 | 35 | cout< 2 | probability (P) - numerical value 3 | sample space (S) - well defined SET of possible outcomes (of an experiment) 4 | event (A,B, etc) - well defined SET of         outcomes (of an experiment) with a probability 5 |                   is subset of sample space (S) 6 | experiment       - any procedure that can be infinitely repeated, has a sample space 7 | 8 | #1 9 | probability of sample space (S) = P(S) = 1 10 | 11 | #2 12 | probability of     occurence of event (A) = P(A) is beteen 0 and 1, both inclusive, 0<=P(A)<=1 13 | probability of non-occurence of event (A) = P(A') is beteen 0 and 1, both inclusive, 0<=P(A)<=1 14 | 15 | P(A) = number of favourable outcomes / total number of outcomes 16 | P(A) = |A| / |S| 17 | 18 | if A and A' is S 19 | then P(A) + P(A') = P(S) 20 | => P(A) + P(A') = 1 21 | => P(A') = 1 - P(A) 22 | 23 | 24 | Simple event 25 | Compound event  = combination of simple events 26 | 27 | A U B = occurence of A or B 28 | A n B = occurence of A and B 29 | 30 | P(A U B) = P(A) + P(B) - P(A n B) 31 | 32 | Mutually exclusive (disjoint) events 33 | = No common outcomes of between A and B 34 | A n B = Pi (empty set) 35 | P(A n B) = 0 36 | 37 | P(A U B) = P(A) + P(B) - P(A n B) 38 | => P(A U B) = P(A) + P(B) - 0 39 | => P(A U B) = P(A) + P(B) 40 | 41 | 42 | 43 | 44 | -------------------------------------------------------------------------------- /nbproject/private/private.properties: -------------------------------------------------------------------------------- 1 | browser=Chrome.INTEGRATED 2 | server=EXTERNAL 3 | -------------------------------------------------------------------------------- /nbproject/private/private.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /nbproject/project.properties: -------------------------------------------------------------------------------- 1 | auxiliary.org-netbeans-modules-javascript-nodejs.enabled=true 2 | auxiliary.org-netbeans-modules-javascript-nodejs.run_2e_enabled=true 3 | auxiliary.org-netbeans-modules-javascript-nodejs.start_2e_file=main.js 4 | files.encoding=UTF-8 5 | run.as=node.js 6 | source.folder= 7 | -------------------------------------------------------------------------------- /nbproject/project.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | org.netbeans.modules.web.clientproject 4 | 5 | 6 | mycp 7 | 8 | 9 | 10 | -------------------------------------------------------------------------------- /old-my-datastructures-in-c/.gitattributes: -------------------------------------------------------------------------------- 1 | # Auto detect text files and perform LF normalization 2 | * text=auto 3 | 4 | # Custom for Visual Studio 5 | *.cs diff=csharp 6 | *.sln merge=union 7 | *.csproj merge=union 8 | *.vbproj merge=union 9 | *.fsproj merge=union 10 | *.dbproj merge=union 11 | 12 | # Standard to msysgit 13 | *.doc diff=astextplain 14 | *.DOC diff=astextplain 15 | *.docx diff=astextplain 16 | *.DOCX diff=astextplain 17 | *.dot diff=astextplain 18 | *.DOT diff=astextplain 19 | *.pdf diff=astextplain 20 | *.PDF diff=astextplain 21 | *.rtf diff=astextplain 22 | *.RTF diff=astextplain 23 | -------------------------------------------------------------------------------- /old-my-datastructures-in-c/.gitignore: -------------------------------------------------------------------------------- 1 | # Windows image file caches 2 | Thumbs.db 3 | ehthumbs.db 4 | 5 | # Folder config file 6 | Desktop.ini 7 | 8 | # Recycle Bin used on file shares 9 | $RECYCLE.BIN/ 10 | 11 | # Windows Installer files 12 | *.cab 13 | *.msi 14 | *.msm 15 | *.msp 16 | 17 | # ========================= 18 | # Operating System Files 19 | # ========================= 20 | 21 | # OSX 22 | # ========================= 23 | 24 | .DS_Store 25 | .AppleDouble 26 | .LSOverride 27 | 28 | # Icon must ends with two \r. 29 | Icon 30 | 31 | # Thumbnails 32 | ._* 33 | 34 | # Files that might appear on external disk 35 | .Spotlight-V100 36 | .Trashes 37 | 38 | Debug/datastructures.Build.CppClean.log 39 | Debug/array.obj 40 | datastructures.opensdf 41 | datastructures.sdf 42 | datastructures.v12.suo 43 | Debug/datastructures.ilk 44 | Debug/datastructures.log 45 | Debug/datastructures.obj 46 | Debug/datastructures.pdb 47 | Debug/datastructures.tlog/cl.command.1.tlog 48 | Debug/datastructures.tlog/CL.write.1.tlog 49 | Debug/datastructures.tlog/CL.read.1.tlog 50 | Debug/datastructures.tlog/datastructures.lastbuildstate 51 | Debug/datastructures.tlog/link.write.1.tlog 52 | Debug/datastructures.tlog/link.read.1.tlog 53 | Debug/datastructures.tlog/link.command.1.tlog 54 | Debug/vc120.idb 55 | Debug/vc120.pdb 56 | *.obj 57 | *.obj 58 | Debug/common.obj 59 | Debug/common.obj 60 | Debug/common.obj 61 | *.tlog 62 | *.obj -------------------------------------------------------------------------------- /old-my-datastructures-in-c/BST.c: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/manoharreddyporeddy/math-advanced-data-structures-and-algorithms/60c574f31b6461b2d702072a06eae5de5b6bb73b/old-my-datastructures-in-c/BST.c -------------------------------------------------------------------------------- /old-my-datastructures-in-c/BST.h: -------------------------------------------------------------------------------- 1 | #ifndef BST_H_INCLUDED 2 | #define BST_H_INCLUDED 3 | #include "common.h" 4 | #include "binarytree.h" 5 | 6 | // Binary Search Tree (BST) 7 | 8 | typedef struct bst_node bst_node; 9 | struct bst_node 10 | { 11 | int key; 12 | int data; 13 | bst_node *left, *right; 14 | }; 15 | 16 | // build tree 17 | bst_node* bst_create_from_array(int arr[], int len); 18 | 19 | // insert 20 | void bst_insert(bst_node *root, int ele); 21 | 22 | // delete 23 | void bst_delete(bst_node *root, int ele); 24 | 25 | #endif // BST_H_INCLUDED 26 | -------------------------------------------------------------------------------- /old-my-datastructures-in-c/ReadMe.txt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/manoharreddyporeddy/math-advanced-data-structures-and-algorithms/60c574f31b6461b2d702072a06eae5de5b6bb73b/old-my-datastructures-in-c/ReadMe.txt -------------------------------------------------------------------------------- /old-my-datastructures-in-c/ReadMe_binarytree_types.txt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/manoharreddyporeddy/math-advanced-data-structures-and-algorithms/60c574f31b6461b2d702072a06eae5de5b6bb73b/old-my-datastructures-in-c/ReadMe_binarytree_types.txt -------------------------------------------------------------------------------- /old-my-datastructures-in-c/ReadMe_tree_types.txt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/manoharreddyporeddy/math-advanced-data-structures-and-algorithms/60c574f31b6461b2d702072a06eae5de5b6bb73b/old-my-datastructures-in-c/ReadMe_tree_types.txt -------------------------------------------------------------------------------- /old-my-datastructures-in-c/_main.c: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/manoharreddyporeddy/math-advanced-data-structures-and-algorithms/60c574f31b6461b2d702072a06eae5de5b6bb73b/old-my-datastructures-in-c/_main.c -------------------------------------------------------------------------------- /old-my-datastructures-in-c/array.c: -------------------------------------------------------------------------------- 1 | #include "array.h" 2 | /** 3 | array 4 | number of elements in specified order 5 | They are accessed using an integer to specify which element required 6 | (although the elements may be of almost any type). 7 | Typical implementations allocate contiguous memory words for the elements of arrays 8 | (but this is not always a necessity). 9 | Arrays may be fixed-length or expandable. 10 | */ 11 | 12 | int print_array(int *parr, int size) 13 | { 14 | for (int i=0; isize]; // expected constant expression 27 | // static int arr[pdynarr->size]; // error: storage pdynarr->size of 'arr' isn't constant| 28 | // static int arr[pdynarr->size] = {0}; // error: variable-sized object may not be initialized| 29 | // static int arr[pdynarr->size] = {0}; // error C2057: expected constant expression 30 | // static int arr[5] = { 0 }; // OK 31 | // preallocated space in the data section of the program 32 | static int arr[5]; 33 | 34 | return arr; 35 | } 36 | 37 | /// Dynamic Allocates memory & also initializes an array 38 | dynamic_array_struct* create_dynamic_array(dynamic_array_struct *pdynarr, int capacity) 39 | { 40 | assert(capacity > 0); 41 | void* _parr=malloc(sizeof(int)*capacity); 42 | if (_parr) 43 | { 44 | pdynarr->parr=_parr; 45 | pdynarr->capacity=pdynarr->size=capacity; 46 | } 47 | 48 | return pdynarr; 49 | } 50 | 51 | /// initializes integer array with 'init_value_from' till 'init_value_from' + size, for size elements 52 | const int initialize_array(int *parr, const int size, int init_value_from) 53 | { 54 | int i; 55 | for (i=0; icapacity; // lets double memory each time, hope new requested cap is less than this 68 | 69 | if (capacity_requested > capacity_projected_required) // higher than existing 70 | { 71 | capacity_projected_required = capacity_requested; 72 | } 73 | else if (capacity_requested < (2/3)*pdynarr->capacity) // lot lesser than existing, lets reduce memory 74 | { 75 | capacity_projected_required = (2/3)*pdynarr->capacity; 76 | } 77 | else if (pdynarr->capacity > capacity_requested) // higher than existing 78 | { 79 | return true; // nothing to do 80 | } 81 | 82 | int* parr_temp = realloc(pdynarr->parr, sizeof(int)*capacity_projected_required); // pdynarr->parr will have garbage for the new elements at the end 83 | if (parr_temp) 84 | { 85 | pdynarr->capacity = capacity_projected_required; 86 | // print_array(parr_temp, pdynarr->size); 87 | return true; 88 | } 89 | 90 | return false; 91 | } 92 | 93 | /// Free memory of a pointer and also sets to NULL 94 | void free_dynamic_array(int **pparr) 95 | { 96 | if (*pparr) 97 | { 98 | free (*pparr); 99 | *pparr = NULL; 100 | } 101 | } 102 | 103 | /// array_get_element_at 104 | /// O(1) 105 | int array_get_element_at(const int *parr, const int size, const int index) 106 | { 107 | if ( (index>=0) && (indexparr]; // works too- -> a+b = b+a // commutative 111 | } 112 | else 113 | { 114 | printf("array_get_element_at: invalid index\n"); 115 | return -1; 116 | } 117 | } 118 | 119 | /// array_set_element_at 120 | /// O(1) 121 | bool array_set_element_at(int *parr, const int size, const int index, const int ele) 122 | { 123 | if ((index>=0) && (indexsize-1; 160 | 161 | // move elements to right by 1, from begin_index to end_index of array 162 | for (int i=end_index; i>=begin_index; i--) 163 | { 164 | pdynarr->parr[i+1] = pdynarr->parr[i]; 165 | } 166 | pdynarr->size++; 167 | 168 | pdynarr->parr[begin_index] = 0; 169 | return pdynarr->parr; 170 | } 171 | 172 | int* left_shift_dynamic_array(dynamic_array_struct *pdynarr, int begin_index, int end_index) 173 | { 174 | if (!end_index) 175 | end_index = pdynarr->size-1; 176 | 177 | // move elements to left by 1, from begin_index to end_index of array 178 | for (int i=begin_index; i<=end_index; i++) 179 | { 180 | pdynarr->parr[i] = pdynarr->parr[i+1]; 181 | } 182 | pdynarr->size--; 183 | 184 | pdynarr->parr[end_index] = 0; 185 | return pdynarr->parr; 186 | } 187 | 188 | /// array_insert_at_begin 189 | /// O(n) 190 | int array_insert_at_begin(dynamic_array_struct *pdynarr, const int ele) 191 | { 192 | myprintf20("array_insert_at_begin: "); 193 | // print_array(pdynarr->parr, pdynarr->size); 194 | 195 | if (resize_dynamic_array_capacity(pdynarr, pdynarr->size+1)) 196 | { 197 | right_shift_dynamic_array(pdynarr,0,0); 198 | 199 | pdynarr->parr[0] = ele; 200 | print_array(pdynarr->parr, pdynarr->size); 201 | } 202 | return pdynarr->size; 203 | } 204 | 205 | /// array_insert_at_end 206 | /// O(1) 207 | int array_insert_at_end(dynamic_array_struct *pdynarr, const int ele) 208 | { 209 | myprintf20("array_insert_at_end: "); 210 | // print_array(pdynarr->parr, pdynarr->size); 211 | 212 | if (resize_dynamic_array_capacity(pdynarr, pdynarr->size+1)) 213 | { 214 | pdynarr->parr[pdynarr->size] = ele; 215 | pdynarr->size++; 216 | print_array(pdynarr->parr, pdynarr->size); 217 | } 218 | 219 | return pdynarr->size; 220 | } 221 | 222 | /// array_insert_at_middle 223 | /// O(n) 224 | int array_insert_at_middle(dynamic_array_struct *pdynarr, const int ele) 225 | { 226 | myprintf20("array_insert_at_middle: "); 227 | // print_array(pdynarr->parr, pdynarr->size); 228 | 229 | if (resize_dynamic_array_capacity(pdynarr, pdynarr->size+1)) 230 | { 231 | int middle_index = pdynarr->size / 2; 232 | right_shift_dynamic_array(pdynarr, middle_index, 0); 233 | 234 | pdynarr->parr[middle_index] = ele; 235 | print_array(pdynarr->parr, pdynarr->size); 236 | } 237 | 238 | return pdynarr->size; 239 | } 240 | 241 | 242 | /// array_delete_at_begin 243 | /// O(n) 244 | int array_delete_at_begin(dynamic_array_struct *pdynarr) 245 | { 246 | myprintf20("array_delete_at_begin: "); 247 | // print_array(pdynarr->parr, pdynarr->size); 248 | 249 | left_shift_dynamic_array(pdynarr,0,0); 250 | resize_dynamic_array_capacity(pdynarr, pdynarr->size-1); // TODO: is resize needed? yes, if deleted many times then significant mem is wasted 251 | 252 | print_array(pdynarr->parr, pdynarr->size); 253 | return pdynarr->size; 254 | } 255 | 256 | /// array_delete_at_end 257 | /// O(1) 258 | int array_delete_at_end(dynamic_array_struct *pdynarr) 259 | { 260 | myprintf20("array_delete_at_end: "); 261 | // print_array(pdynarr->parr, pdynarr->size); 262 | 263 | pdynarr->size--; 264 | resize_dynamic_array_capacity(pdynarr, pdynarr->size-1); 265 | 266 | print_array(pdynarr->parr, pdynarr->size); 267 | return pdynarr->size; 268 | } 269 | 270 | /// array_delete_at_middle 271 | /// O(n) 272 | int array_delete_at_middle(dynamic_array_struct *pdynarr) 273 | { 274 | myprintf20("array_delete_at_middle: "); 275 | 276 | int middle_index = pdynarr->size / 2; 277 | left_shift_dynamic_array(pdynarr, middle_index, 0); 278 | 279 | resize_dynamic_array_capacity(pdynarr, pdynarr->size-1); // ?? 280 | 281 | print_array(pdynarr->parr, pdynarr->size); 282 | return pdynarr->size; 283 | } 284 | -------------------------------------------------------------------------------- /old-my-datastructures-in-c/array.h: -------------------------------------------------------------------------------- 1 | #ifndef ARRAY_H_INCLUDED 2 | #define ARRAY_H_INCLUDED 3 | #include "common.h" 4 | 5 | // Dynamic integer array 6 | typedef struct 7 | { 8 | int *parr; 9 | int capacity; 10 | int size; 11 | } dynamic_array_struct; 12 | 13 | // create an array 14 | int* get_fixed_array(); 15 | // create a dynamic array, growable array, resizeable array, dynamic table, mutable array, or array list 16 | dynamic_array_struct* create_dynamic_array(dynamic_array_struct *pdynarr, int capacity); 17 | 18 | /// wasted space 19 | bool resize_dynamic_array_capacity(dynamic_array_struct *pdynarr, const int capacity_requested); 20 | void free_dynamic_array(int** pparr); 21 | 22 | const int initialize_array(int *pdynarr, const int size, int ele_val_seed); 23 | int print_array(int *parr, int size); 24 | 25 | /// indexing 26 | int array_get_element_at(const int *parr, const int size, const int index); 27 | bool array_set_element_at(int *parr, const int size, const int index, const int ele); 28 | int array_get_index_of(int *parr, const int size, const int ele); 29 | 30 | /// insert/delete at begin 31 | int array_insert_at_begin(dynamic_array_struct *pdynarr, const int ele); 32 | int array_delete_at_begin(dynamic_array_struct *pdynarr); 33 | 34 | /// insert/delete at end 35 | int array_insert_at_end(dynamic_array_struct *pdynarr, const int ele); 36 | int array_delete_at_end(dynamic_array_struct *pdynarr); 37 | 38 | /// insert/delete at middle 39 | int array_insert_at_middle(dynamic_array_struct *pdynarr, const int ele); 40 | int array_delete_at_middle(dynamic_array_struct *pdynarr); 41 | 42 | #endif // ARRAY_H_INCLUDED 43 | -------------------------------------------------------------------------------- /old-my-datastructures-in-c/binaryheap.c: -------------------------------------------------------------------------------- 1 | #include "binaryheap.h" 2 | 3 | // max heap 4 | // parent >= child 5 | // all level are same, filled from left to right 6 | 7 | // min heap 8 | // parent <= child 9 | // all level are same, last level filled from left to right 10 | 11 | // FIXME: hack to reuse in BST, only for printf format 12 | extern char *bintree_format; 13 | extern char *bintree_format_int; 14 | 15 | bh_node* binaryheap_create_from_array(int arr[], int len) 16 | { 17 | bintree_format = bintree_format_int; 18 | 19 | bh_node *start = NULL; 20 | if (len > 0) 21 | { 22 | bh_node *new_node = (bh_node *) malloc(sizeof(bh_node)); 23 | new_node->data = new_node->key = arr[0]; // 1st ele // FIXME: For now, data & key are same, so data cannot be unique 24 | new_node->left = NULL; 25 | new_node->right = NULL; 26 | 27 | start = new_node; 28 | 29 | for (int i = 1; i < len; i++) // i from 1, for rest of eles 30 | { 31 | binaryheap_insert(start, arr[i]); 32 | } 33 | } 34 | 35 | return start; 36 | } 37 | 38 | void binaryheap_insert(bh_node *root, int ele) 39 | { 40 | // implementing max-heap (parent >= child, and so root has highest key) 41 | 42 | bh_node *new_node = (bh_node *) malloc(sizeof(bh_node)); 43 | new_node->data = new_node->key = ele; 44 | new_node->left = NULL; 45 | new_node->right = NULL; 46 | 47 | 48 | 49 | static bool to_left = true; // ********* changed value, for this variable, is retained, between function calls 50 | 51 | 52 | 53 | bh_node *current = root; 54 | { 55 | if (new_node->key < current->key) // new val is less the current node's left, so move the current node down, <= is not put to reduce up-heap? 56 | { 57 | if (to_left == true) // add to left 58 | { 59 | while (current->left) 60 | { 61 | if ((new_node->key < current->left->key) && (current->right)) 62 | current = current->left; // while current left exists, go to it 63 | else 64 | break; 65 | } 66 | if (!(current->right)) 67 | { 68 | current->right = new_node; 69 | } 70 | else 71 | { 72 | new_node->left = current->left; 73 | current->left = new_node; 74 | } 75 | } 76 | else // add to right 77 | { 78 | while (current->right) 79 | { 80 | if ((new_node->key < current->right->key) && (current->left)) 81 | current = current->right; // while current left exists, go to it 82 | else 83 | break; 84 | } 85 | if (!(current->left)) 86 | { 87 | current->left = new_node; 88 | } 89 | else 90 | { 91 | new_node->right = current->right; 92 | current->right = new_node; 93 | } 94 | } 95 | } 96 | else if (new_node->key > current->key) 97 | { 98 | if (to_left == true) // add to left 99 | { 100 | new_node->left = current; 101 | root = new_node; 102 | } 103 | else 104 | { 105 | new_node->right = current; 106 | root = new_node; 107 | } 108 | } 109 | 110 | to_left = !to_left; // next time insert to right/left 111 | 112 | // else 113 | // { 114 | // printf("invalid, key shud be unique\n"); // TODO: == looks invalid, key shud be unique 115 | // break; 116 | // } 117 | } 118 | // if (new_node->key < current->key) 119 | // { 120 | // // new node shud be in left subtree 121 | // current->left = new_node; 122 | // } 123 | // else if (new_node->key > current->key) 124 | // { 125 | // // new node shud be in right subtree 126 | // current->right = new_node; 127 | // } 128 | } 129 | 130 | void binaryheap_delete(bh_node *root, int ele) 131 | { 132 | bh_node *parent = NULL; 133 | bh_node *foundnode = (bh_node *)bintree_find((bintree_node *)root, (bintree_node **)&parent, ele); 134 | if (foundnode != NULL) 135 | { 136 | // node found 137 | 138 | // both left and right of node found, are null 139 | if (((foundnode)->left == NULL) && ((foundnode)->right == NULL)) 140 | { // SAME AS BINTREE 141 | // adjacent parent's link to this found node to null 142 | (parent->left == foundnode) ? (parent->left = NULL) : (parent->right = NULL); 143 | 144 | // delete found node 145 | free(foundnode); 146 | foundnode = NULL; 147 | } 148 | // either left or right of node found, is [not, see above] null 149 | else if (((foundnode)->left == NULL) || ((foundnode)->right == NULL)) 150 | { // SAME AS BINTREE 151 | // adjacent parent's link to this found node to found node's non-null child 152 | bh_node *foundnodechild = ((foundnode)->left != NULL ? (foundnode)->left : (foundnode)->right); // get the non-null child 153 | (parent->left == foundnode) ? (parent->left = foundnodechild) : (parent->right = foundnodechild); 154 | 155 | // delete found node 156 | free(foundnode); 157 | foundnode = NULL; 158 | } 159 | // both left and right of node found, are not null 160 | else 161 | { 162 | // find the immediate predecessor 163 | // copy immediate predecessor to found node 164 | // free immediate predecessor, thru its parent 165 | 166 | // find the immediate predecessor 167 | bh_node *foundnode_immpredecessorchild = (foundnode)->left; 168 | bh_node *foundnode_immpredecessorchild_parent = foundnode; 169 | while (foundnode_immpredecessorchild->right) 170 | { 171 | foundnode_immpredecessorchild_parent = foundnode_immpredecessorchild; 172 | foundnode_immpredecessorchild = foundnode_immpredecessorchild->right; 173 | } 174 | 175 | // copy thru parent into foundnode, from foundnode's immpredecessorchild 176 | foundnode->data = foundnode->key = foundnode_immpredecessorchild->data; 177 | 178 | // delete foundnode's immpredecessorchild, thru its parent 179 | if (foundnode_immpredecessorchild_parent->left == foundnode_immpredecessorchild) 180 | { 181 | free(foundnode_immpredecessorchild_parent->left); 182 | foundnode_immpredecessorchild_parent->left = NULL; 183 | } 184 | else 185 | { 186 | free(foundnode_immpredecessorchild_parent->right); 187 | foundnode_immpredecessorchild_parent->right = NULL; 188 | } 189 | } 190 | } 191 | else 192 | { 193 | printf("node with %c not found\n", ele); 194 | } 195 | } 196 | -------------------------------------------------------------------------------- /old-my-datastructures-in-c/binaryheap.h: -------------------------------------------------------------------------------- 1 | #ifndef BINARYHEAP_H_INCLUDED 2 | #define BINARYHEAP_H_INCLUDED 3 | #include "common.h" 4 | #include "binarytree.h" 5 | 6 | 7 | 8 | typedef struct bh_node bh_node; 9 | struct bh_node 10 | { 11 | int key; 12 | int data; 13 | bh_node *left, *right; 14 | }; 15 | 16 | // build tree 17 | bh_node* binaryheap_create_from_array(int arr[], int len); 18 | 19 | // insert 20 | void binaryheap_insert(bh_node *root, int ele); 21 | 22 | // delete 23 | void binaryheap_delete(bh_node *root, int ele); 24 | 25 | #endif // BINARYHEAP_H_INCLUDED 26 | -------------------------------------------------------------------------------- /old-my-datastructures-in-c/binarytree.c: -------------------------------------------------------------------------------- 1 | #include "binarytree.h" 2 | 3 | // FIXME: hack to reuse in BST, only for printf format 4 | char *bintree_format = "%1c "; 5 | char *bintree_format_char = "%1c "; 6 | char *bintree_format_int = "%3d "; 7 | 8 | bintree_node* _create_bintree_node(const int ele) 9 | { 10 | bintree_node *new_node = (bintree_node *)malloc(sizeof(bintree_node)); 11 | new_node->data = ele; 12 | new_node->left = NULL; 13 | new_node->right = NULL; 14 | 15 | return new_node; 16 | } 17 | 18 | bintree_node* bintree_build_from_in_order_and_pre_order_arrays(int in_order_arr[], int pre_order_arr[], int in_order_begin_index, int in_order_end_index) 19 | { 20 | bintree_format = bintree_format_char; // FIXME: hack to reuse in BST, only for printf format 21 | 22 | if (in_order_begin_index > in_order_end_index) 23 | return NULL; 24 | 25 | static int pre_order_index = 0; 26 | int pre_order_data = pre_order_arr[pre_order_index++]; 27 | 28 | bintree_node *new_node = _create_bintree_node(pre_order_data); 29 | // printf(bintree_format, new_node->data); 30 | 31 | for (int ii = in_order_begin_index; ii <= in_order_end_index; ii++) 32 | { 33 | if (in_order_arr[ii] == pre_order_data) 34 | { 35 | new_node->left = bintree_build_from_in_order_and_pre_order_arrays(in_order_arr, pre_order_arr, in_order_begin_index, ii - 1); 36 | new_node->right = bintree_build_from_in_order_and_pre_order_arrays(in_order_arr, pre_order_arr, ii + 1, in_order_end_index); 37 | break; 38 | } 39 | } 40 | 41 | return new_node; 42 | } 43 | 44 | bool bintree_empty(bintree_node *root) 45 | { 46 | if (root == NULL) 47 | return true; 48 | 49 | return false; 50 | } 51 | 52 | void bintree_traverse_in_order(bintree_node *root) 53 | { 54 | if (root != NULL) 55 | { 56 | bintree_traverse_in_order(root->left); 57 | printf(bintree_format, root->data); 58 | bintree_traverse_in_order(root->right); 59 | } 60 | } 61 | 62 | void bintree_traverse_pre_order(bintree_node *root) 63 | { 64 | if (root != NULL) 65 | { 66 | printf(bintree_format, root->data); 67 | bintree_traverse_pre_order(root->left); 68 | bintree_traverse_pre_order(root->right); 69 | } 70 | } 71 | 72 | void bintree_traverse_post_order(bintree_node *root) 73 | { 74 | if (root != NULL) 75 | { 76 | bintree_traverse_post_order(root->left); 77 | bintree_traverse_post_order(root->right); 78 | printf(bintree_format, root->data); 79 | } 80 | } 81 | 82 | void bintree_traverse_level_order(bintree_node *root) 83 | { 84 | if (root == NULL) 85 | { 86 | return; 87 | } 88 | 89 | llqueue llq1; 90 | initialise_llqueue(&llq1); 91 | 92 | llqueue_push(&llq1, (unsigned int)root); 93 | llqueue_push(&llq1, (unsigned int)99999); // dummy statement for printing purposes only 94 | 95 | bintree_node *ptemp = NULL; 96 | while (!llqueue_empty(&llq1)) 97 | { 98 | ptemp = (bintree_node *)llqueue_pop(&llq1); 99 | if ((unsigned int)ptemp == 99999) // dummy statement for printing purposes only 100 | { 101 | printf("\t"); 102 | } 103 | else 104 | { 105 | printf(bintree_format, ptemp->data); 106 | 107 | if (ptemp->left) 108 | { 109 | llqueue_push(&llq1, (unsigned int)ptemp->left); 110 | } 111 | if (ptemp->right) 112 | { 113 | llqueue_push(&llq1, (unsigned int)ptemp->right); 114 | llqueue_push(&llq1, (unsigned int)99999); // dummy statement for printing purposes only 115 | } 116 | } 117 | } 118 | } 119 | 120 | void bintree_deleteall(bintree_node **root) 121 | { 122 | if (*root != NULL) 123 | { 124 | bintree_deleteall(&(*root)->left); 125 | bintree_deleteall(&(*root)->right); 126 | 127 | free(*root); 128 | (*root) = NULL; 129 | } 130 | } 131 | 132 | // pre-order find 133 | bintree_node* bintree_find(bintree_node *root, bintree_node **parent, const int ele) 134 | { 135 | if (root == NULL) 136 | { 137 | return NULL; 138 | } 139 | 140 | if (root->data == ele) 141 | { 142 | return root; 143 | } 144 | 145 | if (root->left) 146 | { 147 | bintree_node *left_node = bintree_find(root->left, &root, ele); 148 | if (left_node) 149 | { 150 | *parent = root; 151 | return left_node; 152 | } 153 | } 154 | if (root->right) 155 | { 156 | bintree_node *right_node = bintree_find(root->right, &root, ele); 157 | if (right_node) 158 | { 159 | *parent = root; 160 | return right_node; 161 | } 162 | } 163 | 164 | return NULL; 165 | } 166 | 167 | void bintree_delete(bintree_node *root, const int ele) 168 | { 169 | bintree_node *parent = NULL; 170 | bintree_node *foundnode = bintree_find(root, &parent, ele); 171 | if (foundnode == NULL) 172 | { 173 | printf("node with %d not found\n", ele); 174 | return; 175 | } 176 | 177 | // node found 178 | 179 | // both left and right of node found, are null 180 | if (((foundnode)->left == NULL) && ((foundnode)->right == NULL)) 181 | { 182 | // adjust parent's link to this found node to null 183 | (parent->left == foundnode) ? (parent->left = NULL) : (parent->right = NULL); 184 | 185 | // delete found node 186 | free(foundnode); 187 | foundnode = NULL; 188 | } 189 | // one of the left or right of node found, is null 190 | else if (((foundnode)->left == NULL) || ((foundnode)->right == NULL)) 191 | { 192 | // adjust parent's link to this found node to found node's non-null child 193 | bintree_node *foundnodechild = ((foundnode)->left != NULL ? (foundnode)->left : (foundnode)->right); // get the non-null child 194 | (parent->left == foundnode) ? (parent->left = foundnodechild) : (parent->right = foundnodechild); 195 | 196 | // delete found node 197 | free(foundnode); 198 | foundnode = NULL; 199 | } 200 | // both left and right of node found, are not null 201 | else 202 | { 203 | // delete will be unambiguous in binary tree 204 | // many ways to choose a delete, replace the contents of node found, with any leaf (possibly right-most leaf of its children) 205 | // leaving it to deal with it in binary search trees (BST) 206 | } 207 | } 208 | 209 | void bintree_insert(bintree_node *root, const int ele, bool to_left, int of_parent_ele, bool retain_parents_children_side) 210 | { 211 | bintree_node *parent = NULL; 212 | bintree_node *foundnode = bintree_find(root, &parent, of_parent_ele); 213 | if (foundnode == NULL) 214 | { 215 | printf("node with %d not found\n", of_parent_ele); 216 | return; 217 | } 218 | 219 | // node found 220 | bintree_node *new_node = _create_bintree_node(ele); 221 | if (to_left == true) 222 | { 223 | // retain the link type (left/right) of foundnode to its child - to help balancing(?) 224 | if (retain_parents_children_side == true) 225 | { 226 | new_node->left = foundnode->left; 227 | } 228 | else 229 | { 230 | new_node->right = foundnode->left; 231 | } 232 | foundnode->left = new_node; 233 | } 234 | else 235 | { 236 | // retain the link type (left/right) of foundnode to its child - to help balancing(?) 237 | if (retain_parents_children_side == true) 238 | { 239 | new_node->left = foundnode->right; 240 | } 241 | else 242 | { 243 | new_node->right = foundnode->right; 244 | } 245 | foundnode->right = new_node; 246 | } 247 | } 248 | -------------------------------------------------------------------------------- /old-my-datastructures-in-c/binarytree.h: -------------------------------------------------------------------------------- 1 | #ifndef BINARYREE_H_INCLUDED 2 | #define BINARYREE_H_INCLUDED 3 | #include "common.h" 4 | #include "llqueue.h" 5 | 6 | typedef struct bintree_node bintree_node; 7 | struct bintree_node 8 | { 9 | int data; 10 | bintree_node *left, *right; 11 | }; 12 | 13 | // build tree 14 | bintree_node* bintree_build_from_in_order_and_pre_order_arrays(int in_order_arr[], int pre_order_arr[], int in_order_begin_index, int in_order_end_index); 15 | 16 | // check if empty 17 | bool bintree_empty(bintree_node *root); 18 | 19 | // depth first search traversal : in-order, pre-order, post-order 20 | void bintree_traverse_in_order(bintree_node *root); 21 | void bintree_traverse_pre_order(bintree_node *root); 22 | void bintree_traverse_post_order(bintree_node *root); 23 | 24 | // breadth first search traversal : level-order walk 25 | void bintree_traverse_level_order(bintree_node *root); 26 | 27 | // search 28 | bintree_node* bintree_find(bintree_node *root, bintree_node **parent, const int ele); 29 | 30 | // delete 31 | void bintree_delete(bintree_node *root, const int ele); 32 | void bintree_deleteall(bintree_node **root); 33 | 34 | // insert 35 | void bintree_insert(bintree_node *root, const int ele, bool to_left, int of_parent_ele, bool retain_parents_children_side); 36 | 37 | #endif // BINARYREE_H_INCLUDED 38 | -------------------------------------------------------------------------------- /old-my-datastructures-in-c/common.c: -------------------------------------------------------------------------------- 1 | #include "common.h" 2 | 3 | void myprintf20(const char *str) 4 | { 5 | printf("%-20s", str); 6 | } 7 | -------------------------------------------------------------------------------- /old-my-datastructures-in-c/common.h: -------------------------------------------------------------------------------- 1 | #ifndef COMMON_H_INCLUDED 2 | #define COMMON_H_INCLUDED 3 | 4 | #include 5 | #include /* malloc, calloc, realloc, free */ 6 | #include 7 | #include 8 | #include /* true, false */ 9 | 10 | void myprintf20(const char *str); 11 | 12 | #endif // COMMON_H_INCLUDED 13 | -------------------------------------------------------------------------------- /old-my-datastructures-in-c/datastructures.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio Express 2013 for Windows Desktop 4 | VisualStudioVersion = 12.0.30723.0 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "datastructures", "datastructures.vcxproj", "{D9C2955E-5833-4B14-B2C3-5AA70F8CB6F0}" 7 | EndProject 8 | Global 9 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 10 | Debug|Win32 = Debug|Win32 11 | Release|Win32 = Release|Win32 12 | EndGlobalSection 13 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 14 | {D9C2955E-5833-4B14-B2C3-5AA70F8CB6F0}.Debug|Win32.ActiveCfg = Debug|Win32 15 | {D9C2955E-5833-4B14-B2C3-5AA70F8CB6F0}.Debug|Win32.Build.0 = Debug|Win32 16 | {D9C2955E-5833-4B14-B2C3-5AA70F8CB6F0}.Release|Win32.ActiveCfg = Release|Win32 17 | {D9C2955E-5833-4B14-B2C3-5AA70F8CB6F0}.Release|Win32.Build.0 = Release|Win32 18 | EndGlobalSection 19 | GlobalSection(SolutionProperties) = preSolution 20 | HideSolutionNode = FALSE 21 | EndGlobalSection 22 | EndGlobal 23 | -------------------------------------------------------------------------------- /old-my-datastructures-in-c/datastructures.vcxproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | Debug 6 | Win32 7 | 8 | 9 | Release 10 | Win32 11 | 12 | 13 | 14 | {D9C2955E-5833-4B14-B2C3-5AA70F8CB6F0} 15 | Win32Proj 16 | datastructures 17 | 18 | 19 | 20 | Application 21 | true 22 | v120 23 | Unicode 24 | 25 | 26 | Application 27 | false 28 | v120 29 | true 30 | Unicode 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | true 44 | 45 | 46 | false 47 | 48 | 49 | 50 | 51 | 52 | Level3 53 | Disabled 54 | WIN32;_DEBUG;_CONSOLE;_LIB;%(PreprocessorDefinitions) 55 | 56 | 57 | Console 58 | true 59 | 60 | 61 | 62 | 63 | Level3 64 | 65 | 66 | MaxSpeed 67 | true 68 | true 69 | WIN32;NDEBUG;_CONSOLE;_LIB;%(PreprocessorDefinitions) 70 | 71 | 72 | Console 73 | true 74 | true 75 | true 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | 93 | 94 | 95 | 96 | 97 | 98 | 99 | 100 | 101 | 102 | 103 | 104 | 105 | 106 | 107 | 108 | 109 | 110 | 111 | 112 | -------------------------------------------------------------------------------- /old-my-datastructures-in-c/datastructures.vcxproj.filters: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | {4FC737F1-C7A5-4376-A066-2A32D752A2FF} 6 | cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx 7 | 8 | 9 | {93995380-89BD-4b04-88EB-625FBE52EBFB} 10 | h;hh;hpp;hxx;hm;inl;inc;xsd 11 | 12 | 13 | {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} 14 | rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | Header Files 25 | 26 | 27 | Header Files 28 | 29 | 30 | Header Files 31 | 32 | 33 | Header Files 34 | 35 | 36 | Header Files 37 | 38 | 39 | Header Files 40 | 41 | 42 | Header Files 43 | 44 | 45 | Header Files 46 | 47 | 48 | Header Files 49 | 50 | 51 | Header Files 52 | 53 | 54 | Header Files 55 | 56 | 57 | 58 | 59 | Source Files 60 | 61 | 62 | Source Files 63 | 64 | 65 | Source Files 66 | 67 | 68 | Source Files 69 | 70 | 71 | Source Files 72 | 73 | 74 | Source Files 75 | 76 | 77 | Source Files 78 | 79 | 80 | Source Files 81 | 82 | 83 | Source Files 84 | 85 | 86 | Source Files 87 | 88 | 89 | Source Files 90 | 91 | 92 | -------------------------------------------------------------------------------- /old-my-datastructures-in-c/datastructures.vcxproj.user: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | false 5 | 6 | -------------------------------------------------------------------------------- /old-my-datastructures-in-c/linkedlist.c: -------------------------------------------------------------------------------- 1 | #include "linkedlist.h" 2 | 3 | node* _ll_create_new_node(ele) 4 | { 5 | node *new_node = (node*)malloc(sizeof(node)); 6 | 7 | new_node->data = ele; 8 | new_node->next = NULL; 9 | 10 | return new_node; 11 | } 12 | 13 | node* ll_create_linked_list(node *start, int arr[], int len) 14 | { 15 | if (len == 0) 16 | return NULL; 17 | 18 | int i = 0; 19 | node *temp = NULL; 20 | if (start == NULL) 21 | { 22 | temp = start = _ll_create_new_node(arr[i++]); 23 | } 24 | 25 | for (; i < len; i++) 26 | { 27 | temp->next = _ll_create_new_node(arr[i]); 28 | temp = temp->next; 29 | } 30 | 31 | return start; 32 | } 33 | 34 | void ll_traverse(node *start) 35 | { 36 | node *ptemp = start; 37 | 38 | while (ptemp) 39 | { 40 | printf("%c ", ptemp->data); 41 | ptemp = ptemp->next; 42 | } 43 | 44 | printf("\n"); 45 | } 46 | 47 | node* ll_insert_at_begin(node *start, unsigned int ele) 48 | { 49 | node *new_node = _ll_create_new_node(ele); 50 | 51 | new_node->next = start; 52 | start = new_node; 53 | 54 | return start; 55 | } 56 | 57 | node* ll_insert_at_pos(node *start, unsigned int ele, const int at_position) // at_position could be another node as position here 58 | { 59 | if (start == NULL) 60 | { 61 | printf("Linked List is null\n"); 62 | return start; 63 | } 64 | if (at_position <= 0) 65 | { 66 | printf("Position should be > 0\n"); 67 | return start; 68 | } 69 | 70 | node *ptemp = start; 71 | int pos; 72 | for (pos = 1; pos < at_position - 1; pos++) 73 | { 74 | ptemp = ptemp->next; 75 | if (ptemp == NULL) 76 | break; 77 | } 78 | 79 | if (pos != at_position - 1) 80 | { 81 | printf("Position could not be found within linked list\n"); 82 | return start; 83 | } 84 | 85 | node *new_node = (node*)malloc(sizeof(node)); 86 | new_node->data = ele; 87 | 88 | new_node->next = ptemp->next; 89 | ptemp->next = new_node; 90 | 91 | return start; 92 | } 93 | 94 | node* ll_insert_after_node(node *pafter_node, unsigned int ele) 95 | { 96 | // NOTE: pafter_node could be a single or linked list, caller responsibility 97 | if (pafter_node) 98 | { 99 | node *new_node = (node*)malloc(sizeof(node)); 100 | new_node->data = ele; 101 | 102 | new_node->next = pafter_node->next; 103 | pafter_node->next = new_node; 104 | 105 | return new_node; 106 | } 107 | else 108 | { 109 | printf("Position does not exist\n"); 110 | } 111 | 112 | return pafter_node; 113 | } 114 | 115 | node* unused_ll_insert_after_value(node *start, unsigned int ele, unsigned int after_ele) 116 | { 117 | node *ptemp = start; 118 | 119 | while ((ptemp != NULL) && (ptemp->data != after_ele)) 120 | { 121 | ptemp = ptemp->next; 122 | } 123 | 124 | if (ptemp->data == after_ele) 125 | { 126 | node *new_node = (node*)malloc(sizeof(node)); 127 | new_node->data = ele; 128 | new_node->next = ptemp->next; 129 | ptemp->next = new_node; 130 | } 131 | else 132 | { 133 | printf("Position does not exist\n"); 134 | } 135 | 136 | return start; 137 | } 138 | 139 | bool ll_delete_node(node *delete_node) 140 | { 141 | printf("%c is being deleted.. ", delete_node->data); 142 | free(delete_node); 143 | printf("done\n"); 144 | delete_node = NULL; 145 | 146 | return true; 147 | } 148 | 149 | node* ll_delete_begin(node *start) 150 | { 151 | node *ptemp = start; 152 | start = start->next; 153 | 154 | ll_delete_node(ptemp); 155 | 156 | return start; 157 | } 158 | 159 | node* ll_delete_at_pos(node *start, int at_position) 160 | { 161 | if (at_position == 1) 162 | return ll_delete_begin(start); 163 | 164 | node *ptemp = start; 165 | int pos; 166 | for (pos = 1; pos < at_position - 1; pos++) 167 | { 168 | ptemp = ptemp->next; 169 | if (ptemp == NULL) 170 | break; 171 | } 172 | if (ptemp->next == NULL) 173 | { 174 | printf("Position does not exist in linked list\n"); 175 | return start; 176 | } 177 | 178 | node *temp = ptemp->next; 179 | ptemp->next = ptemp->next->next; 180 | 181 | ll_delete_node(temp); 182 | 183 | return start; 184 | } 185 | -------------------------------------------------------------------------------- /old-my-datastructures-in-c/linkedlist.h: -------------------------------------------------------------------------------- 1 | #ifndef LINKEDLIST_H_INCLUDED 2 | #define LINKEDLIST_H_INCLUDED 3 | #include "common.h" 4 | 5 | typedef struct node node; 6 | 7 | struct node 8 | { 9 | unsigned int data; 10 | node *next; 11 | }; 12 | 13 | node* _ll_create_new_node(ele); 14 | node* ll_create_linked_list(node *start, int arr[], int len); 15 | void ll_traverse(node *start); 16 | 17 | node* ll_insert_at_begin(node *start, unsigned int ele); 18 | node* ll_insert_at_pos(node *start, unsigned int ele, const int at_position); 19 | node* ll_insert_after_node(node *pafter_node, unsigned int ele); 20 | node* unused_ll_insert_after_value(node *start, unsigned int ele, unsigned int after_ele); 21 | 22 | node* ll_delete_begin(node *start); 23 | node* ll_delete_at_pos(node *start, int at_position); 24 | 25 | #endif // LINKEDLIST_H_INCLUDED 26 | -------------------------------------------------------------------------------- /old-my-datastructures-in-c/llqueue.c: -------------------------------------------------------------------------------- 1 | #include "llqueue.h" 2 | 3 | void initialise_llqueue(llqueue *llqueue1) 4 | { 5 | llqueue1->front = llqueue1->rear = NULL; 6 | } 7 | 8 | bool llqueue_empty(const llqueue *llqueue1) // is empty 9 | { 10 | if (llqueue1->rear == NULL) 11 | { 12 | return true; 13 | } 14 | 15 | return false; 16 | } 17 | 18 | void llqueue_push(llqueue *llqueue1, unsigned int ele) // at rear 19 | { 20 | if (llqueue1->rear == NULL) 21 | { 22 | llqueue1->front = 23 | llqueue1->rear = 24 | ll_insert_at_begin(llqueue1->rear, ele); 25 | return; 26 | } 27 | 28 | llqueue1->rear = ll_insert_after_node(llqueue1->rear, ele); 29 | } 30 | 31 | unsigned int llqueue_pop(llqueue *llqueue1) // at front 32 | { 33 | unsigned int temp = (unsigned int)llqueue1->front->data; 34 | 35 | llqueue1->front = llqueue1->front->next; 36 | if (llqueue1->front == NULL) 37 | { 38 | llqueue1->rear = NULL; 39 | } 40 | 41 | return temp; 42 | } 43 | 44 | unsigned int llqueue_rear_data(const llqueue *llqueue1) // get rear 45 | { 46 | if (llqueue1->rear != NULL) 47 | { 48 | return llqueue1->rear->data; 49 | } 50 | else 51 | { 52 | return -1; // FIXME: using -1 as error code 53 | } 54 | } 55 | 56 | unsigned int llqueue_front_data(const llqueue *llqueue1) // get front 57 | { 58 | if (llqueue1->front != NULL) 59 | { 60 | return llqueue1->front->data; 61 | } 62 | else 63 | { 64 | return -1; // FIXME: using -1 as error code 65 | } 66 | } 67 | -------------------------------------------------------------------------------- /old-my-datastructures-in-c/llqueue.h: -------------------------------------------------------------------------------- 1 | #ifndef LLQUEUE_H_INCLUDED 2 | #define LLQUEUE_H_INCLUDED 3 | #include "common.h" 4 | #include "linkedlist.h" 5 | 6 | typedef struct llqueue llqueue; 7 | struct llqueue 8 | { 9 | node *front; 10 | node *rear; 11 | }; 12 | 13 | void initialise_llqueue(llqueue *llqueue1); 14 | void llqueue_push(llqueue *llqueue1, unsigned int ele); // at rear // NOTE: prefixing with filename to eliminate naming conflits 15 | unsigned int llqueue_pop(llqueue *llqueue1); // at front 16 | unsigned int llqueue_rear_data(const llqueue *llqueue1); // get rear 17 | unsigned int llqueue_front_data(const llqueue *llqueue1); // get front 18 | bool llqueue_empty(const llqueue *llqueue1); // is empty 19 | // TO DO ? 20 | int llqueue_size(const llqueue *llqueue1); // get size 21 | 22 | #endif // LLQUEUE_H_INCLUDED 23 | -------------------------------------------------------------------------------- /old-my-datastructures-in-c/queue.c: -------------------------------------------------------------------------------- 1 | #include "queue.h" 2 | 3 | #define QUEUE_IS_EMPTY (pq->rear + 1 == pq->front) 4 | #define QUEUE_IS_NOT_EMPTY (!QUEUE_IS_EMPTY) 5 | #define QUEUE_SIZE (pq->rear - pq->front + 1) 6 | #define QUEUE_IS_FULL (QUEUE_SIZE == QUEUE_CAPACITY) 7 | 8 | void queue_init(queue *pq, const int invalid_ele) 9 | { 10 | pq->rear = -1; // index of eles 11 | pq->front = 0; // index of eles 12 | 13 | pq->invalid_ele = invalid_ele; 14 | } 15 | 16 | int queue_size(const queue *pq) 17 | { 18 | return QUEUE_SIZE; 19 | } 20 | 21 | bool queue_empty(const queue *pq) 22 | { 23 | if (QUEUE_IS_EMPTY) { 24 | printf("queue empty. "); 25 | return true; 26 | } 27 | 28 | return false; 29 | } 30 | 31 | bool queue_full(const queue *pq) 32 | { 33 | if (QUEUE_IS_FULL) { 34 | printf("queue full. \n"); 35 | return true; 36 | } 37 | 38 | return false; 39 | } 40 | 41 | int queue_rear(const queue *pq) 42 | { 43 | if (queue_empty(pq)) { 44 | return pq->invalid_ele; 45 | } 46 | 47 | return pq->eles[pq->rear]; 48 | } 49 | 50 | int queue_front(const queue *pq) 51 | { 52 | if (queue_empty(pq)) { 53 | return pq->invalid_ele; 54 | } 55 | 56 | return pq->eles[pq->front]; 57 | } 58 | 59 | void queue_push(queue *pq, const int ele) 60 | { 61 | if (queue_full(pq)) { 62 | return; 63 | } 64 | 65 | pq->rear++; 66 | pq->eles[pq->rear] = ele; 67 | } 68 | 69 | int queue_pop(queue *pq) 70 | { 71 | if (queue_empty(pq)) { 72 | return pq->invalid_ele; 73 | } 74 | 75 | int ele = pq->eles[pq->front]; 76 | pq->front++; 77 | return ele; 78 | } 79 | -------------------------------------------------------------------------------- /old-my-datastructures-in-c/queue.h: -------------------------------------------------------------------------------- 1 | #ifndef QUEUE_H_INCLUDED 2 | #define QUEUE_H_INCLUDED 3 | #include "common.h" 4 | 5 | #define QUEUE_CAPACITY 100 // problem, since it is fixed. taking a big number that is large enough for the problem domain may be ok for today 6 | 7 | typedef struct 8 | { 9 | int eles[QUEUE_CAPACITY]; 10 | 11 | int front; // index of eles 12 | int rear; // index of eles 13 | 14 | int invalid_ele; // Example: = -1 or = -999; a value that pop returns when empty cllient can decide 15 | } queue; 16 | 17 | void queue_init(queue *pq, const int invalid_ele); 18 | 19 | void queue_push(queue *pq, const int ele); // at rear // NOTE: prefixing with filename to eliminate naming conflits 20 | int queue_pop(queue *pq); // at front 21 | int queue_rear(const queue *pq); // get rear 22 | int queue_front(const queue *pq); // get front 23 | bool queue_empty(const queue *pq); // is empty 24 | int queue_size(const queue *pq); // get size 25 | 26 | #endif // QUEUE_H_INCLUDED 27 | -------------------------------------------------------------------------------- /old-my-datastructures-in-c/queue_circular_buffer.c: -------------------------------------------------------------------------------- 1 | #include "queue_circular_buffer.h" 2 | 3 | #define CB_SIZE_NO_WRAP (pcb->rear - pcb->front + 1) 4 | #define CB_SIZE ((pcb->rear_wrapped == false)? CB_SIZE_NO_WRAP: CB_CAPACITY - CB_SIZE_NO_WRAP) 5 | #define CB_IS_EMPTY (CB_SIZE == 0) 6 | #define CB_IS_NOT_EMPTY (!CB_IS_EMPTY) 7 | #define CB_IS_FULL (CB_SIZE == CB_CAPACITY) 8 | 9 | void cb_init(circular_buffer *pcb, const int invalid_ele) 10 | { 11 | pcb->rear = -1; // index of eles 12 | pcb->front = 0; // index of eles 13 | 14 | pcb->rear_wrapped = false; 15 | 16 | pcb->invalid_ele = invalid_ele; 17 | } 18 | 19 | int cb_size(const circular_buffer *pcb) 20 | { 21 | return CB_SIZE; 22 | } 23 | 24 | bool cb_empty(const circular_buffer *pcb) 25 | { 26 | if (CB_IS_EMPTY) { 27 | printf("cb empty. "); 28 | return true; 29 | } 30 | 31 | return false; 32 | } 33 | 34 | int cb_rear(const circular_buffer *pcb) 35 | { 36 | if (cb_empty(pcb)) { 37 | return pcb->invalid_ele; 38 | } 39 | 40 | return pcb->eles[pcb->rear]; 41 | } 42 | 43 | int cb_front(const circular_buffer *pcb) 44 | { 45 | if (cb_empty(pcb)) { 46 | return pcb->invalid_ele; 47 | } 48 | 49 | return pcb->eles[pcb->front]; 50 | } 51 | 52 | void cb_push(circular_buffer *pcb, const int ele) 53 | { 54 | if (CB_IS_FULL) { 55 | printf("cb full. "); 56 | return; 57 | } 58 | 59 | pcb->rear++; 60 | if (pcb->rear == CB_CAPACITY) 61 | { 62 | pcb->rear = 0; 63 | pcb->rear_wrapped = true; // rear pointer rear_wrapped from end to begin 64 | } 65 | 66 | pcb->eles[pcb->rear] = ele; 67 | } 68 | 69 | int cb_pop(circular_buffer *pcb) 70 | { 71 | if (cb_empty(pcb)) { 72 | return pcb->invalid_ele; 73 | } 74 | 75 | int ele = pcb->eles[pcb->front]; 76 | pcb->front++; 77 | if (pcb->front == CB_CAPACITY) 78 | { 79 | pcb->front = 0; 80 | if (pcb->rear == CB_CAPACITY - 1) 81 | { 82 | pcb->rear = -1; 83 | } 84 | 85 | pcb->rear_wrapped = false; 86 | } 87 | 88 | return ele; 89 | } 90 | -------------------------------------------------------------------------------- /old-my-datastructures-in-c/queue_circular_buffer.h: -------------------------------------------------------------------------------- 1 | #ifndef CB_H_INCLUDED 2 | #define CB_H_INCLUDED 3 | #include "common.h" 4 | 5 | #define CB_CAPACITY 3 6 | 7 | typedef struct 8 | { 9 | int eles[CB_CAPACITY]; 10 | int front; // index of eles 11 | int rear; // index of eles 12 | 13 | bool rear_wrapped; 14 | 15 | int invalid_ele; // Example: = -1 or = -999; a value that pop returns when empty cllient can decide 16 | } circular_buffer; 17 | 18 | void cb_init(circular_buffer *pcb, const int invalid_ele); 19 | 20 | bool cb_empty(const circular_buffer *pcb); // is empty 21 | int cb_size(const circular_buffer *pcb); // get size 22 | int cb_rear(const circular_buffer *pcb); // get rear 23 | int cb_front(const circular_buffer *pcb); // get front 24 | void cb_push(circular_buffer *pcb, const int ele); // at rear // NOTE: prefixing with filename to eliminate naming conflits 25 | int cb_pop(circular_buffer *pcb); // at front 26 | 27 | #endif // CB_H_INCLUDED 28 | -------------------------------------------------------------------------------- /old-my-datastructures-in-c/stack.c: -------------------------------------------------------------------------------- 1 | #include "stack.h" 2 | 3 | #define STACK_IS_EMPTY (ps->top == -1) 4 | #define STACK_IS_NOT_EMPTY (!STACK_IS_EMPTY) 5 | #define STACK_SIZE (ps->top + 1) 6 | #define STACK_IS_FULL (STACK_SIZE == STACK_CAPACITY) 7 | 8 | void stack_init(stack *ps, int invalid_ele) 9 | { 10 | ps->top = -1; // index of eles 11 | 12 | // invalid_ele for example can be -1, or, -999 13 | // a value that pop returns when empty, cllients can decide for their problem domains 14 | ps->invalid_ele = invalid_ele; 15 | } 16 | 17 | void stack_push(stack *ps, int ele) 18 | { 19 | if (STACK_IS_FULL) { 20 | printf("stack overflow. \n"); 21 | return; 22 | } 23 | 24 | ps->top++; 25 | ps->eles[ps->top] = ele; 26 | } 27 | 28 | int stack_pop(stack *ps) 29 | { 30 | if (STACK_IS_EMPTY) { 31 | printf("stack underflow. "); 32 | return ps->invalid_ele; 33 | } 34 | 35 | int temp = ps->eles[ps->top]; // safe to return array pointer? since element exits in the static array? for single threaded app 36 | ps->top--; 37 | return temp; 38 | } 39 | 40 | bool stack_empty(stack *ps) 41 | { 42 | if (STACK_IS_EMPTY) { 43 | return true; 44 | } 45 | 46 | return false; 47 | } 48 | -------------------------------------------------------------------------------- /old-my-datastructures-in-c/stack.h: -------------------------------------------------------------------------------- 1 | #ifndef STACK_H_INCLUDED 2 | #define STACK_H_INCLUDED 3 | #include "common.h" 4 | 5 | // fixed size is restriction, should take large enough for the problem domain, or go dynamic array 6 | #define STACK_CAPACITY 100 7 | 8 | typedef struct 9 | { 10 | int eles[STACK_CAPACITY]; 11 | int top; // index of eles 12 | 13 | int invalid_ele; 14 | } stack; 15 | 16 | void stack_init(stack *ps, int invalid_ele); 17 | 18 | void stack_push(stack *ps, int ele); // NOTE: prefixing with filename to eliminate naming conflits 19 | int stack_pop(stack *ps); 20 | bool stack_empty(stack *ps); // is empty 21 | 22 | #endif // STACK_H_INCLUDED 23 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "basics", 3 | "version": "1.0.0", 4 | "keywords": ["util", "functional", "server", "client", "browser"], 5 | "author": "manoharreddyporeddy", 6 | "contributors": [], 7 | "dependencies": {} 8 | } 9 | -------------------------------------------------------------------------------- /primes-offline.cpp: -------------------------------------------------------------------------------- 1 | #define NTypeVal unsigned long 2 | 3 | template 4 | class primes_list { 5 | vector primes; // dummy, 1st prime, 2nd prime, so on 6 | vector is_primes; 7 | 8 | public: 9 | primes_list(NType N) { // ** NOTE: N > 1 ** 10 | 11 | is_primes.resize(N + 1); // 2 to N 12 | std::fill(is_primes.begin(), is_primes.end(), true); 13 | 14 | auto sqrtN = sqrt(N); 15 | for (NType i = 2; i <= sqrtN; i++) { 16 | if (is_primes[i] == true) { 17 | 18 | NType isq = i*i; 19 | for (NType j = isq; j <= N; j += i) { 20 | is_primes[j] = false; 21 | } 22 | } 23 | } 24 | 25 | primes.push_back(0); // dummy value 26 | for (NType i = 2; i <= N; i++) { 27 | if (is_primes[i] == true) { 28 | primes.push_back(i); 29 | } 30 | } 31 | 32 | } 33 | }; 34 | -------------------------------------------------------------------------------- /trie-the-dictionary.cpp: -------------------------------------------------------------------------------- 1 | // 2 | // beautiful code 3 | // 4 | 5 | #include // max, max 6 | #include 7 | #include // assert 8 | #include 9 | #include 10 | #include // deque 11 | #include // ifstream 12 | #include // greater 13 | #include // setw, setfill 14 | #include 15 | #include // numeric_limits 16 | #include // map, multimap 17 | #include 18 | #include // priority_queue (greatest on top, by default, use greater for smallest on top) 19 | #include // set 20 | #include // stringstream 21 | #include // stack 22 | #include // tuple 23 | #include 24 | #include // unordered_set 25 | #include // vector 26 | 27 | using namespace std; 28 | 29 | 30 | bool ON = 1; 31 | bool OFF = 0; 32 | 33 | #ifdef DEBUGG 34 | bool DEBUG_MODE = ON; 35 | bool LOGS = ON; 36 | #else 37 | bool DEBUG_MODE = OFF; 38 | bool LOGS = OFF; 39 | #endif 40 | 41 | template 42 | void debug(Arg&& arg, Args&&... args) { 43 | 44 | if (LOGS) { 45 | std::ostream& out = std::cout; 46 | out << std::forward(arg); 47 | using expander = int[]; 48 | ( 49 | 50 | void)expander { 51 | 0, (void(out << ' ' << std::forward(args)), 0)... 52 | }; 53 | } 54 | } 55 | 56 | template 57 | ostream & operator<<(ostream &o1, const vector &c) { 58 | for (auto it = c.begin(); it != c.end(); it++) { 59 | o1 << setw(4) << *it << " "; 60 | } 61 | return o1; 62 | } 63 | 64 | template 65 | ostream & operator<<(ostream &o1, const deque &c) { 66 | for (auto it = c.begin(); it != c.end(); it++) { 67 | o1 << setw(4) << *it << " "; 68 | } 69 | return o1; 70 | } 71 | 72 | template 73 | vector range(T N1, T N2) { 74 | vector numbers(N2 - N1); 75 | iota(numbers.begin(), numbers.end(), N1); 76 | return numbers; 77 | } 78 | 79 | template 80 | vector zero_till(T N) { 81 | vector numbers(N); 82 | iota(numbers.begin(), numbers.end(), 0); 83 | return numbers; 84 | } 85 | 86 | template 87 | vector one_till(T N) { 88 | vector numbers(N); 89 | iota(numbers.begin(), numbers.end(), 1); 90 | return numbers; 91 | } 92 | 93 | template 94 | void get_log_table(T NType) { 95 | vector _log2floor_table_; 96 | // See: http://www.rapidtables.com/math/algebra/logarithm/Logarithm_Table.htm 97 | _log2floor_table_.resize(N + 1, 0); 98 | for (NType i = 2; i < _log2floor_table_.size(); i++) { 99 | _log2floor_table_[i] = _log2floor_table_[i / 2] + 1; 100 | } 101 | } 102 | // ----------------------------------- 103 | // ----------------------------------- 104 | // ----------------------------------- 105 | 106 | // #define PTypeVal short // 1 to 50 107 | // 108 | //#define NTypeValue int // 1 to 10^5 109 | //#define MTypeValue int // 1 to 10^5 110 | //#define XTypeValue int // 1 to 10^9 111 | //#define VTypeValue int // 0 to 10^6 112 | //#define TypeValue unsigned long long // 0 to 10^6 113 | //#define PTypeVal unsigned long long 114 | //#define VTypeVal unsigned short // long long 115 | //#define PTypeVal long long 116 | //#define DTypeVal long long 117 | //#define TTypeVal unsigned long long 118 | //#define LTypeVal unsigned long long 119 | //#define SumOfLTypeVal unsigned long long 120 | 121 | /* 122 | struct Node 123 | { 124 | NTypeVal i; 125 | EleTypeVal d; 126 | Node *l, *r, *p; // lefti, righti, parent 127 | }; 128 | */ 129 | 130 | // #define PTypeVal unsigned long long 131 | // #define EleTypeVal unsigned long long 132 | // #define EleTypeVeryLargVal unsigned long long 133 | // #define SizeT unsigned int 134 | 135 | #define NTypeVal unsigned int 136 | #define EleTypeVal unsigned long 137 | #define NTypeValBig unsigned long 138 | #define EleTypeValBig unsigned long 139 | 140 | template 141 | class trie { 142 | 143 | NType i, j; 144 | NType N; 145 | 146 | class TrieNode { 147 | public: 148 | map children; // input array, with N elements 149 | bool isLeaf; 150 | TrieNode(bool &isLeaf1) { 151 | isLeaf = isLeaf1; 152 | } 153 | TrieNode(char ch1, bool isLeaf1) { 154 | children[ch1] = NULL; 155 | isLeaf = isLeaf1; 156 | } 157 | }; 158 | 159 | class TrieNode *start; 160 | 161 | /* 162 | //////////// when vector or deque? 163 | 164 | // vector> vv1; 165 | vv1.resize(_log2floor_table_[N] + 1, vector(N)); 166 | for (NType i = 0; i <= N - 1; i++) { 167 | cin >> vv1[0][i]; 168 | }*/ 169 | 170 | // unordered_set s1; 171 | // unordered_multimap > m1; 172 | // unordered_map , EleTypeVal> m1; 173 | // unordered_multimap > 174 | // pair least_gr_eq; 175 | // NType least_gr_eq_ri; 176 | // EleType least_gr_eq_rmax; 177 | 178 | public: 179 | 180 | trie(istream &cin) { 181 | 182 | // c( 183 | 184 | cin >> N; 185 | start = getEmptyNode(false); 186 | 187 | // v1.resize(N); 188 | 189 | // v1 = { 1,3,5,7,9,11 }; 190 | // v1 = { 5,6,4 ,1,7, 1,3,2 }; 191 | // v1 = { 1,4,2,3 }; 192 | // cout << one_till(N) << endl; 193 | // cout << v1 << endl; 194 | // cout << setw(4) << ai << " "; 195 | 196 | // build___trie_ment_tree__for_Range_Query_Max__wrapper(cin); 197 | //for (NType i = 0; i < _trie_.size(); i++) { 198 | // cout << _trie_[i] << endl; 199 | //} 200 | } 201 | 202 | class TrieNode *getEmptyNode(bool isLeaf) { 203 | return new class TrieNode(isLeaf); 204 | } 205 | 206 | void add_to_trie(istream &cin) { 207 | // a( 208 | 209 | string name; // [1,21] char len 210 | cin >> name; 211 | cout << "ADDING..." << name << " "; 212 | 213 | auto temp = start; 214 | 215 | size_t i = 0; 216 | 217 | for (; i < name.size() - 1; i++) { 218 | if (temp->children.find(name[i]) != temp->children.end()) { 219 | // found 220 | temp = temp->children[name[i]]; 221 | } 222 | else { 223 | // not found 224 | temp->children[name[i]] = getEmptyNode(false); 225 | cout << setw(4) << "I: " << name[i]; 226 | temp = temp->children[name[i]]; 227 | } 228 | } 229 | 230 | if (i == name.size() - 1) { 231 | temp->children[name[i]] = getEmptyNode(true); 232 | cout << setw(4) << "I: " << name[i]; 233 | temp = temp->children[name[i]]; 234 | } 235 | 236 | cout << endl; 237 | } 238 | 239 | void find_prefix_in_trie(istream &cin) { 240 | // f( 241 | 242 | string prefix; // [1,21] char len 243 | cin >> prefix; 244 | cout << "FINDING..." << prefix; 245 | 246 | auto temp = start; 247 | 248 | size_t i = 0; 249 | 250 | for (; i < prefix.size(); i++) { 251 | if (temp->children.find(prefix[i]) != temp->children.end()) { 252 | // found 253 | temp = temp->children[prefix[i]]; 254 | } 255 | else { 256 | break; 257 | } 258 | } 259 | 260 | if (i == prefix.size()) { 261 | // full prefix found 262 | cout << " FOUND."; 263 | } 264 | else { 265 | cout << " NOT FOUND."; 266 | } 267 | 268 | cout << endl; 269 | } 270 | 271 | void doMain(istream & cin) { 272 | 273 | string option; 274 | string name, prefix; // [1,21] char len 275 | 276 | while (N > 0) { 277 | cin >> option; 278 | 279 | if (option == "add") { // no duplicates 280 | add_to_trie(cin); 281 | } 282 | else { // 'find': 283 | find_prefix_in_trie(cin); 284 | } 285 | 286 | N--; 287 | } 288 | 289 | cout << endl; 290 | } 291 | }; 292 | 293 | // testsss 294 | #define ReturnCountTypeValue char 295 | vector < pair < vector, vector>> tests = { 296 | 297 | { 298 | { 299 | "7", 300 | "add abc", 301 | "add abgl", 302 | "add cdf", 303 | "add abcd", 304 | "add lmn", 305 | "find ab", 306 | "find lo" 307 | }, 308 | { 0, 0, 0, 0, 0, 0, 0, 0 } // 4(new) 3 (old) 5*10 = 50 309 | } 310 | 311 | 312 | 313 | }; 314 | 315 | class Cls1 { 316 | 317 | // HNType n; 318 | // MType m; 319 | // deque > p1; 320 | // XType x; 321 | // string S; 322 | // LenType ai; 323 | // TType type; 324 | // HVType v; 325 | // VType v; 326 | // PType P; 327 | // DType D; 328 | // KType K; 329 | // Heap> h1; 330 | // multiset se1; 331 | // deque p1; 332 | 333 | public: 334 | 335 | Cls1() { 336 | // LOGS = OFF; 337 | } 338 | 339 | 340 | vector testFunction(istream & cin) { 341 | // debug("testFunction - begin\n\n"); 342 | vector res; 343 | // -------------------- 344 | 345 | // LOGS = 0; 346 | 347 | 348 | 349 | trie o1(cin); 350 | o1.doMain(cin); 351 | 352 | 353 | auto actual_result = 0; 354 | res.push_back(actual_result); 355 | 356 | return res; 357 | } 358 | 359 | }; 360 | 361 | 362 | int main() { 363 | 364 | if (!DEBUG_MODE) { 365 | 366 | Cls1 o; 367 | o.testFunction(cin); 368 | 369 | return 0; 370 | } 371 | else { 372 | 373 | for (unsigned long i = 0; i < tests.size(); i++) { 374 | // debug("----------------------- input getting ready ----------------------------- ", "\n"); 375 | 376 | auto input = tests[i].first; 377 | auto expected_output = tests[i].second; 378 | 379 | std::stringstream ss; 380 | istream &cin = ss; 381 | 382 | for (size_t i = 0; i < input.size(); i++) { 383 | // debug(input[i], "\n"); 384 | ss << input[i] << endl; 385 | } 386 | 387 | /* 388 | ifstream ifs; 389 | // ifs.open("../lr_input09_dummy.txt"); 390 | ifs.open("../lr_input09.txt"); 391 | string temp; 392 | vector a; 393 | getline(ifs, temp); ss << temp << endl; 394 | getline(ifs, temp); ss << temp << endl; 395 | */ 396 | 397 | 398 | // debug("----------------------- input ready ----------------------------- ", "\n"); 399 | 400 | Cls1 o; 401 | // auto actual_result = o.testFunction(cin, q)[0]; 402 | auto actual_result = o.testFunction(cin)[0]; 403 | 404 | // for (PTypeVal ai = 0; ai < q; ai++) { 405 | // Cls1 o; 406 | // // // debug("\tactual_result ", actual_result, " ", "expected_output ", expected_output[ai], "\n"); 407 | // 408 | // // assert(actual_result == expected_output[ai]); 409 | // } 410 | 411 | // break; 412 | 413 | } // for tests.size() 414 | 415 | return 0; 416 | } 417 | 418 | return 0; 419 | } 420 | -------------------------------------------------------------------------------- /y-BST.txt: -------------------------------------------------------------------------------- 1 | 2 | 3 | From: http://www.personal.kent.edu/~rmuhamma/Algorithms/MyAlgorithms/binarySearchTree.htm 4 | Index: http://www.personal.kent.edu/~rmuhamma/Algorithms/algorithm.html 5 | 6 | 19 7 | 11 35 8 | 7 16 23 9 | 13 17 10 | 11 | Binary Search Tree/ BST 12 | binary_search_tree property. 13 | for each, internal node, say node 14 | any node's key in node's left sub tree is <= node 15 | any node's key in node's right sub tree is >= node 16 | 17 | left subtree < node 18 | right subtree > node 19 | 20 | 19 21 | 11 35 22 | 7 16 23 23 | 13 17 24 | 25 | NOTE: 26 | in actual, <= and >= cannot exists same time. 27 | so, one among below exists: 28 | <= and > 29 | OR 30 | < and >= 31 | OR 32 | < and > 33 | 34 | height = 35 | number of links from root to deepest node 36 | 37 | operations depend on height of tree 38 | case worst-case time 39 | complete binary tree O(log N) 40 | linear-chain tree O(N) 41 | 42 | node can have a 43 | element (also called info, it will include either key/value) 44 | and 3 pointer fields 45 | left 46 | right 47 | parent 48 | parent is NULL for root 49 | left & right are NULL for leafs 50 | Walk 51 | 52 | // 53 | // while the current node is not NULL, walk current node's left, then visit current node, then walk current node's right 54 | // 55 | inorder_walk (current_node) 56 | if current_node is NOT NULL: 57 | inorder_walk (current_node's left) 58 | access current_node's key 59 | inorder_walk (current_node's right) 60 | // 61 | // call: inorder_walk(root) 62 | // all nodes will be walked so it's O(N) 63 | // the order is: (left-subtree)current_node(right-subtree) 64 | // if printed, will be ascending order 65 | // 66 | 67 | // 68 | // while the current node is not NULL, visit current node, then walk current node's left, then walk current node's right 69 | // 70 | preorder_walk (current_node) 71 | if current_node is NOT NULL: 72 | access current_node's key 73 | preorder_walk (current_node's left) 74 | preorder_walk (current_node's right) 75 | // 76 | // call: preorder_walk(root) 77 | // all nodes will be walked so it's O(N) 78 | // the order is: current_node(left-subtree)(right-subtree) 79 | // 80 | 81 | // 82 | // while the current node is not NULL, walk current node's left, then walk current node's right, then visit current node 83 | // 84 | postorder_walk (current_node) 85 | if current_node is NOT NULL: 86 | postorder_walk (current_node's left) 87 | postorder_walk (current_node's right) 88 | access current_node's key 89 | // 90 | // call: postorder_walk(root) 91 | // all nodes will be walked so it's O(N) 92 | // the order is: (left-subtree)(right-subtree)current_node 93 | // 94 | 95 | 96 | Querying a Binary Search Tree 97 | MINIMUM, MAXIMUM, SUCCESSOR and PREDESESSOR 98 | O(h) 99 | h is height of the tree i.e., the number of links root node to the deepest node. 100 | 101 | 102 | // depending on the the given key to find, traverse down 103 | // traverse down to left, if key is < current node 104 | // traverse down to right, if key is > current node 105 | // else return node, that is, if key is = current node 106 | bst_tree_search (current_node, key) 107 | if current_node is NULL 108 | return current_node 109 | 110 | if key == current_node's key: 111 | return current_node 112 | 113 | if key < current_node's key: 114 | return bst_tree_search (current_node's left, key) 115 | else 116 | return bst_tree_search (current_node's right, key) 117 | 118 | bst_tree_search_iterative (current_node, key) 119 | 120 | while current_node != NULL AND key < current_node's key 121 | current_node = current_node's left 122 | 123 | while current_node != NULL AND key > current_node's key 124 | current_node = current_node's right 125 | 126 | if current_node == NULL: 127 | return current_node 128 | 129 | if key == current_node's key: 130 | return current_node 131 | 132 | // To get the minimum, go down to the left most element of the tree 133 | // does not look at key 134 | bst_tree_minimum (current_node) 135 | 136 | if current_node == NULL: 137 | return current_node 138 | 139 | while current_node's left != NULL 140 | current_node = current_node's left 141 | 142 | return current_node 143 | 144 | 145 | // To get the maximum, go down to the right most element of the tree 146 | // does not look at key 147 | bst_tree_maximum (current_node) 148 | 149 | if current_node == NULL: 150 | return current_node 151 | 152 | while current_node's right != NULL 153 | current_node = current_node's right 154 | 155 | return current_node 156 | 157 | 158 | // find node with key just > current_node's key 159 | // it is either 160 | // minimum element of the right child's subtree, if right child exists 161 | // or 162 | // you go up from the node, until a node's parent's right child is not the node itself. 163 | // does not look at key 164 | bst_tree_successor (current_node) 165 | 166 | if current_node's right != NULL 167 | return bst_tree_minimum (current_node's right) 168 | 169 | // ** redundant ** 170 | // if current_node's parent != NULL AND current_node's parent's key > current_node's key // looks fine but we shudn't look at keys 171 | if current_node's parent != NULL AND current_node's parent's left == current_node 172 | return current_node's parent 173 | 174 | // while current_node's parent != NULL AND current_node's parent < current_node's key // looks fine but we shudn't look at keys 175 | 176 | while current_node's parent != NULL AND current_node's parent's right == current_node 177 | current_node = current_node's parent 178 | 179 | // current_node's parent's right is now NULL or other 180 | 181 | return current_node's parent 182 | 183 | NOTE: 184 | An inorder tree walk of an n-node BST 185 | can be implemented in O(n)-time 186 | by finding the minimum element in the tree with bst_tree_minimum(x) algorithm and 187 | then making n-1 calls to bst_tree_successor (x). 188 | 189 | 190 | 191 | // find node with key just < current_node's key 192 | // it is either 193 | // maximum element of the left child's subtree, if left child exists 194 | // or 195 | // you go up from the node, until a node's parent's left child is not the node itself. 196 | // does not look at key 197 | bst_tree_predecessor (current_node) 198 | 199 | if current_node's left != NULL 200 | return bst_tree_maximum (current_node's left) 201 | 202 | // ** redundant ** 203 | // if current_node's parent != NULL AND current_node's parent's key < current_node's key // looks fine but we shudn't look at keys 204 | if current_node's parent != NULL AND current_node's parent's right == current_node 205 | return current_node's parent 206 | 207 | // while current_node's parent != NULL AND current_node's parent > current_node's key // looks fine but we shudn't look at keys 208 | 209 | while current_node's parent != NULL AND current_node's parent's left == current_node 210 | current_node = current_node's parent 211 | 212 | // current_node's parent's left is now NULL or other 213 | 214 | return current_node's parent 215 | 216 | 217 | // go to leaf, add it 218 | bst_tree_insert (current_node, node_to_insert) 219 | 220 | if current_node == NULL 221 | current_node = node_to_insert 222 | return 223 | 224 | while current_node != NULL 225 | current_node_parent = current_node 226 | 227 | if node_to_insert's key < current_node's key 228 | current_node = current_node's left 229 | else 230 | current_node = current_node's right 231 | 232 | if node_to_insert's key < current_node_parent's key 233 | current_node_parent's left = node_to_insert 234 | else 235 | current_node_parent's right = node_to_insert 236 | // ===== 237 | // if the 1st element to insert is either smallest or biggest or near to them, the tree will be nearly single chain of node 238 | // in which case the build will take O(N^2), i.e. O(N) for each of the N elements, in actually 1,2,3...N insertion cost which is n(n+1)/2 => O(N^2) 239 | // else best case blanced tree, root is in the one of mid value(s) in sorted order, build will take O(N logN), i.e. log N for each of the N elements 240 | // ===== 241 | 242 | 243 | // build bst tree from array 244 | // inorder_walk the bst tree, to print in ascending sorted order 245 | bst_tree_print_ascending_order_sort (array) 246 | 247 | current_node = NULL 248 | 249 | // create tree 250 | for each element in array: 251 | if 1st element of array: 252 | current_node = bst_tree_create_single_node(element); 253 | else: 254 | node_to_insert = bst_tree_create_single_node(element); 255 | bst_tree_insert(current_node, node_to_insert) 256 | 257 | // print inorder 258 | inorder_walk (current_node) 259 | // ===== 260 | // if the 1st element to insert is either smallest or biggest or near to them, the tree will be nearly single chain of node 261 | // in which case the build will take O(N^2), i.e. O(N) for each of the N elements, in actually 1,2,3...N insertion cost which is n(n+1)/2 => O(N^2) 262 | // else best case blanced tree, root is in the one of mid value(s) in sorted order, build will take O(N logN), i.e. log N for each of the N elements 263 | // ===== 264 | 265 | 266 | /* LOOKS CORRECT, NEEDS VERFICATION */ 267 | // case 1: if node_to_delete has no children, then delete node_to_delete 268 | // case 2: if node_to_delete has one child, link the node_to_delete's child to node_to_delete's parent, delete node_to_delete 269 | // case 2: if node_to_delete has two children, find successor of node_to_delete using current_node 270 | // copy the successor's value to node_to_delete, then delete successor node 271 | bst_tree_delete (current_node, node_to_delete) 272 | 273 | // cover both NULL 274 | if node_to_delete's right == NULL 275 | if node_to_delete's parent's left == node_to_delete 276 | node_to_delete's parent's left = node_to_delete's left 277 | else // if node_to_delete's parent's right == node_to_delete 278 | node_to_delete's parent's right = node_to_delete's left 279 | return 280 | 281 | if node_to_delete's left == NULL 282 | if node_to_delete's parent's left == node_to_delete 283 | node_to_delete's parent's left = node_to_delete's right 284 | else // if node_to_delete's parent's right == node_to_delete 285 | node_to_delete's parent's right = node_to_delete's right 286 | return 287 | 288 | successor_node = bst_tree_successor (node_to_delete) 289 | node_to_delete's key = successor_node's key 290 | delete successor_node 291 | return 292 | -------------------------------------------------------------------------------- /y-HEAP.txt: -------------------------------------------------------------------------------- 1 | 2 | In a heap, a nodes key is greater than equal to both of its children's keys. 3 | heap property does not help print the nodes in sorted order because 4 | this property does not tell us in which subtree the next item is 5 | -------------------------------------------------------------------------------- /y-primality.txt: -------------------------------------------------------------------------------- 1 | 2 | Sieve of Eratosthenes: 3 | A[N] = {0} 4 | for i from 2 to sqrt(N): 5 | if A[i] = 0: 6 | for j from 2 to N: 7 | if i*j > N: 8 | break 9 | A[i*j] = 1 10 | 11 | 12 | function: FermatPrimalityTesting(int N): 13 | pick a random integer k //not too less. not too high. 14 | LOOP: repeat k times: 15 | pick a random integer X in range (1,N-1) 16 | if(X^(N-1)%N != 1): 17 | return composite 18 | return probably prime 19 | 20 | --------------------------------------------------------------------------------