diff --git a/Bit Algorithms/Rotate Bits/C++/rotate_bits.cpp b/Bit Algorithms/Rotate Bits/C++/rotate_bits.cpp new file mode 100644 index 00000000..04686f09 --- /dev/null +++ b/Bit Algorithms/Rotate Bits/C++/rotate_bits.cpp @@ -0,0 +1,31 @@ + //Do Left and Right rotate given the number n and the shift-by value d + //Number is n + //The number of bits by which n should be rotated is given by d + //Both rotate right and rotate left is provided + //32 bit frame is taken + +#include +#include +using namespace std; +#define MAX 32 +int bit_rright(int n, int l) +{ + int a = n<<(max-l); + int b = n>>l; + return (a|b); +} +int bit_rleft(int n , int l) +{ + int a = n<>(MAX-l); + return (a|b); +} + +int main() +{ + int n,d; + cin>>n>>d; + int x=bit_rright(n,d); + int y = bit_rleft(n,d); + cout< 110010 +// l = 2 +// r = 5 +// Result -> 101100 = 44 + +#include +#include +using namespace std; + +int toggle(int n , int l , int r) +{ + int c=0; + int b=1; //For a new num, set bits between l to r + b = b<<(l-1); + for(int i=0;i>n>>l>>r; + int x = toggle(n,l,r); + cout< +#include +#include +using namespace std; + +int maxProfit(const vector &A) { + int buy = A[0], flag = 0, i = 1, max_sell = INT_MIN; + int sol = 0; + while(i < A.size()){ + int diff = A[i] - A[i-1]; + //It's a greedy appoach. If current diff is greater than 0, then add that to the solution. + if(diff> 0){ + sol = sol + diff; + } + i++; + } + + return sol; +} + +int main(){ + vector A = {1,2}; + cout << maxProfit(A); +} diff --git a/Dynamic Programming/buy_sell_stocks/README.md b/Dynamic Programming/buy_sell_stocks/README.md new file mode 100644 index 00000000..75291b0d --- /dev/null +++ b/Dynamic Programming/buy_sell_stocks/README.md @@ -0,0 +1,14 @@ +Problem Statement: +Say you have an array for which the ith element is the price of a given stock on day i. +If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit. + +Solution Approach: +If you buy your stock on day i, you’d obviously want to sell it on the day its price is maximum after that day. +So essentially at every index i, you need to find the maximum in the array in the suffix. +Now this part can be done in 2 ways : +1) Have another array which stores that information. +max[i] = max(max[i+1], A[i]) + +2) Start processing entries from the end maintaining a maximum till now. Constant additional space requirement. + + diff --git a/Dynamic Programming/jan-ken-puzzle/python/puzzle_hash.py b/Dynamic Programming/jan-ken-puzzle/python/puzzle_hash.py new file mode 100644 index 00000000..68f06d0a --- /dev/null +++ b/Dynamic Programming/jan-ken-puzzle/python/puzzle_hash.py @@ -0,0 +1,162 @@ +# Jan-Ken-Puzzle Solver +# 9293925 Caroline +# 9442688 Felipe +import random +from collections import OrderedDict + + +# positions of 4 connected neighbors +rowNbr = [-1, 1, 0, 0] +colNbr = [0, 0, -1, +1] +# dictionary of bad pieces for each piece +invalid_moves = {1: [0, 1, 3], 2: [0, 1, 2], 3: [0, 2, 3]} + + +def computeHash(table, board): + key = 0 + for i in range(len(board)): + for j in range(len(board[i])): + if board[i][j] != 0: + key ^= table[i][j][board[i][j]] + return key + + +def DFS(board, i, j, visited): + rows = len(board) + cols = len(board[0]) + + visited[i][j] = True + + # visit all connected neighbors + for k in range(4): + iNbr = i + rowNbr[k] + jNbr = j + colNbr[k] + # check if safe + if ((iNbr>= 0 and iNbr < rows) and (jNbr>= 0 and jNbr < cols)): + if (not visited[iNbr][jNbr] and board[iNbr][jNbr]): + # visit neighbor + DFS(board, iNbr, jNbr, visited) + + +def checkIslands(board): + rows = len(board) + cols = len(board[0]) + # initialize cells as unvisited + visited = [[False for j in range(cols)] for i in range(rows)] + + # traverse all cells to find islands + count = 0 + for i in range(rows): + for j in range(cols): + # if a cell with value 1 is not visited yet, + # then new island found + if visited[i][j] == False and board[i][j]: + # visit all cells in this island + # and increment island count + DFS(board, i, j, visited) + count += 1 + if (count> 1): + # if there's more than one island, + # board has no solution + return False + return True + + +def solve(cache, table, board, solutions, pieces): + success = False + state_hits = 0 + + rows = len(board) + cols = len(board[0]) + + # check cache (memoization) + key = computeHash(table, board) + if key in cache: + return cache[key] + + # check for islands + if (not checkIslands(board)): + cache[key] = [False, 0] + return cache[key] + + # store solution if found + if (pieces == 1): + for i in range(len(board)): + for j in range(len(board[i])): + if (board[i][j] != 0): + solutions.append([i+1, j+1, board[i][j]]) + cache[key] = [True, 1] + return cache[key] + + # check all alive pieces for possible jumps + for i in range(len(board)): + for j in range(len(board[i])): + current = board[i][j] + # if current is piece + if (current != 0): + # check all neighbors + for k in range(4): + iNbr = i + rowNbr[k] + jNbr = j + colNbr[k] + # check if neighbor exists and is valid + if ((iNbr>= 0 and iNbr < rows) and (jNbr>= 0 and jNbr < cols)): + neighbor = board[iNbr][jNbr] + if (neighbor not in invalid_moves[current]): + # execute jump + board[iNbr][jNbr] = current + board[i][j] = 0 + pieces -= 1 + # recurse for new state + jump = solve(cache, table, board, solutions, pieces) + if (jump[0]): + success = True + state_hits += jump[1] + # undo jump + board[iNbr][jNbr] = neighbor + board[i][j] = current + pieces += 1 + # tried all possible jumps for current state + if (not success): + cache[key] = [False, 0] + else: + cache[key] = [True, state_hits] + return cache[key] + + +def main(): + # read board + R, C = input().split() + R = int(R) + C = int(C) + + # initialize empty boad + pieces = 0 + board = [x[:] for x in [[0] * int(C)] * int(R)] + + # initialize zobrist hashing table + table = [[[random.randint(1,2**64 - 1) for i in range(4)]for j in range(C)] for k in range(R)] + + # fill board + for i in range(R): + line = input().split() + for j in range(C): + board[i][j] = int(line[j]) + if (board[i][j] != 0): + pieces += 1 + + # search for solutions + solutions = [] + cache = OrderedDict() + solve(cache, table, board, solutions, pieces) + hits = cache.popitem()[1][1] + + print(hits) + print(len(solutions)) + # display sorted unique solutions + for solution in sorted(solutions): + for value in solution: + print(str(value), end=' ') + print() + +if __name__ == '__main__': + main() diff --git a/Dynamic Programming/jan-ken-puzzle/python/test/heavy/01.in b/Dynamic Programming/jan-ken-puzzle/python/test/heavy/01.in new file mode 100644 index 00000000..88d73ff8 --- /dev/null +++ b/Dynamic Programming/jan-ken-puzzle/python/test/heavy/01.in @@ -0,0 +1,5 @@ +4 4 +2 3 3 3 +1 3 2 3 +2 2 1 2 +1 2 1 1 diff --git a/Dynamic Programming/jan-ken-puzzle/python/test/heavy/02.in b/Dynamic Programming/jan-ken-puzzle/python/test/heavy/02.in new file mode 100644 index 00000000..e1aff55c --- /dev/null +++ b/Dynamic Programming/jan-ken-puzzle/python/test/heavy/02.in @@ -0,0 +1,5 @@ +4 5 +1 1 2 2 1 +1 3 1 1 1 +3 3 1 3 3 +0 0 3 2 0 diff --git a/Dynamic Programming/jan-ken-puzzle/python/test/heavy/03.in b/Dynamic Programming/jan-ken-puzzle/python/test/heavy/03.in new file mode 100644 index 00000000..6b0c36d4 --- /dev/null +++ b/Dynamic Programming/jan-ken-puzzle/python/test/heavy/03.in @@ -0,0 +1,5 @@ +4 5 +1 2 1 3 1 +2 2 3 3 1 +2 1 3 0 3 +1 1 1 0 2 diff --git a/Dynamic Programming/jan-ken-puzzle/python/test/heavy/04.in b/Dynamic Programming/jan-ken-puzzle/python/test/heavy/04.in new file mode 100644 index 00000000..0efdafdf --- /dev/null +++ b/Dynamic Programming/jan-ken-puzzle/python/test/heavy/04.in @@ -0,0 +1,5 @@ +4 5 +2 3 1 3 1 +3 1 2 2 2 +2 3 1 3 2 +1 3 2 1 0 diff --git a/Dynamic Programming/jan-ken-puzzle/python/test/heavy/05.in b/Dynamic Programming/jan-ken-puzzle/python/test/heavy/05.in new file mode 100644 index 00000000..8442a416 --- /dev/null +++ b/Dynamic Programming/jan-ken-puzzle/python/test/heavy/05.in @@ -0,0 +1,5 @@ +4 5 +3 1 2 2 1 +1 2 2 2 1 +1 2 1 1 3 +3 1 3 3 2 diff --git a/Dynamic Programming/jan-ken-puzzle/python/test/heavy/06.in b/Dynamic Programming/jan-ken-puzzle/python/test/heavy/06.in new file mode 100644 index 00000000..d73e8fd9 --- /dev/null +++ b/Dynamic Programming/jan-ken-puzzle/python/test/heavy/06.in @@ -0,0 +1,6 @@ +5 5 +2 3 3 3 2 +2 3 2 3 2 +0 1 2 2 2 +0 2 2 1 1 +0 1 0 3 1 diff --git a/Dynamic Programming/jan-ken-puzzle/python/test/heavy/07.in b/Dynamic Programming/jan-ken-puzzle/python/test/heavy/07.in new file mode 100644 index 00000000..9730680b --- /dev/null +++ b/Dynamic Programming/jan-ken-puzzle/python/test/heavy/07.in @@ -0,0 +1,5 @@ +4 6 +1 3 2 3 3 0 +3 2 2 3 1 3 +1 2 2 3 2 0 +1 2 1 3 3 2 diff --git a/Dynamic Programming/jan-ken-puzzle/python/test/heavy/08.in b/Dynamic Programming/jan-ken-puzzle/python/test/heavy/08.in new file mode 100644 index 00000000..18fa10cc --- /dev/null +++ b/Dynamic Programming/jan-ken-puzzle/python/test/heavy/08.in @@ -0,0 +1,4 @@ +3 8 +1 3 3 1 1 1 1 0 +1 3 2 2 1 1 2 3 +3 2 2 2 3 2 1 1 diff --git a/Dynamic Programming/jan-ken-puzzle/python/test/heavy/09.in b/Dynamic Programming/jan-ken-puzzle/python/test/heavy/09.in new file mode 100644 index 00000000..1e8305f5 --- /dev/null +++ b/Dynamic Programming/jan-ken-puzzle/python/test/heavy/09.in @@ -0,0 +1,4 @@ +3 8 +3 3 3 3 1 3 1 3 +2 2 2 1 3 3 1 0 +1 3 2 3 3 1 1 2 diff --git a/Dynamic Programming/jan-ken-puzzle/python/test/heavy/10.in b/Dynamic Programming/jan-ken-puzzle/python/test/heavy/10.in new file mode 100644 index 00000000..28df6724 --- /dev/null +++ b/Dynamic Programming/jan-ken-puzzle/python/test/heavy/10.in @@ -0,0 +1,3 @@ +2 3 +0 0 3 +2 3 3 diff --git a/Dynamic Programming/jan-ken-puzzle/python/test/heavy/results01 b/Dynamic Programming/jan-ken-puzzle/python/test/heavy/results01 new file mode 100644 index 00000000..1cf2f38f --- /dev/null +++ b/Dynamic Programming/jan-ken-puzzle/python/test/heavy/results01 @@ -0,0 +1,8 @@ +501215 +6 +2 1 3 +2 3 3 +3 2 3 +3 4 3 +4 1 3 +4 3 3 diff --git a/Dynamic Programming/jan-ken-puzzle/python/test/heavy/results02 b/Dynamic Programming/jan-ken-puzzle/python/test/heavy/results02 new file mode 100644 index 00000000..f1ef167b --- /dev/null +++ b/Dynamic Programming/jan-ken-puzzle/python/test/heavy/results02 @@ -0,0 +1,9 @@ +99131410 +7 +1 1 2 +1 3 2 +1 5 2 +2 2 2 +2 4 2 +3 1 2 +3 3 2 diff --git a/Dynamic Programming/jan-ken-puzzle/python/test/heavy/results03 b/Dynamic Programming/jan-ken-puzzle/python/test/heavy/results03 new file mode 100644 index 00000000..d2874a48 --- /dev/null +++ b/Dynamic Programming/jan-ken-puzzle/python/test/heavy/results03 @@ -0,0 +1,5 @@ +55218735 +3 +1 1 2 +1 3 2 +2 2 2 diff --git a/Dynamic Programming/jan-ken-puzzle/python/test/heavy/results04 b/Dynamic Programming/jan-ken-puzzle/python/test/heavy/results04 new file mode 100644 index 00000000..704c26c1 --- /dev/null +++ b/Dynamic Programming/jan-ken-puzzle/python/test/heavy/results04 @@ -0,0 +1,12 @@ +11491157072 +10 +1 1 3 +1 3 3 +1 5 3 +2 2 3 +2 4 3 +3 1 3 +3 3 3 +3 5 3 +4 2 3 +4 4 3 diff --git a/Dynamic Programming/jan-ken-puzzle/python/test/heavy/results05 b/Dynamic Programming/jan-ken-puzzle/python/test/heavy/results05 new file mode 100644 index 00000000..f37f5886 --- /dev/null +++ b/Dynamic Programming/jan-ken-puzzle/python/test/heavy/results05 @@ -0,0 +1,11 @@ +707769776749 +9 +1 1 2 +1 3 2 +2 2 2 +2 4 2 +3 1 2 +3 3 2 +3 5 2 +4 2 2 +4 4 2 diff --git a/Dynamic Programming/jan-ken-puzzle/python/test/heavy/results06 b/Dynamic Programming/jan-ken-puzzle/python/test/heavy/results06 new file mode 100644 index 00000000..ec7c3b27 --- /dev/null +++ b/Dynamic Programming/jan-ken-puzzle/python/test/heavy/results06 @@ -0,0 +1,5 @@ +7464445170 +3 +1 4 1 +2 5 1 +3 4 1 diff --git a/Dynamic Programming/jan-ken-puzzle/python/test/heavy/results07 b/Dynamic Programming/jan-ken-puzzle/python/test/heavy/results07 new file mode 100644 index 00000000..3c0df2e5 --- /dev/null +++ b/Dynamic Programming/jan-ken-puzzle/python/test/heavy/results07 @@ -0,0 +1,8 @@ +154887457284 +6 +1 2 3 +2 3 3 +3 2 3 +3 4 3 +4 1 3 +4 3 3 diff --git a/Dynamic Programming/jan-ken-puzzle/python/test/heavy/results08 b/Dynamic Programming/jan-ken-puzzle/python/test/heavy/results08 new file mode 100644 index 00000000..c4cde2bf --- /dev/null +++ b/Dynamic Programming/jan-ken-puzzle/python/test/heavy/results08 @@ -0,0 +1,6 @@ +1329421080 +4 +1 2 3 +2 1 3 +2 3 3 +3 2 3 diff --git a/Dynamic Programming/jan-ken-puzzle/python/test/heavy/results09 b/Dynamic Programming/jan-ken-puzzle/python/test/heavy/results09 new file mode 100644 index 00000000..3dd778fa --- /dev/null +++ b/Dynamic Programming/jan-ken-puzzle/python/test/heavy/results09 @@ -0,0 +1,6 @@ +280997347995 +4 +1 4 3 +2 3 3 +2 5 3 +3 2 3 diff --git a/Dynamic Programming/jan-ken-puzzle/python/test/heavy/results10 b/Dynamic Programming/jan-ken-puzzle/python/test/heavy/results10 new file mode 100644 index 00000000..b41f3aa1 --- /dev/null +++ b/Dynamic Programming/jan-ken-puzzle/python/test/heavy/results10 @@ -0,0 +1,3 @@ +1 +1 +1 3 2 diff --git a/Dynamic Programming/jan-ken-puzzle/python/test/light/01.in b/Dynamic Programming/jan-ken-puzzle/python/test/light/01.in new file mode 100644 index 00000000..098d6d87 --- /dev/null +++ b/Dynamic Programming/jan-ken-puzzle/python/test/light/01.in @@ -0,0 +1,5 @@ +4 4 +1 0 0 0 +2 3 2 1 +2 2 2 1 +2 2 2 2 diff --git a/Dynamic Programming/jan-ken-puzzle/python/test/light/02.in b/Dynamic Programming/jan-ken-puzzle/python/test/light/02.in new file mode 100644 index 00000000..8c25a41a --- /dev/null +++ b/Dynamic Programming/jan-ken-puzzle/python/test/light/02.in @@ -0,0 +1,5 @@ +4 4 +2 1 3 3 +0 3 3 1 +0 3 1 2 +1 2 1 1 diff --git a/Dynamic Programming/jan-ken-puzzle/python/test/light/03.in b/Dynamic Programming/jan-ken-puzzle/python/test/light/03.in new file mode 100644 index 00000000..38a1c5a8 --- /dev/null +++ b/Dynamic Programming/jan-ken-puzzle/python/test/light/03.in @@ -0,0 +1,5 @@ +4 4 +1 1 1 3 +1 2 2 2 +2 2 1 1 +2 2 1 0 diff --git a/Dynamic Programming/jan-ken-puzzle/python/test/light/04.in b/Dynamic Programming/jan-ken-puzzle/python/test/light/04.in new file mode 100644 index 00000000..14e01fe6 --- /dev/null +++ b/Dynamic Programming/jan-ken-puzzle/python/test/light/04.in @@ -0,0 +1,5 @@ +4 4 +1 2 1 3 +2 3 2 1 +2 2 1 3 +2 3 3 2 diff --git a/Dynamic Programming/jan-ken-puzzle/python/test/light/05.in b/Dynamic Programming/jan-ken-puzzle/python/test/light/05.in new file mode 100644 index 00000000..915810ea --- /dev/null +++ b/Dynamic Programming/jan-ken-puzzle/python/test/light/05.in @@ -0,0 +1,5 @@ +4 5 +2 0 2 0 2 +3 3 1 1 3 +3 2 3 3 3 +3 3 3 2 0 diff --git a/Dynamic Programming/jan-ken-puzzle/python/test/light/06.in b/Dynamic Programming/jan-ken-puzzle/python/test/light/06.in new file mode 100644 index 00000000..a2ca83e2 --- /dev/null +++ b/Dynamic Programming/jan-ken-puzzle/python/test/light/06.in @@ -0,0 +1,5 @@ +4 5 +1 1 2 2 1 +3 2 3 1 3 +0 3 3 1 3 +2 1 1 2 0 diff --git a/Dynamic Programming/jan-ken-puzzle/python/test/light/07.in b/Dynamic Programming/jan-ken-puzzle/python/test/light/07.in new file mode 100644 index 00000000..5df70701 --- /dev/null +++ b/Dynamic Programming/jan-ken-puzzle/python/test/light/07.in @@ -0,0 +1,4 @@ +3 8 +0 1 3 1 1 2 2 2 +0 2 2 3 1 1 1 2 +0 0 0 2 1 2 1 1 diff --git a/Dynamic Programming/jan-ken-puzzle/python/test/light/08.in b/Dynamic Programming/jan-ken-puzzle/python/test/light/08.in new file mode 100644 index 00000000..3489c543 --- /dev/null +++ b/Dynamic Programming/jan-ken-puzzle/python/test/light/08.in @@ -0,0 +1,3 @@ +2 11 +1 1 1 2 3 2 2 2 1 0 0 +2 1 1 3 2 2 3 3 3 3 2 diff --git a/Dynamic Programming/jan-ken-puzzle/python/test/light/09.in b/Dynamic Programming/jan-ken-puzzle/python/test/light/09.in new file mode 100644 index 00000000..e81638dc --- /dev/null +++ b/Dynamic Programming/jan-ken-puzzle/python/test/light/09.in @@ -0,0 +1,3 @@ +2 11 +0 2 1 3 2 1 1 1 1 3 3 +2 3 2 2 2 2 3 3 3 1 2 diff --git a/Dynamic Programming/jan-ken-puzzle/python/test/light/10.in b/Dynamic Programming/jan-ken-puzzle/python/test/light/10.in new file mode 100644 index 00000000..28df6724 --- /dev/null +++ b/Dynamic Programming/jan-ken-puzzle/python/test/light/10.in @@ -0,0 +1,3 @@ +2 3 +0 0 3 +2 3 3 diff --git a/Dynamic Programming/jan-ken-puzzle/python/test/light/results b/Dynamic Programming/jan-ken-puzzle/python/test/light/results new file mode 100644 index 00000000..e69de29b diff --git a/Dynamic Programming/jan-ken-puzzle/python/test/light/results0 b/Dynamic Programming/jan-ken-puzzle/python/test/light/results0 new file mode 100644 index 00000000..e69de29b diff --git a/Dynamic Programming/jan-ken-puzzle/python/test/light/results01 b/Dynamic Programming/jan-ken-puzzle/python/test/light/results01 new file mode 100644 index 00000000..00227127 --- /dev/null +++ b/Dynamic Programming/jan-ken-puzzle/python/test/light/results01 @@ -0,0 +1,7 @@ +33000 +5 +2 1 3 +2 3 3 +3 2 3 +4 1 3 +4 3 3 diff --git a/Dynamic Programming/jan-ken-puzzle/python/test/light/results02 b/Dynamic Programming/jan-ken-puzzle/python/test/light/results02 new file mode 100644 index 00000000..f0352008 --- /dev/null +++ b/Dynamic Programming/jan-ken-puzzle/python/test/light/results02 @@ -0,0 +1,6 @@ +271700 +4 +1 4 2 +2 3 2 +3 4 2 +4 3 2 diff --git a/Dynamic Programming/jan-ken-puzzle/python/test/light/results03 b/Dynamic Programming/jan-ken-puzzle/python/test/light/results03 new file mode 100644 index 00000000..0d95e826 --- /dev/null +++ b/Dynamic Programming/jan-ken-puzzle/python/test/light/results03 @@ -0,0 +1,8 @@ +365248 +6 +1 1 3 +1 3 3 +2 2 3 +2 4 3 +3 1 3 +3 3 3 diff --git a/Dynamic Programming/jan-ken-puzzle/python/test/light/results04 b/Dynamic Programming/jan-ken-puzzle/python/test/light/results04 new file mode 100644 index 00000000..e69de29b diff --git a/Dynamic Programming/jan-ken-puzzle/python/test/light/results05 b/Dynamic Programming/jan-ken-puzzle/python/test/light/results05 new file mode 100644 index 00000000..e69de29b diff --git a/Dynamic Programming/jan-ken-puzzle/python/test/light/results06 b/Dynamic Programming/jan-ken-puzzle/python/test/light/results06 new file mode 100644 index 00000000..e69de29b diff --git a/Dynamic Programming/jan-ken-puzzle/python/test/light/results07 b/Dynamic Programming/jan-ken-puzzle/python/test/light/results07 new file mode 100644 index 00000000..e69de29b diff --git a/Dynamic Programming/jan-ken-puzzle/python/test/light/results08 b/Dynamic Programming/jan-ken-puzzle/python/test/light/results08 new file mode 100644 index 00000000..e69de29b diff --git a/Dynamic Programming/jan-ken-puzzle/python/test/light/results09 b/Dynamic Programming/jan-ken-puzzle/python/test/light/results09 new file mode 100644 index 00000000..e69de29b diff --git a/Dynamic Programming/jan-ken-puzzle/python/test/light/results1 b/Dynamic Programming/jan-ken-puzzle/python/test/light/results1 new file mode 100644 index 00000000..e69de29b diff --git a/Dynamic Programming/jan-ken-puzzle/python/test/light/results10 b/Dynamic Programming/jan-ken-puzzle/python/test/light/results10 new file mode 100644 index 00000000..b41f3aa1 --- /dev/null +++ b/Dynamic Programming/jan-ken-puzzle/python/test/light/results10 @@ -0,0 +1,3 @@ +1 +1 +1 3 2 diff --git a/Dynamic Programming/jan-ken-puzzle/python/test/light/results2 b/Dynamic Programming/jan-ken-puzzle/python/test/light/results2 new file mode 100644 index 00000000..e69de29b diff --git a/Dynamic Programming/jan-ken-puzzle/python/test/light/results3 b/Dynamic Programming/jan-ken-puzzle/python/test/light/results3 new file mode 100644 index 00000000..e69de29b diff --git a/Dynamic Programming/jan-ken-puzzle/python/test/light/results4 b/Dynamic Programming/jan-ken-puzzle/python/test/light/results4 new file mode 100644 index 00000000..e69de29b diff --git a/Dynamic Programming/jan-ken-puzzle/python/test/light/results5 b/Dynamic Programming/jan-ken-puzzle/python/test/light/results5 new file mode 100644 index 00000000..e69de29b diff --git a/Dynamic Programming/jan-ken-puzzle/python/test/light/results6 b/Dynamic Programming/jan-ken-puzzle/python/test/light/results6 new file mode 100644 index 00000000..e69de29b diff --git a/Dynamic Programming/jan-ken-puzzle/python/tests_heavy.sh b/Dynamic Programming/jan-ken-puzzle/python/tests_heavy.sh new file mode 100644 index 00000000..e62158a9 --- /dev/null +++ b/Dynamic Programming/jan-ken-puzzle/python/tests_heavy.sh @@ -0,0 +1,13 @@ +#!/bin/bash +shopt -s nullglob +TIMEFORMAT='%3R' + +for ext in .in; do + files=(test/heavy/*"$ext") + for i in `seq -f %02g ${#files[@]}`; do + printf "\n$i,"; + time (python3 puzzle_hash.py < test/heavy/$i.in | tee test/heavy/results$i &> /dev/null); + # printf "\n"; + # diff -y test/heavy/results$i test/heavy/$i.out; + done +done diff --git a/Dynamic Programming/jan-ken-puzzle/python/tests_light.sh b/Dynamic Programming/jan-ken-puzzle/python/tests_light.sh new file mode 100644 index 00000000..8a56c9d9 --- /dev/null +++ b/Dynamic Programming/jan-ken-puzzle/python/tests_light.sh @@ -0,0 +1,13 @@ +#!/bin/bash +shopt -s nullglob +TIMEFORMAT='%3R' + +for ext in .in; do + files=(test/light/*"$ext") + for i in `seq -f %02g ${#files[@]}`; do + printf "\n$i,"; + time (python puzzle_hash.py < test/light/$i.in | tee test/light/results$i &> /dev/null); + # printf "\n"; + # diff -y test/light/results$i test/light/$i.out; + done +done diff --git a/Fibonacci_series.py b/Fibonacci_series.py new file mode 100644 index 00000000..b1f557f8 --- /dev/null +++ b/Fibonacci_series.py @@ -0,0 +1,28 @@ +# Program to display the Fibonacci sequence up to n-th term where n is provided by the user + +# change this value for a different result +nterms = int (input("enter the no. of terms " )) + +# uncomment to take input from the user +#nterms = int(input("How many terms? ")) + +# first two terms +n1 = 0 +n2 = 1 +count = 0 + +# check if the number of terms is valid +if nterms <= 0: + print("Please enter a positive integer") +elif nterms == 1: + print("Fibonacci sequence upto",nterms,":") + print(n1) +else: + print("Fibonacci sequence upto",nterms,":") + while count < nterms: + print(n1,end=' , ') + nth = n1 + n2 + # update values + n1 = n2 + n2 = nth + count += 1 diff --git a/Graphs/DFS/Python/dfs.py b/Graphs/DFS/Python/dfs.py new file mode 100644 index 00000000..01a6bade --- /dev/null +++ b/Graphs/DFS/Python/dfs.py @@ -0,0 +1,27 @@ +import queue +visited = [] +MAX = 20 +adj = {1: set([2,3,5]), 2: set([3]), 3: set([8,4]), 4:6} +q = queue.Queue(MAX) + +def dfs(s): + if s in visited : + return + visited.append(s) + print(s) + children = adj.get(s) + if children != None: + if isinstance(children,int): # Case : values are not a set + dfs(children) + else : # Case : values are a set + for i in children: + dfs(i) + return + +def test(): + global visited + visited = [] + print("dfs : ") + dfs(1) + +test() \ No newline at end of file diff --git a/Machine Learning/Gradient Descent/C++/SimpleGradientDescent.cpp b/Machine Learning/Gradient Descent/C++/SimpleGradientDescent.cpp new file mode 100644 index 00000000..90f0238c --- /dev/null +++ b/Machine Learning/Gradient Descent/C++/SimpleGradientDescent.cpp @@ -0,0 +1,71 @@ + +#include "Utility.h" + +using namespace std; + +// Performs predictions with the given model. +vector Predict(vector x, pair model){ + int numDataPoints = x.size(); + vector predictions(numDataPoints); + + for(int i = 0; i < numDataPoints; ++i){ + predictions[i] = x[i] * model.first + model.second; + } + + return predictions; +} + +// Performs the gradient step. +pair BatchGradientDecentStep(vector predictions, vector y, double learningRate, pair model){ + int numSamples = y.size(); + double gradientX = 0.0; + double gradientY = 0.0; + + for(int k = 0; k < numSamples; ++k){ + double error = y[k] - predictions[k]; + gradientX += ((-2.0) / (double) numSamples) * error * y[k]; + gradientY += ((-2.0) / (double) numSamples) * error; + } + + model.first = model.first - (learningRate * gradientX); + model.second = model.second - (learningRate * gradientY); + + return model; +} + +// Runs through all the epchs updating the model based on the calculated gradient. +pair LinearRegression(vector x, vector y, unsigned int epochs, double learningRate){ + // Initialize our linear regression model as: 0x + 0. + pair model(0, 0); + + for(int i = 0; i < epochs; ++i){ + auto predictions = Predict(x, model); + model = BatchGradientDecentStep(predictions, y, learningRate, model); + } + + return model; +} + +int main(){ + // Define the x range for data generation. + // Note, larger data values might cause exploding gradients. + // One possible solution is to reduce the learning rate. + pair range = pair(0,100); + + // Get data from the following linear function: 2x + 5. + pair, vector> data = GetLinearFunctionData(range, 2, 5); + vector xData = data.first; + vector yData = data.second; + + // Run for 10000 epochs with a learning rate of 0.0001. + pair model = LinearRegression(xData, yData, 10000, 0.0001); + auto predictions = Predict(xData, model); + + cout << "Data generating function: 2x + 5" << endl; + // Mean squared error: 2.37223. + cout << "Mean squared error: " << MSE(yData, predictions) << endl; + // Learned model: 2.04665x + 1.94324. + cout << "Learned model: " << model.first << "x + " << model.second << endl; + + return 0; +} \ No newline at end of file diff --git a/Machine Learning/Gradient Descent/C++/Utility.h b/Machine Learning/Gradient Descent/C++/Utility.h new file mode 100644 index 00000000..66bbea1f --- /dev/null +++ b/Machine Learning/Gradient Descent/C++/Utility.h @@ -0,0 +1,37 @@ + +/* Header-only utility functions used for gradient descent */ + +#include +#include +#include +#include +#include + +using namespace std; +using namespace boost; + +// Generating data from a linear function. +pair, vector> GetLinearFunctionData(pair range, double x, double yIntercept){ + vector xData(range.second); + vector yData(range.second); + int numSamples = range.second - range.first; + + for(int i = range.first, k = 0; i < range.second, k < numSamples; ++i, ++k){ + xData[k] = i; + yData[k] = i * x + yIntercept; + } + + pair, vector> data(xData, yData); + return data; +} + +// Sum of squared erros. +double MSE(vector actual, vector predicted){ + auto actualItt = actual.begin(); + auto predictedItt = predicted.begin(); + double sum = 0; + for( ; actualItt != actual.end(), predictedItt != predicted.end(); ++actualItt, ++predictedItt){ + sum += pow(*actualItt - *predictedItt, 2); + } + return sum/actual.size(); +} \ No newline at end of file diff --git a/Machine Learning/Gradient Descent/README.md b/Machine Learning/Gradient Descent/README.md new file mode 100644 index 00000000..51a273c4 --- /dev/null +++ b/Machine Learning/Gradient Descent/README.md @@ -0,0 +1,17 @@ + +# Gradient Descent Optimisation Algorithm + +This explanation of the algorithm will not go into details with the mathematics, however, it is an important part but it is better explained online and in books. Instead, the focus is more on a high-level explanation of the algorithm. + +Gradient descent is a mathematical optimization algorithm. It is essentially a hill-climbing algorithm that follows the gradient of the function being optimized in order to search for optimal values. It is called gradient descent because we minimize a function by incrementally following the gradient towards a local minimum. And it is often used when training machine learning models. + +A gradient is basically the derivative for multi-variable functions, but it is a vector rather than a scaler. The gradient vector encapsulates the partial derivatives of a multi-variable function with respect to its parameters. The gradient of a function with respect to its input tells us something about how it behaves when we change the input, and for gradient descent we exploit a property, that is, the gradient vector points towards the steepest ascent. Hence, minimizing a function in iterations is simply calculating the gradient and moving in the opposite direction. + +Practically, we derive the partial derivative of our error function with respect to our model parameters, calculate the partial derivative for each weight and incrementally update each parameter in the opposite sign of the corresponding partial derivative. + +## Pseudocode +Where lr is the learning rate, epochs is the number of iterations, and w are the model parameters. + + for i to num_epochs: + for w_i in w: + w_i = w_i - lr * partial_derivative(loss, w_i) diff --git a/Maths/Factorial/C#/Factorial.cs b/Maths/Factorial/C#/Factorial.cs new file mode 100644 index 00000000..16357906 --- /dev/null +++ b/Maths/Factorial/C#/Factorial.cs @@ -0,0 +1,14 @@ + class Factorial + { + public static long factorial(int inputNum) + { + if (inputNum == 1) + { + return 1; + } + else + { + return inputNum * factorial(inputNum - 1); + } + } + } \ No newline at end of file diff --git a/Maths/Factorial/C/factorial.c b/Maths/Factorial/C/factorial.c index 7536935e..818b68ce 100644 --- a/Maths/Factorial/C/factorial.c +++ b/Maths/Factorial/C/factorial.c @@ -1,5 +1,6 @@ #include "stdio.h" + long long factorial(long long n) { if(n == 1) { return 1; @@ -10,5 +11,6 @@ long long factorial(long long n) { } int main(int argc, char * argv[]) { - printf( "%d\n", factorial(5)); + printf("Enter a number"); + scanf("%d",&n); } diff --git a/Maths/Fibonacci/C++/Fibonacci.cpp b/Maths/Fibonacci/C++/Fibonacci.cpp new file mode 100644 index 00000000..61a8d341 --- /dev/null +++ b/Maths/Fibonacci/C++/Fibonacci.cpp @@ -0,0 +1,27 @@ +#include + +using namespace std; + +void fibonacci(int number) +{ + int first = 0, second = 1, next; + + for (int i = 0; i < number; i++) + { + cout << "\n" << first; + next = first + second; + first = second; + second = next; + } +} + +int main() +{ + int number; + + cout << "Enter number of terms for Series: "; + cin>> number; + + cout << "Fibonacci Series are: \n"; + fibonacci(number); +} diff --git a/Maths/Fibonacci/Python/Fibonacci_series.txt b/Maths/Fibonacci/Python/Fibonacci_series.txt new file mode 100644 index 00000000..b1f557f8 --- /dev/null +++ b/Maths/Fibonacci/Python/Fibonacci_series.txt @@ -0,0 +1,28 @@ +# Program to display the Fibonacci sequence up to n-th term where n is provided by the user + +# change this value for a different result +nterms = int (input("enter the no. of terms " )) + +# uncomment to take input from the user +#nterms = int(input("How many terms? ")) + +# first two terms +n1 = 0 +n2 = 1 +count = 0 + +# check if the number of terms is valid +if nterms <= 0: + print("Please enter a positive integer") +elif nterms == 1: + print("Fibonacci sequence upto",nterms,":") + print(n1) +else: + print("Fibonacci sequence upto",nterms,":") + while count < nterms: + print(n1,end=' , ') + nth = n1 + n2 + # update values + n1 = n2 + n2 = nth + count += 1 diff --git a/Searching/Binary Search/C++/BinarySearch.cpp b/Searching/Binary Search/C++/BinarySearch.cpp index 341fdde4..79bd92eb 100644 --- a/Searching/Binary Search/C++/BinarySearch.cpp +++ b/Searching/Binary Search/C++/BinarySearch.cpp @@ -19,7 +19,7 @@ int binarySearch(int itemList[],int itemListSize,int item) int leftIndex = 0; int rightIndex = itemListSize; int middleIndex; - while (leftIndex <= rightIndex) + while (leftIndex < rightIndex) { middleIndex = (leftIndex+rightIndex)/2; if (itemList[middleIndex] < item) diff --git a/Searching/Binary Search/C/BinarySearch.c b/Searching/Binary Search/C/BinarySearch.c index 8f30b75c..cd106437 100644 --- a/Searching/Binary Search/C/BinarySearch.c +++ b/Searching/Binary Search/C/BinarySearch.c @@ -19,7 +19,7 @@ int binarySearch(int itemList[],int itemListSize,int item) int leftIndex = 0; int rightIndex = itemListSize; int middleIndex; - while (leftIndex <= rightIndex) + while (leftIndex < rightIndex) { middleIndex = (leftIndex+rightIndex)/2; if (itemList[middleIndex] < item) diff --git a/Searching/Binary Search/Javascript/BinarySearch.js b/Searching/Binary Search/Javascript/BinarySearch.js new file mode 100644 index 00000000..70ccd749 --- /dev/null +++ b/Searching/Binary Search/Javascript/BinarySearch.js @@ -0,0 +1,21 @@ +/** Binary search algorithm in Javascript **/ +/** Follows the README.md **/ + +function binarySearch(array, target) { + let leftIndex = 0; + let rightIndex = array.length - 1; + let middleIndex; + + while (leftIndex <= rightIndex) { + middleIndex = leftIndex + Math.floor((rightIndex - leftIndex) / 2); + if (array[middleIndex] === target) { + return middleIndex; + } + if (arr[middleIndex] < target) { + leftIndex = middleIndex + 1; + } else { + rightIndex = middleIndex - 1; + } + } + return -1; +} \ No newline at end of file diff --git a/Searching/Binary Search/PHP/BinarySearch.php b/Searching/Binary Search/PHP/BinarySearch.php new file mode 100644 index 00000000..35eb011e --- /dev/null +++ b/Searching/Binary Search/PHP/BinarySearch.php @@ -0,0 +1,26 @@ + $item){ + $rightIndex = $middleIndex - 1; + } + else{ + return $middleIndex; + } + } + return -1; + } + + // Simple demonstration of the function + $array = array(1, 2, 4, 5, 6, 8, 9, 10, 14); + echo binarySearch($array, 8); +?> diff --git a/Searching/Binary Search/Python/BinarySearch.py b/Searching/Binary Search/Python/BinarySearch.py index 75cb8261..8f0ed060 100644 --- a/Searching/Binary Search/Python/BinarySearch.py +++ b/Searching/Binary Search/Python/BinarySearch.py @@ -8,7 +8,7 @@ def binary_search(item_list,item): right_index = len(item_list)-1 while left_index <= right_index: - middle_index = (left_index+right_index) / 2 + middle_index = (left_index+right_index) // 2 if item_list[middle_index] < item: left_index=middle_index+1 elif item_list[middle_index]> item: diff --git a/Searching/Binary Search/README.md b/Searching/Binary Search/README.md index a8829ca7..c6efe20a 100644 --- a/Searching/Binary Search/README.md +++ b/Searching/Binary Search/README.md @@ -1,6 +1,7 @@ # Binary Search >Worst Case Time Complexity: O(log n) +>Best Case Time Complexity: O(1) >Space Complexity: (O(1)) diff --git a/Searching/Linear Search/Java/LinearSearch.java b/Searching/Linear Search/Java/LinearSearch.java index 9467206e..386ac979 100644 --- a/Searching/Linear Search/Java/LinearSearch.java +++ b/Searching/Linear Search/Java/LinearSearch.java @@ -15,10 +15,14 @@ public class LinearSearch{ * @param item The item to search for * @return Index of the item */ - public static int linearSearch(int[] itemList,int item){ + import java.util.Scanner; + public static int linearSearch(int[] itemList,int item) + { int index=0; - while ( index < itemList.length ){ - if ( itemList[index] == item ){ + while ( index < itemList.length ) + { + if ( itemList[index] == item ) + { return index; } index++; @@ -27,8 +31,20 @@ public static int linearSearch(int[] itemList,int item){ } //Simple desmonstration of the function - public static void main(String args[]){ - System.out.println(linearSearch(new int[]{1,2,3,4,5},6)); - System.out.println(linearSearch(new int[]{1,2,3,4,5},3)); + public static void main(String args[]) + { + Scanner sc=new Scanner(System.in); + System.out.println("Enter the total number of elements you will be entering for the search: "); + int nitem=sc.nextInt(); + System.out.println("Enter the integer elements into the element list: "); + for(int i=0;iWorst Case Time Complexity: O(n) +>Best Case Time Complexity: O(1) >Space Complexity: O(1) diff --git a/Sorting/Bubble Sort/C/BubbleSort.c b/Sorting/Bubble Sort/C/BubbleSort.c index 4eaeb69a..a5490326 100644 --- a/Sorting/Bubble Sort/C/BubbleSort.c +++ b/Sorting/Bubble Sort/C/BubbleSort.c @@ -35,6 +35,7 @@ int main() { int arr[] = {6, 4, 5, 8, 2, 1, 9}; int n = sizeof(arr)/sizeof(arr[0]); + scanf("%d",&n); bubbleSort(arr, n); printArray(arr, n); return 0; diff --git a/Sorting/Bubble Sort/Go/BubbleSort.go b/Sorting/Bubble Sort/Go/BubbleSort.go new file mode 100644 index 00000000..1861f628 --- /dev/null +++ b/Sorting/Bubble Sort/Go/BubbleSort.go @@ -0,0 +1,27 @@ +package main + +import "fmt" + +func main() { + //Test Code + array := []int{1, 6, 2, 4, 9, 0, 5, 3, 7, 8} + fmt.Println("Unsorted array: ", array) + sort(array) + fmt.Println("Sorted array: ", array) +} + +func sort(arr []int) { + for i := 0; i < len(arr); i++ { + for j := 0; j < i; j++ { + if arr[j]> arr[i] { + swap(arr, i, j) + } + } + } +} + +func swap(arr []int, x, y int) { + temp := arr[x] + arr[x] = arr[y] + arr[y] = temp +} diff --git a/Sorting/Bubble Sort/Java/BubbleSort.java b/Sorting/Bubble Sort/Java/BubbleSort.java index aabfffa3..6bbe3fc5 100644 --- a/Sorting/Bubble Sort/Java/BubbleSort.java +++ b/Sorting/Bubble Sort/Java/BubbleSort.java @@ -1,6 +1,6 @@ //Bubble sort Algorithm // Java program for implementation of BubbleSort - +import java.util.Scanner; class BubbleSort { /* Fuction Implementing Bubble Sort Algorithm */ @@ -38,12 +38,17 @@ static void printArray(int arr[]) // Driver program public static void main(String args[]) { - int arr[] = {10, 7, 8, 9, 1, 5}; + Scanner sc=new Scanner(System.in); + System.out.println("Enter the number of elements to be sorted: "); + int len=sc.nextInt(); + System.out.println("Enter the elements to be sorted: "); + for(int i=0;ialist[i+1]: + temp = alist[i] + alist[i] = alist[i+1] + alist[i+1] = temp + +alist = [54,26,93,17,77,31,44,55,20] +bubbleSort(alist) +print(alist) diff --git a/Sorting/Counting Sort/Java/CountingSort.java b/Sorting/Counting Sort/Java/CountingSort.java new file mode 100644 index 00000000..f57a854d --- /dev/null +++ b/Sorting/Counting Sort/Java/CountingSort.java @@ -0,0 +1,37 @@ +public class CountingSort { + + private CountingSort() { } + + public static Integer[] sort(Integer[] unsorted) { + int maxValue = findMax(unsorted); + int[] counts = new int[maxValue + 1]; + updateCounts(unsorted, counts); + populateCounts(unsorted, counts); + return unsorted; + } + + private static int findMax(Integer[] unsorted) { + int max = Integer.MIN_VALUE; + for (int i : unsorted) { + if (i> max) + max = i; + } + return max; + } + + private static void updateCounts(Integer[] unsorted, int[] counts) { + for (int e : unsorted) + counts[e]++; + } + + private static void populateCounts(Integer[] unsorted, int[] counts) { + int index = 0; + for (int i = 0; i < counts.length; i++) { + int e = counts[i]; + while (e> 0) { + unsorted[index++] = i; + e--; + } + } + } +} diff --git a/Sorting/Heap Sort/Readme.md b/Sorting/Heap Sort/Readme.md new file mode 100644 index 00000000..c2f0a9c9 --- /dev/null +++ b/Sorting/Heap Sort/Readme.md @@ -0,0 +1,3 @@ +# Heap Sort +Heap sort is a selection based algorithm. It has an ideia similar to Selection Sort. However, instead o search the element in a list (or array), the Heap Sort search the elements in a balanced tree computed as a Heap. +The time complexiy of Heap Sort is allways O(nlogn). diff --git a/Sorting/Insertion Sort/C++/InsertionSort.cpp b/Sorting/Insertion Sort/C++/InsertionSort.cpp index 1a21831d..f1f334f2 100644 --- a/Sorting/Insertion Sort/C++/InsertionSort.cpp +++ b/Sorting/Insertion Sort/C++/InsertionSort.cpp @@ -1,38 +1,50 @@ -// Insertion sort algorithm implemented in C++ - #include +#include +#include + +#define MAX_SIZE 5 + using namespace std; -// Insertion sort function - -void insertionSort(int array[],int size){ - int current; - int i,j; - for(i=0;i0 && array[j-1]> current;j--){ - array[j]=array[j-1]; - } - array[j]=current; - } +void insertion(int[]); + +int main() { + int arr_sort[MAX_SIZE], i; + + cout << "Simple C++ Insertion Sort Example - Array and Functions\n"; + cout << "\nEnter " << MAX_SIZE << " Elements for Sorting : " << endl; + for (i = 0; i < MAX_SIZE; i++) + cin>> arr_sort[i]; + + cout << "\nYour Data :"; + for (i = 0; i < MAX_SIZE; i++) { + cout << "\t" << arr_sort[i]; + } + + insertion(arr_sort); + getch(); } -// Main function to perform sorting - -int main(){ - int i; - int array_size; - cout<< "Enter the size of the array to be sorted: "; - cin>> array_size; - int array[array_size]; - cout<<"enter the elements of the array to be sorted: "; - for(i=0;i>array[i]; +void insertion(int fn_arr[]) { + int i, j, a, t; + for (i = 1; i < MAX_SIZE; i++) { + t = fn_arr[i]; + j = i - 1; + + while (j>= 0 && fn_arr[j]> t) { + fn_arr[j + 1] = fn_arr[j]; + j = j - 1; + } + fn_arr[j + 1] = t; + + cout << "\nIteration : " << i; + for (a = 0; a < MAX_SIZE; a++) { + cout << "\t" << fn_arr[a]; + } } - insertionSort(array,array_size); - cout<<"sorted array is:\n"; - for(i=0;i n (first lon)) + (cons (first lon) (insert n (rest lon))) + (cons n lon))])) diff --git a/Sorting/QuickSort.java b/Sorting/QuickSort.java new file mode 100644 index 00000000..d41459bc --- /dev/null +++ b/Sorting/QuickSort.java @@ -0,0 +1,73 @@ +// Iterative Quick Sort +// Java program for implementation of QuickSort +import java.util.*; + +class QuickSort +{ + /* This function takes last element as pivot, + places the pivot element at its correct + position in sorted array, and places all + smaller (smaller than pivot) to left of + pivot and all greater elements to right + of pivot */ + static int partition(int arr[], int low, int high) + { + int pivot = arr[high]; + int i = (low-1); // index of smaller element + for (int j=low; j<=high-1; j++) + { + // If current element is smaller than or + // equal to pivot + if (arr[j] <= pivot) + { + i++; + + // swap arr[i] and arr[j] + int temp = arr[i]; + arr[i] = arr[j]; + arr[j] = temp; + } + } + + // swap arr[i+1] and arr[high] (or pivot) + int temp = arr[i+1]; + arr[i+1] = arr[high]; + arr[high] = temp; + + return i+1; + } + + /* The main function that implements QuickSort() + arr[] --> Array to be sorted, + low --> Starting index, + high --> Ending index */ + static void qSort(int arr[], int low, int high) + { + if (low < high) + { + /* pi is partitioning index, arr[pi] is + now at right place */ + int pi = partition(arr, low, high); + + // Recursively sort elements before + // partition and after partition + qSort(arr, low, pi-1); + qSort(arr, pi+1, high); + } + } + + // Driver code + public static void main(String args[]) + { + + int n = 5; + int arr[] = {4, 2, 6, 9, 2}; + + qSort(arr, 0, n-1); + + for(int i =0;i + +using namespace std; + +int main() +{ + int array[] = {10, 9, 8, 7, 6, 5, 4, 3, 2, 1}; + + cout << "Before sort:" << endl; + for (int i = 0; i < 10; i++) + { + cout << array[i] << ", "; + } + cout << endl; + + for(int i = 0; i < 10; i++) + { + int small = array[i]; + int smallIndex = i; + + for (int j = i; j < 10; j++) + { + if(array[j] < small) + { + small = array[j]; + smallIndex = j; + } + } + + swap(array[i], array[smallIndex]); + } + + cout << "After sort: " << endl; + for (int i = 0; i < 10; i++) + { + cout << array[i] << ", "; + } + cout << endl; + + return 0; +} diff --git a/String Manipulation/Knuth-Morris-Pratt/C++/KMP.cpp b/String Manipulation/Knuth-Morris-Pratt/C++/KMP.cpp new file mode 100644 index 00000000..4a97fc63 --- /dev/null +++ b/String Manipulation/Knuth-Morris-Pratt/C++/KMP.cpp @@ -0,0 +1,62 @@ +#include +#include + +using namespace std; + +// Computes the prefix-suffix array. +vector ComputePrefixFunction(string pattern){ + int m = pattern.length(); + vector prefixArr(m); + prefixArr[0] = 0; + int k = 0; + + for(int i=1; i 0 && pattern[k] != pattern[i]){ + k = prefixArr[k]; + } + if(pattern[k] == pattern[i]){ + k++; + } + prefixArr[i] = k; + } + + return prefixArr; +} + +// Returns a vector of indicies where there is a pattern match. +vector KMP(string text, string pattern){ + int n = text.length(); + int m = pattern.length(); + vector prefixArr = ComputePrefixFunction(pattern); + int q = 0; + + vector results; + + for (int i = 0; i < n; ++i){ + while(q> 0 && pattern[q] != text[i]){ + q = prefixArr[q]; + } + if(pattern[q] == text[i]){ + q++; + } + if(q == m){ + results.push_back(i-m); + q = prefixArr[q]; + } + } + + return results; +} + +int main(){ + string example1 = "bacbababaabacabababaabaca"; + string pattern1 = "abaabaca"; + + vector result = KMP(example1, pattern1); + vector::iterator itt; + cout << "Matches at the following indicies..." << endl; + for(itt = result.begin(); itt != result.end(); ++itt){ + cout << *itt << endl; + } + return 0; +} \ No newline at end of file diff --git a/String Manipulation/Knuth-Morris-Pratt/README.md b/String Manipulation/Knuth-Morris-Pratt/README.md new file mode 100644 index 00000000..e0af2d6e --- /dev/null +++ b/String Manipulation/Knuth-Morris-Pratt/README.md @@ -0,0 +1,66 @@ +# Knuth-Morris-Pratt (KMP) Algorithm +KMP is a linear time string matching algorithm. The problem involves finding +all occurences where a string pattern matches a substring in a text. +The naive approach to string matching involves +looping over all indicies over a text string and finding the indicies +where the pattern p matches the substring starting at the index. + +s.t. pattern[0 ... m - 1] = text[idx ... idx + m - 1], where idx is some offset. + +The worst case of this approach is O(m*(n-m+1)), where m is |p| and n is |text|. + +The main drawback of the naive appraoch is that it handles overlaps +poorly. Since it will go deep into the second nested loop when checking +whether the substring and the pattern matches. When it hits a mismatch +it will start over from the next increment, thereby redoing some of its +comparisons. + +The KMP algorithm solves this problem by relying on some clever preprocessing, +thereby reaching a linear time performance. The clever preprocessing is simply +creating an array that contains information calculated by a prefix function, and this information describes how the pattern matches against shifts of itself. +We use this array to avoid the worst case situation of the naive approach by reusing previously performed comparisons. + +The prefix-function(i) is the longest prefix of p that is also a suffix of p[1 ... i]. The whole idea of finding these substrings in the +pattern which are both prefixes and suffixes, is that they determine from what index in the pattern and text we should start from next, hence +avoiding having to start all the way at the start index of the pattern and only one index further in the text each time we hit a +character miss match. + +KMP runs in O(n + m). Note, KMP is only necessary when there are many overlapping parts, since it is only in such +situations where the prefix-suffix array helps. However, the worst case linear time efficiency is guaranteed, meaning +the KMP algorithm is useful in general cases aswell. + +## Pseudocode +Where t is the text string and p is the pattern. + + KMP-Matcher(t, p): + n = len(t) + m = len(p) + prefix-arr = Compute-Prefix-Function(p) + q = 0 + for i = 0 to n: + while q> 0 and p[q] != t[i]: + q = prefix-arr[q] + if p[q] == t[i]: + q++ + if q == m: + patterns occurs at index i - m + q = prefix-arr[q] + + Compute-Prefix-Function(p) + m = len(p) + new arr[0 ... m-1] + arr[0] = 0 + k = 0 + for i = 1 to m: + while k> 0 and p[k] != p[i]: + k = arr[k] + if p[k] == p[i]: + k++ + arr[i] = k + + return arr + +CLRS[p. 1006]. + + +

AltStyle によって変換されたページ (->オリジナル) /