diff --git a/.DS_Store b/.DS_Store new file mode 100644 index 0000000..6b19b25 Binary files /dev/null and b/.DS_Store differ diff --git a/FCFS/fcfs.py b/Algorithm/FCFS/fcfs.py similarity index 100% rename from FCFS/fcfs.py rename to Algorithm/FCFS/fcfs.py diff --git a/FCFS/question.txt b/Algorithm/FCFS/question.txt similarity index 100% rename from FCFS/question.txt rename to Algorithm/FCFS/question.txt diff --git a/Floodfill/Problem_statement.txt b/Algorithm/Floodfill/Problem_statement.txt similarity index 97% rename from Floodfill/Problem_statement.txt rename to Algorithm/Floodfill/Problem_statement.txt index 9ddda57..f36d41a 100644 --- a/Floodfill/Problem_statement.txt +++ b/Algorithm/Floodfill/Problem_statement.txt @@ -1,28 +1,28 @@ -For those who dont like regular images, ASCII Maps Inc. has created maps that are fully printable ASCII characters. Each map is a rectangular grid of lowercase English letters, where each letter stands for various locations. In particular, w stands for water and the other 25 letters represent various different land locations. For this problem, we are interested in counting the number of bodies of water on a given ASCII map. A body of water is a maximal set of contiguous grid squares on the ASCII map where each square in the body of water shares a boundary with at least one other square in the body of water. Thus, for two grid squares to be part of the same body of water, one must be above, below, to the left, or to the right of the other grid square. -Input -The first line of input consists of two space separated integers, r (1=r=50) and c (1=c=50), the number of rows and columns, respectively for the input map. The next r lines will each contain c lowercase English letters, representing the corresponding row of the input map. - -Output -On a line by itself, output the number of bodies of water in the input map. - -Sample test case 1: - -Input: -5 6 -waaaww -wawawc -bbbbwc -wwwwww -dddddd - -Output: -3 - -Sample test case 2: -Input: -2 8 -wxwxwxwx -xwxwxwxw - -Output: -8 +For those who dont like regular images, ASCII Maps Inc. has created maps that are fully printable ASCII characters. Each map is a rectangular grid of lowercase English letters, where each letter stands for various locations. In particular, w stands for water and the other 25 letters represent various different land locations. For this problem, we are interested in counting the number of bodies of water on a given ASCII map. A body of water is a maximal set of contiguous grid squares on the ASCII map where each square in the body of water shares a boundary with at least one other square in the body of water. Thus, for two grid squares to be part of the same body of water, one must be above, below, to the left, or to the right of the other grid square. +Input +The first line of input consists of two space separated integers, r (1=r=50) and c (1=c=50), the number of rows and columns, respectively for the input map. The next r lines will each contain c lowercase English letters, representing the corresponding row of the input map. + +Output +On a line by itself, output the number of bodies of water in the input map. + +Sample test case 1: + +Input: +5 6 +waaaww +wawawc +bbbbwc +wwwwww +dddddd + +Output: +3 + +Sample test case 2: +Input: +2 8 +wxwxwxwx +xwxwxwxw + +Output: +8 diff --git a/Floodfill/solution.java b/Algorithm/Floodfill/solution.java similarity index 95% rename from Floodfill/solution.java rename to Algorithm/Floodfill/solution.java index 2974a5a..a043c94 100644 --- a/Floodfill/solution.java +++ b/Algorithm/Floodfill/solution.java @@ -1,53 +1,53 @@ -import java.util.Arrays; -import java.util.Scanner; - -public class water { -public static void main(String[] args){ -Scanner kb=new Scanner(System.in); -System.out.println("Enter the dimensions of the map:"); -int n=kb.nextInt(); -int m=kb.nextInt(); -System.out.println("Enter the map:"); -char[][] x=new char[n][m]; -for(int i=0;i=0&&r=0&&c=0&&r=0&&c= M or y < 0 or + y >= N or screen[x][y] != prevC or + screen[x][y] == newC): + return + + # Replace the color at (x, y) + screen[x][y] = newC + + # Recur for north, east, south and west + floodFillUtil(screen, x + 1, y, prevC, newC) + floodFillUtil(screen, x - 1, y, prevC, newC) + floodFillUtil(screen, x, y + 1, prevC, newC) + floodFillUtil(screen, x, y - 1, prevC, newC) + +# It mainly finds the previous color on (x, y) and +# calls floodFillUtil() +def floodFill(screen, x, y, newC): + prevC = screen[x][y] + floodFillUtil(screen, x, y, prevC, newC) + +# Driver Code +screen = [[1, 1, 1, 1, 1, 1, 1, 1], + [1, 1, 1, 1, 1, 1, 0, 0], + [1, 0, 0, 1, 1, 0, 1, 1], + [1, 2, 2, 2, 2, 0, 1, 0], + [1, 1, 1, 2, 2, 0, 1, 0], + [1, 1, 1, 2, 2, 2, 2, 0], + [1, 1, 1, 1, 1, 2, 1, 1], + [1, 1, 1, 1, 1, 2, 2, 1]] + +x = 4 +y = 4 +newC = 3 +floodFill(screen, x, y, newC) + +print ("Updated screen after call to floodFill:") +for i in range(M): + for j in range(N): + print(screen[i][j], end = ' ') + print() diff --git a/Josephus's Problem/josephus.java b/Algorithm/Josephus's Problem/josephus.java similarity index 100% rename from Josephus's Problem/josephus.java rename to Algorithm/Josephus's Problem/josephus.java diff --git a/Josephus's Problem/question.txt b/Algorithm/Josephus's Problem/question.txt similarity index 100% rename from Josephus's Problem/question.txt rename to Algorithm/Josephus's Problem/question.txt diff --git a/Kadane's Algorithm/kadane.c b/Algorithm/Kadane's Algorithm/kadane.c similarity index 95% rename from Kadane's Algorithm/kadane.c rename to Algorithm/Kadane's Algorithm/kadane.c index bf44ca1..4b19327 100644 --- a/Kadane's Algorithm/kadane.c +++ b/Algorithm/Kadane's Algorithm/kadane.c @@ -1,37 +1,37 @@ -#include -#include - -int maxSubarraySum(int a[], int l) { - int max = INT_MIN, max_here = 0; - - for (int i = 0; i < l; i++) { - max_here = max_here + a[i]; - if (max < max_here) max = max_here; - if (max_here < 0) max_here = 0; - } - - return max; -} - -// int maxSubarraySum(int a[], int l) { -// int max = a[0], max_here = a[0]; - -// for (int i = 0; i < l; i++) { -// if (max_here > 0) max_here += a[i]; -// else max_here = a[i]; -// if (max_here > max) max = max_here; -// } - -// return max; -// } - -int main(int argc, char *argv[]) { - int arr[] = {-2, -3, 4, -1, -2, 1, 5, -3}; - int l = sizeof(arr) / sizeof(int); - - int m = maxSubarraySum(arr, l); - - printf("%d is the max subarray sum\n", m); - - return 0; +#include +#include + +int maxSubarraySum(int a[], int l) { + int max = INT_MIN, max_here = 0; + + for (int i = 0; i < l; i++) { + max_here = max_here + a[i]; + if (max < max_here) max = max_here; + if (max_here < 0) max_here = 0; + } + + return max; +} + +// int maxSubarraySum(int a[], int l) { +// int max = a[0], max_here = a[0]; + +// for (int i = 0; i < l; i++) { +// if (max_here > 0) max_here += a[i]; +// else max_here = a[i]; +// if (max_here > max) max = max_here; +// } + +// return max; +// } + +int main(int argc, char *argv[]) { + int arr[] = {-2, -3, 4, -1, -2, 1, 5, -3}; + int l = sizeof(arr) / sizeof(int); + + int m = maxSubarraySum(arr, l); + + printf("%d is the max subarray sum\n", m); + + return 0; } \ No newline at end of file diff --git a/Algorithm/Kadane's Algorithm/kadane.cpp b/Algorithm/Kadane's Algorithm/kadane.cpp new file mode 100644 index 0000000..0101507 --- /dev/null +++ b/Algorithm/Kadane's Algorithm/kadane.cpp @@ -0,0 +1,27 @@ +#include +#include +using namespace std; + +int maxSubarraySum(vector a, int l) { + int max = INT_MIN, max_here = 0; + + for (int i = 0; i < l; i++) { + max_here = max_here + a[i]; + if (max < max_here) max = max_here; + if (max_here < 0) max_here = 0; + } + + return max; +} + + +int main() { + vector arr({-2, -3, 4, -1, -2, 1, 5, -3}); + int l = arr.size(); + + int m = maxSubarraySum(arr, l); + + cout< +using namespace std; + +template +class LinearList{ + private: + int MaxSize; + Item *element; // 1D dynamic array + int len; + public: + /* Default constructor. + * Should create an empty list that not contain any elements*/ + LinearList() + { + element=nullptr; + len=0; + }; + + /* This constructor should create a list containing MaxSize elements. You can intialize the elements with any values.*/ + LinearList(const int& MaxListSize) + { + MaxSize=MaxListSize; + element = new Item[MaxSize]; + len=0; + /*for(int i=0;ik;i--) + { + element[i]=element[i-1]; + } + element[k]=x; + len=len+1; + }; + + +}; + +int main() +{ + LinearList a(250); + int k,n,i,j,temp; + cout << "Enter number of children: "; + cin >> n; + cout << "Enter elimination rule: "; + cin >> i; + for(j=0;j +using namespace std; + +char board[30][30]; + +void printBoard(char arr[][30], int n) { + for (int r = 0; r < n; ++r) { + for (int c = 0; c < n; ++c) { + cout << arr[r][c] << " " ; + } + cout << endl; + } +} + +void initialiseBoard(int n) { + for (int r = 0; r < n; ++r) { + for (int c = 0; c < n; ++c) { + board[r][c] = 'X'; + } + } +} + +bool canPlace(char board[][30], int N, int x, int y) +{ + //check the row if aqueen already exists + for (int r = 0; r < N; ++r) + { + if (board[r][y] == 'Q') + return false; + } + + int rInc[] = { -1, +1, +1, -1}; + int cInc[] = { -1, +1, -1, +1}; + //check diagonal if queen already exists + for (int dir = 0; dir < 4; ++dir) + { + int rowAdd = rInc[dir]; + int colAdd = cInc[dir]; + int r = x + rowAdd; + int c = y + colAdd; + //check that r c is within the board + while (r >= 0 && r < N && c >= 0 && c < N) + { + if (board[r][c] == 'Q') + return false; + r = r + rowAdd; + c = c + colAdd; + } + } + return true; +} + +bool nqueen(int r, int n) +{ + if (r == n)//base case if all queens are placed + { + return true; + } + //for every column, use hit and trial by placing a queen in the each cell of curr Row + for (int c = 0; c < n; ++c) + { + int x = r; + int y = c; + //check if queen can be placed on board[i][c] + if (canPlace(board, n, x, y)==true) + { + board[x][y] = 'Q'; //place queen in each column + bool isSuccessful = nqueen(r + 1, n); //recursion to place rest of queens + if (isSuccessful == true) + return true; + board[x][y] = 'X'; //else unmark the cell or backtrack + } + } + return false; //if queen cannot be placed in any row in this column then return false +} + +int main() +{ + int n; + cin >> n; + + initialiseBoard(n);//initialse all the board with X + bool isSuccessful = nqueen(0, n); + + if (isSuccessful) printBoard(board, n); + else cout << "Sorry man! You need to have a larger board!\n"; + + return 0; +} diff --git a/Array/Biggest_Sum_5_Consecutives_Integers/Biggest_Sum_5_Consecutives_Integers b/Array/Biggest_Sum_5_Consecutives_Integers/Biggest_Sum_5_Consecutives_Integers new file mode 100644 index 0000000..b526a8c --- /dev/null +++ b/Array/Biggest_Sum_5_Consecutives_Integers/Biggest_Sum_5_Consecutives_Integers @@ -0,0 +1,19 @@ +What's the biggest sum you can get from adding 5 consecutives integers in a array? + +Example: + Array = [1, 3, -2, 4, -9, 1, 4, 7] + Possibles Sums: + 1 + 3 + (-2) + 4 + (-9) = -3 + 3 + (-2) + 4 + (-9) + 1 = -3 + (-2) + 4 + (-9) + 1 + 4 = -2 + 4 + (-9) + 1 + 4 + 7 = 7 + + So the biggest Sum is 7. + +What's the biggest sum of 5 consecutives integers of the array below? + +Array = [1, 3, -5, 8, -9, 13, -2, -3, 8, 4, 3, 6, 1, 2, -2, -4, 8, -4, 1, 8, 2, 1, 3, 1, 2, 3, + 7, 8, -9, 5, 4, 3, 2, 4, 1, 2, 6, 6, 7, -15, 9, 7, 8, 16, -10, 1, 2, 6, 6, 4, -5, 2, 2 + 3, 6, 7, 8, 1, 2, 3, 3, 4, 5, 6, 1, -5,7, -9, 10, 1, 3, 4, 8, 7, 6, 4, 1, 1, 2, 3, 1] + +PS: There may or may not have different sequences that has the same sum. diff --git a/Array/Biggest_Sum_5_Consecutives_Integers/solution.c b/Array/Biggest_Sum_5_Consecutives_Integers/solution.c new file mode 100644 index 0000000..4a395d4 --- /dev/null +++ b/Array/Biggest_Sum_5_Consecutives_Integers/solution.c @@ -0,0 +1,23 @@ +#include +#include + +int main(){ + int i; + int size = 81; //SIZE OF THE ARRAY + int sum; + int biggestSum; + int array[] = {1, 3, -5, 8, -9, 13, -2, -3, 8, 4, 3, 6, 1, 2, -2, -4, 8, -4, 1, 8, 2, 1, 3, 1, 2, 3, 7, 8, -9, 5, 4, 3, 2, 4, 1, 2, 6, 6, 7, -15, 9, 7, 8, 16, -10, 1, 2, 6, 6, 4, -5, 2, 2, 3, 6, 7, 8, 1, 2, 3, 3, 4, 5, 6, 1, -5, 7, -9, 10, 1, 3, 4, 8, 7, 6, 4, 1, 1, 2, 3, 1}; + + //FIRST SUM + sum = array[0] + array[1] + array[2] + array[3] + array[4]; + biggestSum = sum; + + //OTHER SUMS + for(i = 1; i < (size - 4); i++){ //THERE ARE (size - 4) POSSIBLE SUMS, BUT WE ALREADY MADE 1, SO i STARTS AT 1 + sum = sum - array[i - 1] + array[i + 4]; //REMOVE THE FIRST OF THE OLD SUM, AND ADD THE NEW INTEGER + if(sum > biggestSum){ + biggestSum = sum; + } + } + printf("biggestSum = %d\n", biggestSum); //PRINT THE RESULT +} \ No newline at end of file diff --git a/Array/Circle Coloring/1408A.cpp b/Array/Circle Coloring/1408A.cpp new file mode 100644 index 0000000..d526a08 --- /dev/null +++ b/Array/Circle Coloring/1408A.cpp @@ -0,0 +1,52 @@ +#include + +using namespace std; + +int main() +{ + while() + { + int n; + cin>>n; + std::vector a(n), b(n), c(n), ans; + + for(int i=0; i>a[i]; + } + for(int i=0; i>b[i]; + } + for(int i=0; i>c[i]; + } + ans.push_back(a[0]); + + for(int i=1; i + +using namespace std; + +// Complete the hourglassSum function below. +int hourglassSum(vector> arr) { + + int sum[16]={0}; + int a[36]; + static int r=0,x=0; + + for(int i=0;i<6;i++){ + for(int j=0;j<6;j++,r++){ + a[r]=arr[i][j]; + } + } + + + for(int i=0;i<22;i++,x++){ + sum[x]=a[i]+a[i+1]+a[i+2]+a[i+7]+a[i+12]+a[i+13]+a[i+14]; + if(i==3 || i==9 || i==15) + i+=2; + cout << sum[x] << " "; + } + + int large = sum[0]; + + for(int i=1;i<16;i++){ + if(large> arr(6); + for (int i = 0; i < 6; i++) { + arr[i].resize(6); + + for (int j = 0; j < 6; j++) { + cin >> arr[i][j]; + } + + cin.ignore(numeric_limits::max(), '\n'); + } + + int result = hourglassSum(arr); + + fout << result << "\n"; + + fout.close(); + + return 0; +} \ No newline at end of file diff --git a/Lily's Homework/Question.txt b/Array/Lily's Homework/Question.txt similarity index 98% rename from Lily's Homework/Question.txt rename to Array/Lily's Homework/Question.txt index 502c95c..39f207f 100644 --- a/Lily's Homework/Question.txt +++ b/Array/Lily's Homework/Question.txt @@ -1,11 +1,11 @@ -Consider an array of distinct integers, arr = [a[0], a[1], ..., a[n-1]]. George can swap any two elements of the array any number of times. An array is beautiful if the sum of |arr[i] - arr[i-1]|among 0< i < n is minimal. - -Given the array , determine and return the minimum number of swaps that should be performed in order to make the array beautiful. - -For example, arr = [7, 15, 12, 3]. One minimal array is [3, 7, 12, 15]. To get there, George performed the following swaps: - -Swap Result - [7, 15, 12, 3] -3 7 [3, 15, 12, 7] -7 15 [3, 7, 12, 15] +Consider an array of distinct integers, arr = [a[0], a[1], ..., a[n-1]]. George can swap any two elements of the array any number of times. An array is beautiful if the sum of |arr[i] - arr[i-1]|among 0< i < n is minimal. + +Given the array , determine and return the minimum number of swaps that should be performed in order to make the array beautiful. + +For example, arr = [7, 15, 12, 3]. One minimal array is [3, 7, 12, 15]. To get there, George performed the following swaps: + +Swap Result + [7, 15, 12, 3] +3 7 [3, 15, 12, 7] +7 15 [3, 7, 12, 15] It took 2 swaps to make the array beautiful. This is minimal among the choice of beautiful arrays possible. \ No newline at end of file diff --git a/Lily's Homework/solution.py b/Array/Lily's Homework/solution.py similarity index 96% rename from Lily's Homework/solution.py rename to Array/Lily's Homework/solution.py index 8b29419..7783d49 100644 --- a/Lily's Homework/solution.py +++ b/Array/Lily's Homework/solution.py @@ -1,26 +1,26 @@ -def lilysHomework(arr): - m = {} - for i in range(len(arr)): - m[arr[i]] = i - sorted_arr = sorted(arr) - res = 0 - for i in range(len(arr)): - if(arr[i] != sorted_arr[i]): - res += 1 - x = m[sorted_arr[i]] - m[ arr[i] ] = m[ sorted_arr[i]] - arr[i],arr[x] = sorted_arr[i],arr[i] - return res - -if __name__ == '__main__': - fptr = open(os.environ['OUTPUT_PATH'], 'w') - - n = int(input()) - - arr = list(map(int, input().rstrip().split())) - - result = min(lilysHomework(list(arr)), lilysHomework(list(arr[::-1]))) - - fptr.write(str(result) + '\n') - - fptr.close() +def lilysHomework(arr): + m = {} + for i in range(len(arr)): + m[arr[i]] = i + sorted_arr = sorted(arr) + res = 0 + for i in range(len(arr)): + if(arr[i] != sorted_arr[i]): + res += 1 + x = m[sorted_arr[i]] + m[ arr[i] ] = m[ sorted_arr[i]] + arr[i],arr[x] = sorted_arr[i],arr[i] + return res + +if __name__ == '__main__': + fptr = open(os.environ['OUTPUT_PATH'], 'w') + + n = int(input()) + + arr = list(map(int, input().rstrip().split())) + + result = min(lilysHomework(list(arr)), lilysHomework(list(arr[::-1]))) + + fptr.write(str(result) + '\n') + + fptr.close() diff --git a/Array/Mislove Has Lost an Array/Question.txt b/Array/Mislove Has Lost an Array/Question.txt new file mode 100644 index 0000000..23182ac --- /dev/null +++ b/Array/Mislove Has Lost an Array/Question.txt @@ -0,0 +1,17 @@ +Mislove had an array a1, a2, ⋯, an of n positive integers, but he has lost it. He only remembers the following facts about it: + +1)The number of different numbers in the array is not less than l and is not greater than r. +2)For each array's element ai either ai=1 or ai is even and there is a number ai/2 in the array. + +For example, if n=5, l=2, r=3 then an array could be [1,2,2,4,4] or [1,1,1,1,2]; but it couldn't be [1,2,2,4,8] because this array contains 4 different numbers; it couldn't be [1,2,2,3,3] because 3 is odd and isn't equal to 1; and it couldn't be [1,1,2,2,16] because there is a number 16 in the array but there isn't a number 16/2=8. + +According to these facts, he is asking you to count the minimal and the maximal possible sums of all elements in an array. + +Input-1 +4 2 2 +Output +5 7 +Input-2 +5 1 5 +Output +5 31 diff --git a/Array/Mislove Has Lost an Array/Solution.cpp b/Array/Mislove Has Lost an Array/Solution.cpp new file mode 100644 index 0000000..841440f --- /dev/null +++ b/Array/Mislove Has Lost an Array/Solution.cpp @@ -0,0 +1,26 @@ +#include +using namespace std; +int main() +{ + long long int i,mini=1,mine=0,maxi=1,maxo=0,n,s,e; + cin>>n>>s>>e; + + for(i=1;i<=s-1;i++) + { + mini=2*mini; + mine+=mini; + } +mine+=n-s+1; + +for(i=1;i<=e-1;i++) +{ + maxi=2*maxi; + maxo+=maxi; +} +maxo+=1; + + +maxo+=(n-e)*(maxi); +cout< +#include +#include + +int main() +{ + int t; + scanf("%d",&t); + while(t--){ + char str[100]; + scanf("%s",str); + int i; + int *arr = (int*)calloc(26,sizeof(int)); + for(i=0;imax){ + max = arr[i]; + c=i; + } + } + printf("%d %c\n",max,c+97); +} + return 0; +} diff --git a/Array/Philosophers_Stone/question.txt b/Array/Philosophers_Stone/question.txt new file mode 100644 index 0000000..f2474d3 --- /dev/null +++ b/Array/Philosophers_Stone/question.txt @@ -0,0 +1,30 @@ + + +One of the secret chambers in Hogwarts is full of philosopher’s stones. The floor of the chamber is covered by h × w square tiles, where there are h rows of tiles from front (first row) to back (last row) and w columns of tiles from left to right. Each tile has 1 to 100 stones on it. Harry has to grab as many philosopher’s stones as possible, subject to the following restrictions: + + He starts by choosing any tile in the first row, and collects the philosopher’s stones on that tile. Then, he moves to a tile in the next row, collects the philosopher’s stones on the tile, and so on until he reaches the last row. + When he moves from one tile to a tile in the next row, he can only move to the tile just below it or diagonally to the left or right. + +Given the values of h and w, and the number of philosopher’s stones on each tile, write a program to compute the maximum possible number of philosopher’s stones Harry can grab in one single trip from the first row to the last row. +Input + +The first line consists of a single integer T, the number of test cases. In each of the test cases, the first line has two integers. The first integer h (1 <= h <= 100) is the number of rows of tiles on the floor. The second integer w (1 <= w <= 100) is the number of columns of tiles on the floor. Next, there are h lines of inputs. The i-th line of these, specifies the number of philosopher’s stones in each tile of the i-th row from the front. Each line has w integers, where each integer m (0 <= m <= 100) is the number of philosopher’s stones on that tile. The integers are separated by a space character. +Output + +The output should consist of T lines, (1 <= T <= 100), one for each test case. Each line consists of a single integer, which is the maximum possible number of philosopher’s stones Harry can grab, in one single trip from the first row to the last row for the corresponding test case. +Example + +Input: +1 +6 5 +3 1 7 4 2 +2 1 3 1 1 +1 2 2 1 8 +2 2 1 5 3 +2 1 4 4 4 +5 2 7 5 1 + +Output: +32 + +//7+1+8+5+4+7=32 diff --git a/Array/Philosophers_Stone/solution.cpp b/Array/Philosophers_Stone/solution.cpp new file mode 100644 index 0000000..f3cc8e7 --- /dev/null +++ b/Array/Philosophers_Stone/solution.cpp @@ -0,0 +1,29 @@ +#include +using namespace std; +int main(void) +{ + int t; + cin>>t; + while(t--) + { + int r,c; + cin>>r>>c; + int arr[r][c+2]={0}; + arr[0][c+1]=0; + + for(int i=0;i>arr[i][j]; + + for(int i=r-2;i>=0;i--) + for(int j=1;j<=c;j++) + arr[i][j]+=max((arr[i+1][j-1]),max(arr[i+1][j],arr[i+1][j+1])); + + int max = INT_MIN; + for(int i=1;i<=c;i++) + if(arr[0][i]>max) + max = arr[0][i]; + + cout< +using namespace std; + +int main(){ + int t; + cin>>t; + while(t--){ + int n; + cin>>n;int a[n]; + + for(int i=0;i>a[i]; + } + + int j=1;int good =1;int cnt=0;int t=0; + + for(int i=1;i=6)t++; + for(j=i-1;j>=t;j--){ + + if(a[j]>a[i]){ + cnt=1;} + + else { + cnt=0; + break;} + + } + + if(cnt==1) + good++; + + } + + cout< +using namespace std; +int main() +{ + int t,a,i,j,c,e,g,x,y; + cin>>t; + while(t>0) + { x=0; + y=0; + cin>>a; + int b[a]; + for( i=0;i>b[i]; + + cin>>c; + int d[c]; + for( i=0; i>d[i]; + + cin>>e; + int f[e]; + for(i=0;i>f[i]; + + cin>>g; + int h[g]; + for(i=0;i>h[i]; + + for(i=0;i +using namespace std; + +typedef long long int ll; + + +int main() +{ + ios::sync_with_stdio(false); + cin.tie(0); + cout.tie(0); + + ll x11,x12,y11,y12; + ll x21,x22,y21,y22; + ll x31,x32,y31,y32; + + ll area = 0; + + cin>>x11>>y11>>x12>>y12; + cin>>x21>>y21>>x22>>y22; + cin>>x31>>y31>>x32>>y32; + + area = abs(x11-x12)*abs(y11-y12); + x21 = max(x11,x21); + y21 = max(y11,y21); + x22 = min(x12,x22); + y22 = min(y12,y22); + x31 = max(x11,x31); + y31 = max(y11,y31); + x32 = min(x12,x32); + y32 = min(y12,y32); + ll a1,a2,b1,b2; + if(x21 < x22 && y21 < y22) area -= abs(x21-x22)*abs(y21-y22); + if(x31 < x32 && y31 < y32) area -= abs(x31-x32)*abs(y31-y32); + if((x21x31) || (x21x32)) + { + if((y21 < y31 && y22 > y31) || (y21 < y32 && y22 > y32)) + { + ll narea = 0; + + } + } + + a1 = max(x21,x31); + b1 = max(y21,y31); + a2 = min(x22,x32); + b2 = min(y22,y32); + + if(a1 < a2 && b1 < b2) area += abs(a2-a1)*abs(b2-b1); + + if(area > 0) cout<<"YES\n"; + else cout<<"NO\n"; + + return 0; +} \ No newline at end of file diff --git a/Array/triplet_problem/question.txt b/Array/triplet_problem/question.txt new file mode 100644 index 0000000..b1417a8 --- /dev/null +++ b/Array/triplet_problem/question.txt @@ -0,0 +1 @@ +Find a triplet such that sum of two equals to third element in an array. diff --git a/Array/triplet_problem/solution.c b/Array/triplet_problem/solution.c new file mode 100644 index 0000000..69ac10c --- /dev/null +++ b/Array/triplet_problem/solution.c @@ -0,0 +1,48 @@ +#include + +void sort(int a[],int); +void findtriplet(int a[],int n) +{ + sort(a,n); + for(int k=n-1;k>=0;k--) + { + int i=0,j=k-1; + while(i (a[i]+a[j])) + i++; + else + j--; + } + } + printf("No such triplet exists\n"); +} + +void sort(int a[],int n) +{ + for(int i=0;i a[j+1]) + { + int t; + t = a[j]; + a[j] = a[j+1]; + a[j+1] = t; + } + } + } +} + +int main() +{ + int a[9] = {5,32,1,7,10,50,15,21,2}; + findtriplet(a,9); + return 0; +} diff --git a/Backtracking/Generate_parenthesis/Generate_Parenthesis.cpp b/Backtracking/Generate_parenthesis/Generate_Parenthesis.cpp new file mode 100644 index 0000000..0b6a580 --- /dev/null +++ b/Backtracking/Generate_parenthesis/Generate_Parenthesis.cpp @@ -0,0 +1,31 @@ +#include +using namespace std; +void Generate_Parenthesis(int open, int close, vector &ans, string s) +{ + if (close == 0) + { + ans.push_back(s); + return; + } + if (open) + { + string temp = s; + temp += '('; + Generate_Parenthesis(open - 1, close, ans, temp); + } + if (close > open) + { + string temp = s; + temp += ')'; + Generate_Parenthesis(open, close - 1, ans, temp); + } +} +int main() +{ + int n; + cin >> n; + vector ans; + Generate_Parenthesis(n, n, ans, ""); + for (int i = 0; i < ans.size(); i++) + cout << ans[i] << endl; +} \ No newline at end of file diff --git a/Backtracking/Generate_parenthesis/Question.txt b/Backtracking/Generate_parenthesis/Question.txt new file mode 100644 index 0000000..9012c1d --- /dev/null +++ b/Backtracking/Generate_parenthesis/Question.txt @@ -0,0 +1,7 @@ +Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses. + +Sample Input +n = 3 + +Sample Output +["((()))","(()())","(())()","()(())","()()()"] \ No newline at end of file diff --git a/Backtracking/SudokuSolver/Question.txt b/Backtracking/SudokuSolver/Question.txt new file mode 100644 index 0000000..eadd651 --- /dev/null +++ b/Backtracking/SudokuSolver/Question.txt @@ -0,0 +1,20 @@ +Given a partially filled NxN 2D array, the goal is to assign digits (from 1 to 9) +to the empty cells (cells assigned O value) so that every row, column,and subgrid +of size 3×3 contains exactly one instance of the digits from 1 to 9. We provide the +value of N and a partially filled sudoku as input. + +Sample Input: +4 +3 4 1 0 0 2 0 0 0 0 2 0 0 1 4 3 + +Sample Output: +============== +3 4 1 0 +0 2 0 0 +0 0 2 0 +0 1 4 3 +============== +3 4 1 2 +1 2 3 4 +4 3 2 1 +2 1 4 3 diff --git a/Backtracking/SudokuSolver/sudokuSolver.cpp b/Backtracking/SudokuSolver/sudokuSolver.cpp new file mode 100644 index 0000000..5013019 --- /dev/null +++ b/Backtracking/SudokuSolver/sudokuSolver.cpp @@ -0,0 +1,100 @@ +#include +#include +using namespace std; + +void print2D(int arr[][20], int M, int N) { + for (int i = 0; i < M; ++i) { + for (int j = 0; j < N; ++j) { + cout << arr[i][j] << " "; + } + cout << endl; + } +} + +bool myfixed[20][20] = {}; + +void input2D_soduku(int arr[][20], int M, int N) +{ + for (int i = 0; i < M; ++i) + { + for (int j = 0; j < N; ++j) + { + cin >> arr[i][j]; + if (arr[i][j] != 0) myfixed[i][j] = true; //so that our entry does not change + } + } +} + +bool canPlace(int board[][20], int N, int x, int y, int num) +{ + //check along row && col + for (int i = 0; i < N; ++i) + { + if (board[x][i] == num) return false; //check along row + if (board[i][y] == num) return false; //check along col + } + + //check in the box + int rootN = sqrt(N); + int boxRow = x / rootN; + int boxCol = y / rootN; + int startRow = boxRow * rootN; + int startCol = boxCol * rootN; + + for (int r = startRow; r < startRow + rootN; ++r) + { + for (int c = startCol; c < startCol + rootN; ++c) + { + if (board[r][c] == num) return false; + } + } + + return true; +} + + +bool solveSudoku(int board[][20], int N, int x, int y) +{ + if (x == N && y == 0) return true; //we have reached row 4 ---->sudoku over + + if (y == N) return solveSudoku(board, N, x + 1, 0);//stop y to go to column4-->goto nxt row + + if (myfixed[x][y]) return solveSudoku(board, N, x , y + 1); + + for (int num = 1; num <= N; ++num) + { + if (canPlace(board, N, x, y, num) == true) + { + board[x][y] = num; + bool isSuccessful = solveSudoku(board, N, x , y + 1); //recursion for nxt columns + if (isSuccessful) return true; + else board[x][y] = 0; + } + } + return false; +} + +int main() +{ + int board[20][20] = {}; + + int N; + cin >> N; + input2D_soduku(board, N, N); + for(int i=0;i>board[i][j]; + } + } + cout << "==============\n"; + + print2D(board, N, N); + + cout << "==============\n"; + + solveSudoku(board, N, 0, 0); + + print2D(board, N, N); + +} + diff --git a/Armstrong No/armstrongnum.c b/Basic Math/Armstrong No/armstrongnum.c similarity index 100% rename from Armstrong No/armstrongnum.c rename to Basic Math/Armstrong No/armstrongnum.c diff --git a/Average/Average-Question.txt b/Basic Math/Average/Average-Question.txt similarity index 100% rename from Average/Average-Question.txt rename to Basic Math/Average/Average-Question.txt diff --git a/Average/Solution.cpp b/Basic Math/Average/Solution.cpp similarity index 100% rename from Average/Solution.cpp rename to Basic Math/Average/Solution.cpp diff --git a/Basic Math/Counting-Change-Combinations/counting.txt b/Basic Math/Counting-Change-Combinations/counting.txt new file mode 100644 index 0000000..e7aba7c --- /dev/null +++ b/Basic Math/Counting-Change-Combinations/counting.txt @@ -0,0 +1,13 @@ +Write a function that counts how many different ways you can make change for an amount of money, given an array of coin denominations. For example, there are 3 ways to give change for 4 if you have coins with denomination 1 and 2: + +1+1+1+1, 1+1+2, 2+2. +The order of coins does not matter: + +1+1+2 == 2+1+1 +Also, assume that you have an infinite amount of coins. + +Your function should take an amount to change and an array of unique denominations for the coins: + + countChange(4, [1,2]) // => 3 + countChange(10, [5,2,3]) // => 4 + countChange(11, [5,7]) // => 0 \ No newline at end of file diff --git a/Basic Math/Counting-Change-Combinations/solution.js b/Basic Math/Counting-Change-Combinations/solution.js new file mode 100644 index 0000000..fcb7e85 --- /dev/null +++ b/Basic Math/Counting-Change-Combinations/solution.js @@ -0,0 +1,24 @@ +let countChange = function(money, coins) { + if (coins.length === 0) { + return 0; + } + + coins = coins.slice(0).sort(); + let result = 0, + largestCoin = coins.pop(), + maxCount = 0; + let maxRemain = money % largestCoin; + + if (maxRemain === 0) { + result++; + maxCount = money / largestCoin - 1; + } else { + maxCount = (money - maxRemain) / largestCoin; + } + + for (let i = maxCount; i >= 0; i--) { + result += countChange(money - largestCoin * i, coins); + } + + return result; +} \ No newline at end of file diff --git a/Divisibility_Check/Question.txt b/Basic Math/Divisibility_Check/Question.txt similarity index 100% rename from Divisibility_Check/Question.txt rename to Basic Math/Divisibility_Check/Question.txt diff --git a/Divisibility_Check/Solution.cpp b/Basic Math/Divisibility_Check/Solution.cpp similarity index 100% rename from Divisibility_Check/Solution.cpp rename to Basic Math/Divisibility_Check/Solution.cpp diff --git a/Divisible Sum Pairs/Problem Description.txt b/Basic Math/Divisible Sum Pairs/Problem Description.txt similarity index 98% rename from Divisible Sum Pairs/Problem Description.txt rename to Basic Math/Divisible Sum Pairs/Problem Description.txt index 7525f0e..1ffa981 100644 --- a/Divisible Sum Pairs/Problem Description.txt +++ b/Basic Math/Divisible Sum Pairs/Problem Description.txt @@ -1,2 +1,2 @@ -You are given an array of n integers, ar = [ar[0], ar[1], ... , ar[n-1]], and a positive integer k. Find and print the number of -(i,j) pairs where i < j and ar[i]+ar[j] is divisible by k. +You are given an array of n integers, ar = [ar[0], ar[1], ... , ar[n-1]], and a positive integer k. Find and print the number of +(i,j) pairs where i < j and ar[i]+ar[j] is divisible by k. diff --git a/Divisible Sum Pairs/solution.js b/Basic Math/Divisible Sum Pairs/solution.js similarity index 95% rename from Divisible Sum Pairs/solution.js rename to Basic Math/Divisible Sum Pairs/solution.js index d75bca6..7c65521 100644 --- a/Divisible Sum Pairs/solution.js +++ b/Basic Math/Divisible Sum Pairs/solution.js @@ -1,12 +1,12 @@ -function divisibleSumPairs(n, k, ar) { - let count =0; - for(let i=0; i +void main() +{ + int i; + for(i=1;i<=100;i++) + { + if(i%3!=0 && i%5!=0) printf("%d\n", i); + if(i%3 == 0 && i%5!=0)printf("Fizz\n"); + if(i%5 == 0 && i%3!=0)printf("Buzz\n"); + if(i%5 == 0 && i%3==0)printf("FizzBuzz\n"); + } +} diff --git a/Basic Math/Fizz Buzz/fizzbuzz.cpp b/Basic Math/Fizz Buzz/fizzbuzz.cpp new file mode 100644 index 0000000..4d6c904 --- /dev/null +++ b/Basic Math/Fizz Buzz/fizzbuzz.cpp @@ -0,0 +1,16 @@ +#include +using namespace std; +int main() +{ + for(int i=1;i<=100;i++){ + if((i%3 == 0) && (i%5==0)) + cout<<"FizzBuzz\n"; + else if(i%3 == 0) + cout<<"Fizz\n"; + else if(i%5 == 0) + cout<<"Buzz\n"; + else + cout< N. + PERFORM Y-PARA VARYING I FROM B BY 1 UNTIL C = N. + MOVE K TO P. + DISPLAY "THE LCM IS " P. + + DISPLAY "Enter Number of Head". + ACCEPT num. + DISPLAY "Enter number of legs". + ACCEPT num2. + PERFORM headleg-PARA. + if count1 equals 2 DISPLAY "NONE" + STOP RUN. + + X-PARA. + ACCEPT A(I). + IF (B < A(I)) + MOVE A(I) TO B. + + Y-PARA. + MOVE 0 TO C. + COMPUTE D = D + 1. + PERFORM Z-PARA VARYING J FROM 1 BY 1 UNTIL J > N. + + Z-PARA. + COMPUTE K = B * D. + DIVIDE K BY A(J) GIVING Q REMAINDER R. + IF (R = 0) + COMPUTE C = C + 1. + + headleg-PARA. + PERFORM VARYING chickens FROM 0 BY 1 UNTIL chickens >= num + COMPUTE dogs = num - chickens + COMPUTE result =2 * chickens + COMPUTE result1 =4 * dogs + COMPUTE result2 = result + result1 + IF result2 EQUALS num2 + DISPLAY "[", chickens,",",dogs,"]" + SET count1 to 1 + ELSE IF count1 equals to 1 set count1 to 1 + else set count1 to 2 + END-IF + END-PERFORM. diff --git a/Basic Math/Least_Common_Multiple/Problem.txt b/Basic Math/Least_Common_Multiple/Problem.txt new file mode 100644 index 0000000..83e009c --- /dev/null +++ b/Basic Math/Least_Common_Multiple/Problem.txt @@ -0,0 +1,6 @@ +## Problem: + +The LCM of two integers n1 and n2 is the smallest positive integer that is perfectly +divisible by both n1 and n2 (without a remainder). For example: the LCM of 72 and 120 is 360. + +write a program written in COBOL that will compute the LCM of 2 numbers diff --git a/Basic Math/Number to Words/number_to_words.CPP b/Basic Math/Number to Words/number_to_words.CPP new file mode 100644 index 0000000..94e3047 --- /dev/null +++ b/Basic Math/Number to Words/number_to_words.CPP @@ -0,0 +1,62 @@ +//Converts any number between 0-9999 (inclusive) to words +//till 4 digits only + +#include +#include + +void words(int n, int c, int r) +{ + if(n==0 && c==1) + { + cout<<"Zero"<=20 || n==10) + { + cout<<" "<=14) + cout<<" "<>n; + int n1=n; + int count=0, rev=0; + while(n1!=0) + { + rev=rev*10+(n1%10); + count++; + n1=n1/10; + } + words(n,count,rev); + getch(); +} \ No newline at end of file diff --git a/Basic Math/Number to Words/problem_definition.txt b/Basic Math/Number to Words/problem_definition.txt new file mode 100644 index 0000000..0e39580 --- /dev/null +++ b/Basic Math/Number to Words/problem_definition.txt @@ -0,0 +1,4 @@ +Write code to convert a given number into words. +For example, +if “1234” is given as input +output should be “one thousand two hundred thirty four”. \ No newline at end of file diff --git a/Basic Math/Octal Decimal Calculator/Octal Decimal Calculator.txt b/Basic Math/Octal Decimal Calculator/Octal Decimal Calculator.txt new file mode 100644 index 0000000..0ff00e0 --- /dev/null +++ b/Basic Math/Octal Decimal Calculator/Octal Decimal Calculator.txt @@ -0,0 +1,9 @@ +Given an octal number it is required to convert to decimal and print it on the console + +Example: + +The octal number 567 is entered. + +The system calculates the equivalent number in decimal that is 375 and prints it on the console + +The decimal number for octal 567 is: 357 \ No newline at end of file diff --git a/Basic Math/Octal Decimal Calculator/OctalDecimalCalculator.java b/Basic Math/Octal Decimal Calculator/OctalDecimalCalculator.java new file mode 100644 index 0000000..dac72a3 --- /dev/null +++ b/Basic Math/Octal Decimal Calculator/OctalDecimalCalculator.java @@ -0,0 +1,43 @@ +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; + +public class OctalDecimalCalculator { + + private static int BASE_8 = 8; + private static final BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + private static final String RESULT_TEMPLATE = "The decimal number for octal %s is: %s"; + + public static void main(String[] args){ + + System.out.println("Please input octal number to convert"); + try { + String octal = br.readLine(); + String decimal = convertOctalToDecimal(Integer.parseInt(octal)); + + System.out.println(String.format(RESULT_TEMPLATE, octal, decimal)); + } catch (IOException e) { + e.printStackTrace(); + } + + } + + public static String convertOctalToDecimal(int octal){ + int result = 0; + String tmp = String.valueOf(octal); + int count = 0; + int multiple; + String caracter; + for (int i = tmp.length(); i > 0; i--) { + caracter = tmp.substring(i-1, i); + multiple = (int) Math.pow(BASE_8, count); + int value = (Integer.parseInt(caracter) * multiple); + count = count + 1; + result += value; + + } + + return String.valueOf(result); + } + +} diff --git a/Odd or Even Game/.idea/Odd or Even Game.iml b/Basic Math/Odd or Even Game/.idea/Odd or Even Game.iml similarity index 100% rename from Odd or Even Game/.idea/Odd or Even Game.iml rename to Basic Math/Odd or Even Game/.idea/Odd or Even Game.iml diff --git a/Odd or Even Game/.idea/misc.xml b/Basic Math/Odd or Even Game/.idea/misc.xml similarity index 100% rename from Odd or Even Game/.idea/misc.xml rename to Basic Math/Odd or Even Game/.idea/misc.xml diff --git a/Odd or Even Game/.idea/modules.xml b/Basic Math/Odd or Even Game/.idea/modules.xml similarity index 100% rename from Odd or Even Game/.idea/modules.xml rename to Basic Math/Odd or Even Game/.idea/modules.xml diff --git a/Odd or Even Game/.idea/vcs.xml b/Basic Math/Odd or Even Game/.idea/vcs.xml similarity index 100% rename from Odd or Even Game/.idea/vcs.xml rename to Basic Math/Odd or Even Game/.idea/vcs.xml diff --git a/Odd or Even Game/.idea/workspace.xml b/Basic Math/Odd or Even Game/.idea/workspace.xml similarity index 100% rename from Odd or Even Game/.idea/workspace.xml rename to Basic Math/Odd or Even Game/.idea/workspace.xml diff --git a/Odd or Even Game/OddEvenGame.txt b/Basic Math/Odd or Even Game/OddEvenGame.txt similarity index 100% rename from Odd or Even Game/OddEvenGame.txt rename to Basic Math/Odd or Even Game/OddEvenGame.txt diff --git a/Odd or Even Game/oddEvenGame.py b/Basic Math/Odd or Even Game/oddEvenGame.py similarity index 100% rename from Odd or Even Game/oddEvenGame.py rename to Basic Math/Odd or Even Game/oddEvenGame.py diff --git a/Basic Math/PROXY/question.txt b/Basic Math/PROXY/question.txt new file mode 100644 index 0000000..aeecadd --- /dev/null +++ b/Basic Math/PROXY/question.txt @@ -0,0 +1,33 @@ +Chef is a brilliant university student that does not attend lectures because he believes that they are boring and coding is life! However, his university follows certain rules and regulations, and a student may only take an exam for a course if he has attended at least 75% of lectures for this course. + +Since you are Chef's best friend, you want to help him reach the attendance he needs to take exams. Unfortunately, Chef is still focused on his code and refuses to attend more lectures, so the only option is to have some of his friends mark him as present by proxy. This trick is well-known in the university, but only few have the talent to pull it off. + +In a certain course, there is exactly one lesson per day over the course of D days (numbered 1 through D). You are given a string S with length D describing the lessons Chef attended — for each valid i, the i-th character of this string is either 'A' if Chef was absent on day i or 'P' if Chef was actually present on day i. + +For each day d when Chef is absent, one of Chef's friends can mark him as present by proxy on this day only if he was present (if he was really present, not just marked as present) on at least one of the previous two days, i.e. days d−1 and d−2, and on at least one of the following two days, i.e. days d+1 and d+2. However, it is impossible to mark him as present by proxy on the first two days and the last two days. + +Find the minimum number of times Chef has to be marked as present by proxy so that his attendance becomes at least 75% (0.75). Chef's attendance is number of days when he was marked as present, either by proxy or by actually being present, divided by D. + +Input +The first line of the input contains a single integer T denoting the number of test cases. The description of T test cases follows. +The first line of each test case contains a single integer D. +The second line contains a single string S with length D. + +Output +For each test case, print a single line containing one integer — the minimum number of times Chef needs to be marked as present by proxy, or −1 if it is impossible to make Chef achieve 75% attendance. + +Constraints +1≤T≤200 +1≤D≤1,000 +S contains only characters 'A' and 'P' +Subtasks +Subtask #1 (100 points): original constraints + +Example Input +1 +9 +PAAPPAPPP +Example Output +1 +Explanation +Example case 1: With a proxy on the third day, the attendance string is "PAPPPAPPP". Now, Chef's attendance is at least 75%, so the minimum number of times Chef needs to be marked as present by proxy is 1. \ No newline at end of file diff --git a/Basic Math/PROXY/solution.cpp b/Basic Math/PROXY/solution.cpp new file mode 100644 index 0000000..9eb5c92 --- /dev/null +++ b/Basic Math/PROXY/solution.cpp @@ -0,0 +1,49 @@ +#include +using namespace std; + +float att(int act,int cnt,int d){ + float t = (double)cnt/d; + if(t>=0.75) + cout<>t; + while(t--){ + int d,cnt=0,i=0,flag=0; + cin>>d; + char s[d]; + cin >> s; + + + //count of present + for(i=0;i=0.75){ + flag=1; + break; + } + + } + } + if(flag==0) + cout<<-1< +using namespace std; +int main() +{ + int t,n,m,s; + cin>>t; + while(t>0) + { + cin>>n>>m>>s; + s=s+m%n -1; + if(m%n==0) + s=s+n; + if(s>n) + s=s%n; + cout< - -using namespace std; - - -// Complete the decentNumber function below. - -void decent(int digits) -{ - int flag=0; - - if(digits==4 || digits==7 || digits<3) - flag=0; - else if(digits==5) - { - flag=1; - cout<<"33333\n"; - - } - else if(digits%3 ==0) - { - flag=1; - //(no. of times, what needs to be printed) - cout<=8) - { - - int remain3,remain5,temp; - - temp=digits%3; - flag=1; - if(temp==1) - { - remain5=digits-10; - remain3=10; - } - else if(temp==2) - { - remain5=digits-5; - remain3=5; - } - - cout<>cases; - while(cases-->0) - { - cin>>input; - decent(input); - } - return 0; +#include + +using namespace std; + + +// Complete the decentNumber function below. + +void decent(int digits) +{ + int flag=0; + + if(digits==4 || digits==7 || digits<3) + flag=0; + else if(digits==5) + { + flag=1; + cout<<"33333\n"; + + } + else if(digits%3 ==0) + { + flag=1; + //(no. of times, what needs to be printed) + cout<=8) + { + + int remain3,remain5,temp; + + temp=digits%3; + flag=1; + if(temp==1) + { + remain5=digits-10; + remain3=10; + } + else if(temp==2) + { + remain5=digits-5; + remain3=5; + } + + cout<>cases; + while(cases-->0) + { + cin>>input; + decent(input); + } + return 0; } \ No newline at end of file diff --git a/Basic Math/The Additionator/The Additionator.txt b/Basic Math/The Additionator/The Additionator.txt new file mode 100644 index 0000000..59a741e --- /dev/null +++ b/Basic Math/The Additionator/The Additionator.txt @@ -0,0 +1,20 @@ +The Additionator - + +The first line contains an integer 1≤N≤100000 (The number of addition problems). The next N lines will each contain two space-separated integers whose absolute value is less than 1000000000 (numbers to add) + +Output N lines of one integer each, the solutions to the addition problems in order. + +Example: + +IN + +3 +4 2 +-1 -1000 +9 10 + +OUT + +6 +-1001 +19 diff --git a/Basic Math/The Additionator/solution.java b/Basic Math/The Additionator/solution.java new file mode 100644 index 0000000..d5a160f --- /dev/null +++ b/Basic Math/The Additionator/solution.java @@ -0,0 +1,14 @@ +import java.util.*; + +public class Main { + public static void main(String[] args) { + Scanner in = new Scanner(System.in); + + int N = in.nextInt(); + for (int i = 0; i < N; i++) { + int a = in.nextInt(); + int b = in.nextInt(); + System.out.println(a + b); + } + } +} diff --git a/The Prime Game/Problem_statement.txt b/Basic Math/The Prime Game/Problem_statement.txt similarity index 99% rename from The Prime Game/Problem_statement.txt rename to Basic Math/The Prime Game/Problem_statement.txt index 050d2b2..062ec10 100644 --- a/The Prime Game/Problem_statement.txt +++ b/Basic Math/The Prime Game/Problem_statement.txt @@ -1,9 +1,9 @@ -Manasa loves the nim game, in which there are n buckets, each having Ai balls. Two players play alternately. Each turn consists of removing some non-zero number of balls from one of the bucket. A player with lack of moves looses. But, Manasa having played it so many times, she gets bored one day. So she wants to change the rules of the game. She loves prime numbers, so she makes a new rule: any player can only remove a prime number of balls from a bucket. But there are infinite number prime numbers. So to keep the game simple, a player can only remove x balls from a bucket if x belongs to the set - -S = {2, 3, 5, 7, 11, 13} - -The whole game can now be described as follows: - -There are buckets, and the bucket contains balls. A player can choose a bucket and remove balls from that bucket where belongs to . A player loses if there are no more available moves. - +Manasa loves the nim game, in which there are n buckets, each having Ai balls. Two players play alternately. Each turn consists of removing some non-zero number of balls from one of the bucket. A player with lack of moves looses. But, Manasa having played it so many times, she gets bored one day. So she wants to change the rules of the game. She loves prime numbers, so she makes a new rule: any player can only remove a prime number of balls from a bucket. But there are infinite number prime numbers. So to keep the game simple, a player can only remove x balls from a bucket if x belongs to the set + +S = {2, 3, 5, 7, 11, 13} + +The whole game can now be described as follows: + +There are buckets, and the bucket contains balls. A player can choose a bucket and remove balls from that bucket where belongs to . A player loses if there are no more available moves. + Manasa plays the first move against Sandy. Who will win if both of them play optimally? \ No newline at end of file diff --git a/The Prime Game/Solution.py b/Basic Math/The Prime Game/Solution.py similarity index 96% rename from The Prime Game/Solution.py rename to Basic Math/The Prime Game/Solution.py index 7ec6413..4238403 100644 --- a/The Prime Game/Solution.py +++ b/Basic Math/The Prime Game/Solution.py @@ -1,12 +1,12 @@ -s = [0, 0, 1, 1, 2, 2, 3, 3, 4] -t = int(input()) -for ti in range(t): - n = int(input()) - a = [int(ai) for ai in input().strip().split(" ")] - ans = 0 - for i in range(n): - ans = ans^s[int(a[i]%len(s))] - if(ans>0): - print("Manasa") - else: - print("Sandy") +s = [0, 0, 1, 1, 2, 2, 3, 3, 4] +t = int(input()) +for ti in range(t): + n = int(input()) + a = [int(ai) for ai in input().strip().split(" ")] + ans = 0 + for i in range(n): + ans = ans^s[int(a[i]%len(s))] + if(ans>0): + print("Manasa") + else: + print("Sandy") diff --git a/When to take medicine/problem_statement.txt b/Basic Math/When to take medicine/problem_statement.txt similarity index 100% rename from When to take medicine/problem_statement.txt rename to Basic Math/When to take medicine/problem_statement.txt diff --git a/When to take medicine/when to take medicine_answer.txt b/Basic Math/When to take medicine/when to take medicine_answer.txt similarity index 100% rename from When to take medicine/when to take medicine_answer.txt rename to Basic Math/When to take medicine/when to take medicine_answer.txt diff --git a/find_factorial_of_a_number/find_factorial_of_a_number.txt b/Basic Math/find_factorial_of_a_number/find_factorial_of_a_number.txt similarity index 100% rename from find_factorial_of_a_number/find_factorial_of_a_number.txt rename to Basic Math/find_factorial_of_a_number/find_factorial_of_a_number.txt diff --git a/find_factorial_of_a_number/solution.cpp b/Basic Math/find_factorial_of_a_number/solution.cpp similarity index 100% rename from find_factorial_of_a_number/solution.cpp rename to Basic Math/find_factorial_of_a_number/solution.cpp diff --git a/project_euler problem12/Highly divisible triangular number.cpp b/Basic Math/project_euler problem12/Highly divisible triangular number.cpp similarity index 100% rename from project_euler problem12/Highly divisible triangular number.cpp rename to Basic Math/project_euler problem12/Highly divisible triangular number.cpp diff --git a/project_euler problem12/problem b/Basic Math/project_euler problem12/problem similarity index 100% rename from project_euler problem12/problem rename to Basic Math/project_euler problem12/problem diff --git a/Basic Program/A. Team/A.Team.cpp b/Basic Program/A. Team/A.Team.cpp new file mode 100644 index 0000000..05dfbeb --- /dev/null +++ b/Basic Program/A. Team/A.Team.cpp @@ -0,0 +1,24 @@ +#include + +int main() +{ + //Creation of vars + int n, a, b, c, count = 0; + //Take in input for n lines + std::cin >> n; + //Loop for n + for (int i = 0; i < n; i++) + { + //Take in user input + std::cin >> a; + std::cin >> b; + std::cin >> c; + //If more than 2 are sure then they will do the problem + if (a + b + c >= 2) + //Increase problem count + count++; + } + //Return problem count + std::cout << count; + return 0; +} diff --git a/Basic Program/A. Team/A.Team.txt b/Basic Program/A. Team/A.Team.txt new file mode 100644 index 0000000..f7d38b4 --- /dev/null +++ b/Basic Program/A. Team/A.Team.txt @@ -0,0 +1,34 @@ +A. Team [https://codeforces.com/contest/231/problem/A] + + +One day three best friends Petya, Vasya and Tonya decided to form a team and take part in programming contests. Participants are usually offered several problems during programming contests. Long before the start the friends decided that they will implement a problem if at least two of them are sure about the solution. Otherwise, the friends won't write the problem's solution. + +This contest offers n problems to the participants. For each problem we know, which friend is sure about the solution. Help the friends find the number of problems for which they will write a solution. + +Input +The first input line contains a single integer n (1 ≤ n ≤ 1000) — the number of problems in the contest. Then n lines contain three integers each, each integer is either 0 or 1. If the first number in the line equals 1, then Petya is sure about the problem's solution, otherwise he isn't sure. The second number shows Vasya's view on the solution, the third number shows Tonya's view. The numbers on the lines are separated by spaces. + +Output +Print a single integer — the number of problems the friends will implement on the contest. + +Examples +INPUT +3 +1 1 0 +1 1 1 +1 0 0 +OUTPUT +2 + +INPUT +2 +1 0 0 +0 1 1 +OUTPUT +1 + +Note +In the first sample Petya and Vasya are sure that they know how to solve the first problem and all three of them know how to solve the second problem. That means that they will write solutions for these problems. Only Petya is sure about the solution for the third problem, but that isn't enough, so the friends won't take it. + +In the second sample the friends will only implement the second problem, as Vasya and Tonya are sure about the solution. + diff --git a/Basic Program/CollatzConjecture/CollatzConjecture.txt b/Basic Program/CollatzConjecture/CollatzConjecture.txt new file mode 100644 index 0000000..799a6b3 --- /dev/null +++ b/Basic Program/CollatzConjecture/CollatzConjecture.txt @@ -0,0 +1,24 @@ +Collatz Conjecture + +The Collatz Conjecture says that if you take any number and follow the following steps, you will never be stuck in a loop. + +If the number is even -> number = number/2; +If the number is odd -> number = 3*number + 1; + +If you continue to do this, at some point your number will be equal to 1. + +Example: number = 26 + 1 Step - number = 26/2 = 13 + 2 Step - number = 13*3 + 1 = 40 + 3 Step - number = 40/2 = 20 + 4 Step - number = 20/2 = 10 + 5 Step - number = 10/2 = 5 + 6 Step - number = 3*5 + 1 = 16 + 7 Step - number = 16/2 = 8 + 8 Step - number = 8/2 = 4 + 9 Step - number = 4/2 = 2 + 10 Step - number = 2/2 = 1 + +For the number 26, 10 steps are needed, create a solution that calculates the number of steps for a given N number, +and the biggest value the number had during the steps. + diff --git a/Basic Program/CollatzConjecture/solution.c b/Basic Program/CollatzConjecture/solution.c new file mode 100644 index 0000000..0f667da --- /dev/null +++ b/Basic Program/CollatzConjecture/solution.c @@ -0,0 +1,23 @@ +#include +#include + +int main(){ + long int N = 26; //CALCULATING FOR N = 26 + long int biggestValue = 0; + long int steps = 0; + + while(N != 1){ + if(N%2 == 0){ + N = N/2; + }else{ + N = N*3 + 1; + } + if(N>biggestValue){ + biggestValue = N; + } + steps++; + } + + printf("Number of Steps: %ld BiggestValue: %ld", steps, biggestValue); + +} \ No newline at end of file diff --git a/EncoderProblem/Encoder.java b/Basic Program/EncoderProblem/Encoder.java similarity index 100% rename from EncoderProblem/Encoder.java rename to Basic Program/EncoderProblem/Encoder.java diff --git a/EncoderProblem/problem.txt b/Basic Program/EncoderProblem/problem.txt similarity index 100% rename from EncoderProblem/problem.txt rename to Basic Program/EncoderProblem/problem.txt diff --git a/Basic Program/Leap Year/instructions.txt b/Basic Program/Leap Year/instructions.txt new file mode 100644 index 0000000..47ee92e --- /dev/null +++ b/Basic Program/Leap Year/instructions.txt @@ -0,0 +1,11 @@ +Leap +Given a year, report if it is a leap year. + +The tricky thing here is that a leap year in the Gregorian calendar occurs: + +on every year that is evenly divisible by 4 + except every year that is evenly divisible by 100 + unless the year is also evenly divisible by 400 +For example, 1997 is not a leap year, but 1996 is. 1900 is not a leap year, but 2000 is. + +If your language provides a method in the standard library that does this look-up, pretend it doesn't exist and implement it yourself. diff --git a/Basic Program/Leap Year/ruby_solution.rb b/Basic Program/Leap Year/ruby_solution.rb new file mode 100644 index 0000000..d5051d8 --- /dev/null +++ b/Basic Program/Leap Year/ruby_solution.rb @@ -0,0 +1,8 @@ +def leap(year) + puts year %400 == 0 || year %4 == 0 && !(year %100 == 0) +end + +leap(1996) #expect true +leap(2000) #expect true +leap(2015) #expect false +leap(1800) #expect false diff --git a/Basic Program/Sleep_In/sleep_in.py b/Basic Program/Sleep_In/sleep_in.py new file mode 100644 index 0000000..efa6144 --- /dev/null +++ b/Basic Program/Sleep_In/sleep_in.py @@ -0,0 +1,7 @@ +"""The parameter weekday is True if it is a weekday, and the parameter vacation is True if we are on vacation. We sleep in if it is not a weekday or we're on vacation. +Return True if we sleep in.""" + +def sleep_in(weekday, vacation): + if not weekday or vacation: + return True + return False diff --git a/how-can-create-a-hackthoberfest-infinite-loop-in-python/hacktoberfest-loop.txt b/Basic Program/how-can-create-a-hackthoberfest-infinite-loop-in-python/hacktoberfest-loop.txt similarity index 100% rename from how-can-create-a-hackthoberfest-infinite-loop-in-python/hacktoberfest-loop.txt rename to Basic Program/how-can-create-a-hackthoberfest-infinite-loop-in-python/hacktoberfest-loop.txt diff --git a/how-can-create-a-hackthoberfest-infinite-loop-in-python/infinity-hscktoberfest-loop.py b/Basic Program/how-can-create-a-hackthoberfest-infinite-loop-in-python/infinity-hscktoberfest-loop.py similarity index 100% rename from how-can-create-a-hackthoberfest-infinite-loop-in-python/infinity-hscktoberfest-loop.py rename to Basic Program/how-can-create-a-hackthoberfest-infinite-loop-in-python/infinity-hscktoberfest-loop.py diff --git a/Aggressive Cows Spoj/problem statement.txt b/Binary Search/Aggressive Cows Spoj/problem statement.txt similarity index 100% rename from Aggressive Cows Spoj/problem statement.txt rename to Binary Search/Aggressive Cows Spoj/problem statement.txt diff --git a/Aggressive Cows Spoj/solution1.cpp b/Binary Search/Aggressive Cows Spoj/solution1.cpp similarity index 100% rename from Aggressive Cows Spoj/solution1.cpp rename to Binary Search/Aggressive Cows Spoj/solution1.cpp diff --git a/Aggressive Cows Spoj/solution2.cpp b/Binary Search/Aggressive Cows Spoj/solution2.cpp similarity index 100% rename from Aggressive Cows Spoj/solution2.cpp rename to Binary Search/Aggressive Cows Spoj/solution2.cpp diff --git a/Binary Search/binary_search/binary_search.txt b/Binary Search/binary_search/binary_search.txt new file mode 100644 index 0000000..352fb59 --- /dev/null +++ b/Binary Search/binary_search/binary_search.txt @@ -0,0 +1,3 @@ +Binary search + +Question- Given a sorted array of numbers and a number, find if the given number exists in the array in O(nlogn) time and O(1) space. \ No newline at end of file diff --git a/Binary Search/binary_search/bs.class b/Binary Search/binary_search/bs.class new file mode 100644 index 0000000..31b1966 Binary files /dev/null and b/Binary Search/binary_search/bs.class differ diff --git a/Binary Search/binary_search/bs.ctxt b/Binary Search/binary_search/bs.ctxt new file mode 100644 index 0000000..487f1ee --- /dev/null +++ b/Binary Search/binary_search/bs.ctxt @@ -0,0 +1,7 @@ +#BlueJ class context +comment0.target=bs +comment1.params=arr\ n +comment1.target=boolean\ binary_search(int[],\ int) +comment2.params=args +comment2.target=void\ main(java.lang.String[]) +numComments=3 diff --git a/Binary Search/binary_search/bs.java b/Binary Search/binary_search/bs.java new file mode 100644 index 0000000..c5eb9f4 --- /dev/null +++ b/Binary Search/binary_search/bs.java @@ -0,0 +1,29 @@ +class bs +{ + public boolean binary_search(int arr[], int n) + { + int right;int left; int mid; + right= arr.length; + left=0; + do{ + mid= (right+left)/2; + if(arr[mid]==n) + return true; + if(arr[mid]>n) + right= mid-1; + else + left= mid+1; + }while((arr[mid]!=n)&&(left!=right)); + return false; + } + public static void main(String args[]) + { + bs obj = new bs(); + int a[]={1,2,3,4,5}; + int n= 5; + if(obj.binary_search(a,n)) + System.out.println("Element found"); + else + System.out.println("Element is not present"); + } +} diff --git a/Binary Search/binary_search/solution.cpp b/Binary Search/binary_search/solution.cpp new file mode 100644 index 0000000..09ecfb5 --- /dev/null +++ b/Binary Search/binary_search/solution.cpp @@ -0,0 +1,32 @@ +#include +#include +using namespace std; + +bool binarySearch(vector arr,int ele) +{ + int l=0; + int r=arr.size()-1; + while(l<=r) + { + int m=(l+r)/2; + if(arr[m]==ele) + return true; + else{ + if(arr[m] arr({1,2,3,4,5}); + int ele=1; + if(binarySearch(arr,ele)) + cout<<"Exists"< +using namespace std; +map dp; +long long optcoins(int n){ + if(n<12) + return n; + if(dp.count(n)) + return dp[n]; + dp[n]=optcoins(n/2)+optcoins(n/3)+optcoins(n/4); + return dp[n]; +} +int main(){ + int x; + while(scanf("%d",&x)!=EOF) + printf("%lld\n",optcoins(x)); + return 0; +} diff --git a/COINS/Question.txt b/Dynamic Programming/COINS/Question.txt similarity index 100% rename from COINS/Question.txt rename to Dynamic Programming/COINS/Question.txt diff --git a/COINS/Readme.md b/Dynamic Programming/COINS/Readme.md similarity index 100% rename from COINS/Readme.md rename to Dynamic Programming/COINS/Readme.md diff --git a/COINS/Solution.cpp b/Dynamic Programming/COINS/Solution.cpp similarity index 100% rename from COINS/Solution.cpp rename to Dynamic Programming/COINS/Solution.cpp diff --git a/DP- Min Steps to 1/Min Steps to 1 Problem Statement.txt b/Dynamic Programming/DP- Min Steps to 1/Min Steps to 1 Problem Statement.txt similarity index 100% rename from DP- Min Steps to 1/Min Steps to 1 Problem Statement.txt rename to Dynamic Programming/DP- Min Steps to 1/Min Steps to 1 Problem Statement.txt diff --git a/DP- Min Steps to 1/minsteps.java b/Dynamic Programming/DP- Min Steps to 1/minsteps.java similarity index 100% rename from DP- Min Steps to 1/minsteps.java rename to Dynamic Programming/DP- Min Steps to 1/minsteps.java diff --git a/Dynamic Programming/Gold mine problem/GoldMineProblem.txt b/Dynamic Programming/Gold mine problem/GoldMineProblem.txt new file mode 100644 index 0000000..76506c3 --- /dev/null +++ b/Dynamic Programming/Gold mine problem/GoldMineProblem.txt @@ -0,0 +1,7 @@ +Gold Mine Problem + +Given a gold mine of n*m dimensions. + Each field in this mine contains a positive integer which is the amount of gold in tons. +Initially the miner is at first column but can be at any row. + He can move only (right->,right up /,right down\) that is from a given cell, the miner can move to the cell diagonally up towards the right or right or diagonally down towards the right. +Find out maximum amount of gold he can collect. \ No newline at end of file diff --git a/Dynamic Programming/Gold mine problem/solution.cpp.txt b/Dynamic Programming/Gold mine problem/solution.cpp.txt new file mode 100644 index 0000000..13394ba --- /dev/null +++ b/Dynamic Programming/Gold mine problem/solution.cpp.txt @@ -0,0 +1,61 @@ +// C++ program to solve Gold Mine problem +#include +using namespace std; + +const int MAX = 100; + +// Returns maximum amount of gold that can be collected +// when journey started from first column and moves +// allowed are right, right-up and right-down +int getMaxGold(int gold[][MAX], int m, int n) +{ + // Create a table for storing intermediate results + // and initialize all cells to 0. The first row of + // goldMineTable gives the maximum gold that the miner + // can collect when starts that row + int goldTable[m][n]; + memset(goldTable, 0, sizeof(goldTable)); + + for (int col=n-1; col>=0; col--) + { + for (int row=0; row) + int right = (col==n-1)? 0: goldTable[row][col+1]; + + // Gold collected on going to the cell to right up (/) + int right_up = (row==0 || col==n-1)? 0: + goldTable[row-1][col+1]; + + // Gold collected on going to the cell to right down (\) + int right_down = (row==m-1 || col==n-1)? 0: + goldTable[row+1][col+1]; + + // Max gold collected from taking either of the + // above 3 paths + goldTable[row][col] = gold[row][col] + + max(right, max(right_up, right_down)); + + } + } + + // The max amount of gold collected will be the max + // value in first column of all rows + int res = goldTable[0][0]; + for (int i=1; i [[],[1],[2],[3],[1,3],[1,2][2,3],[1,2,3]] + +const powerSet = (arr) => { + const result = []; + + const _recurse = (chosen, remaining) => { + if (remaining.length === 0) { + result.push(chosen); + } else { + _recurse(chosen, remaining.slice(1)); + _recurse(chosen.concat(remaining[0]), remaining.slice(1)); + } + }; + + _recurse([], arr); + return result; +} + +console.log(powerSet([1, 2, 3])); \ No newline at end of file diff --git a/Dynamic Programming/Powerset/question.txt b/Dynamic Programming/Powerset/question.txt new file mode 100644 index 0000000..2eb1aca --- /dev/null +++ b/Dynamic Programming/Powerset/question.txt @@ -0,0 +1,5 @@ +given an array, provide all subsets (powersets); + +result: +[1,3,2] +[[],[1],[2],[3],[1,3],[1,2][2,3],[1,2,3]] \ No newline at end of file diff --git a/Dynamic Programming/Prime_subsequence/question.txt b/Dynamic Programming/Prime_subsequence/question.txt new file mode 100644 index 0000000..b91d65a --- /dev/null +++ b/Dynamic Programming/Prime_subsequence/question.txt @@ -0,0 +1,10 @@ + +Given a sequence of prime numbers A1,A2,…,AN. This sequence has exactly 2N subsequences. +A subsequence of A is good if it does not contain any two identical numbers; in particular, the empty sequence is good. + +You to find the number of good subsequences which contain at most K numbers. +This number could be very large, so compute it modulo 1,000,000,007. + +Constraints: +1≤K≤N≤105 +2≤Ai≤8,000 for each valid i diff --git a/Dynamic Programming/Prime_subsequence/solution.cpp b/Dynamic Programming/Prime_subsequence/solution.cpp new file mode 100644 index 0000000..09cc920 --- /dev/null +++ b/Dynamic Programming/Prime_subsequence/solution.cpp @@ -0,0 +1,41 @@ +#include +using namespace std; +int main(){ + ios_base::sync_with_stdio(false); + int n,k;cin>>n>>k; + int a[n];long long int mod=1000000007; + int max=0; + for(int i=0;i>a[i]; + if(a[i]>max) + max=a[i]; + } + long int f[max+1]; + memset(f,0,sizeof(f)); + for(int i=0;iv; + for(int i=0;i<=max;i++) + if(f[i]) + v.push_back(f[i]); + long int l=v.size(); + k=k>l?l:k; + long int dpans[k+1][l],val; + val=v[0]+1; + memset(dpans,0,sizeof(dpans)); + dpans[0][0]=1; + dpans[1][0]=val; + long int total=0; + for(int i=2;i<=k;i++) + dpans[i][0]=val; + for(int i=1;i 0 length of rod => 0 profit + if(j == 0) { + continue; + } + + // First row => T[i-1][j] doesn't exist so just pick the second value + else if(i == 0) { + T[i][j] = price[i] + T[i][j-i-1]; + } + + // where j <= i => T[i][j-i-1] doesn't exist so just pick the first value + else if(j-i-1 < 0) { + T[i][j] = T[i-1][j]; + } + + // using the whole expression + else { + T[i][j] = Math.max(T[i-1][j], (price[i] + T[i][j-i-1])); + } + } + } + return T[n-2][n]; + } + + public static void main(String args[]) + { + int price[] = new int[] {2,5,7,8}; + int n = 5; + System.out.println("Maximum profit is " + cut_rod(price, n)); + } +} diff --git a/The Mailbox Manufacturers Problem/mailbox-question.txt b/Dynamic Programming/The Mailbox Manufacturers Problem/mailbox-question.txt similarity index 100% rename from The Mailbox Manufacturers Problem/mailbox-question.txt rename to Dynamic Programming/The Mailbox Manufacturers Problem/mailbox-question.txt diff --git a/The Mailbox Manufacturers Problem/solution.cpp b/Dynamic Programming/The Mailbox Manufacturers Problem/solution.cpp similarity index 100% rename from The Mailbox Manufacturers Problem/solution.cpp rename to Dynamic Programming/The Mailbox Manufacturers Problem/solution.cpp diff --git a/Dynamic Programming/Zero_Sum_SubArray/question.txt b/Dynamic Programming/Zero_Sum_SubArray/question.txt new file mode 100644 index 0000000..de9d990 --- /dev/null +++ b/Dynamic Programming/Zero_Sum_SubArray/question.txt @@ -0,0 +1,4 @@ +Given an Array of size N, identify whether there exists a subarray with zero sum? + +Conditions: -10^6<=N<=10^6 +Time limit is 1.0 sec diff --git a/Dynamic Programming/Zero_Sum_SubArray/solution.cpp b/Dynamic Programming/Zero_Sum_SubArray/solution.cpp new file mode 100644 index 0000000..793b681 --- /dev/null +++ b/Dynamic Programming/Zero_Sum_SubArray/solution.cpp @@ -0,0 +1,37 @@ +/* C++ Solution */ + +#include +using namespace std; + +/*Function to check whether zero sum subarray exists or not*/ +bool hasZeroSum(int arr[], int N) +{ + set st; + int sum=0; + for(int i=0;i>N; + int arr[N+1]; + + //Array input + for(int i=0;i>arr[i]; + + + bool ans = hasZeroSum(arr,N); + cout< +#include + +using namespace std; + +int main(){ + int L; + char d[5001]; + long long dp[5001]; + + while(true){ + scanf("%s",d); + if(d[0]=='0') break; + + L = strlen(d); + + dp[0] = dp[1] = 1; + + for(int i = 2;i<=L;++i){ + dp[i] = 0; + + char c1 = d[i-2]-'0', c2 = d[i-1]-'0'; + + if(c1==1 || (c1==2 && c2<=6)) dp[i] += dp[i-2]; + if(c2!=0) dp[i] += dp[i-1]; + } + + printf("%lld\n",dp[L]); + } + + return 0; +} diff --git a/Dynamic Programming/largest_comman_subsequece/largest_comman_subsecuence.cpp b/Dynamic Programming/largest_comman_subsequece/largest_comman_subsecuence.cpp new file mode 100644 index 0000000..f8996f7 --- /dev/null +++ b/Dynamic Programming/largest_comman_subsequece/largest_comman_subsecuence.cpp @@ -0,0 +1,35 @@ +#include +#include +#include +using namespace std; +int solver(string s1,string s2,vector>&dp,int n,int m) +{ + if(s1.empty()||s2.empty()) + return 0; + if(dp[n][m] >= 0) + return dp[n][m]; + if(s1[0]==s2[0]) + { + int ans = 1 + solver(s1.substr(1),s2.substr(1),dp,n-1,m-1); + dp[n][m] = ans; + return ans; + } + int ans1 = solver(s1,s2.substr(1),dp,n,m-1); + int ans2 = solver(s1.substr(1),s2,dp,n-1,m); + dp[n][m] = max(ans1,ans2); + return max(ans1,ans2); +} +int lcs(string s1, string s2) +{ + int n = s1.length(),m=s2.length(); + vector>dp(n+1,vector(m+1,-1)); + int ans = solver( s1, s2, dp , s1.length(),s2.length()); + return ans; +} + +int main() +{ + string s1, s2; + cin >> s1 >> s2; + cout << lcs(s1, s2); +} diff --git a/Dynamic Programming/largest_comman_subsequece/question.txt b/Dynamic Programming/largest_comman_subsequece/question.txt new file mode 100644 index 0000000..5f6391b --- /dev/null +++ b/Dynamic Programming/largest_comman_subsequece/question.txt @@ -0,0 +1,3 @@ +LCS Problem Statement: Given two sequences, find the length of longest subsequence present in both of them. A subsequence is a sequence that appears in the same relative order, but not necessarily contiguous. + + diff --git a/Product_of_lengths_all_cycles_undirected_graph/question.txt b/Graph/Product_of_lengths_all_cycles_undirected_graph/question.txt similarity index 100% rename from Product_of_lengths_all_cycles_undirected_graph/question.txt rename to Graph/Product_of_lengths_all_cycles_undirected_graph/question.txt diff --git a/Product_of_lengths_all_cycles_undirected_graph/solution.cpp b/Graph/Product_of_lengths_all_cycles_undirected_graph/solution.cpp similarity index 100% rename from Product_of_lengths_all_cycles_undirected_graph/solution.cpp rename to Graph/Product_of_lengths_all_cycles_undirected_graph/solution.cpp diff --git a/Greedy/Cutting_a_Rod/CuttingARod.java b/Greedy/Cutting_a_Rod/CuttingARod.java new file mode 100644 index 0000000..8a29c87 --- /dev/null +++ b/Greedy/Cutting_a_Rod/CuttingARod.java @@ -0,0 +1,33 @@ +/** + * Time Complexity : O(n^2) + * which is much better than the + * worst case time complexity of Naive Recursive implementation. + */ + +import java.util.*; +import java.io.*; + +class CuttingARod { + + public static int cutCutCut(int price[], int size) { + + int memory[] = new int[size+1]; + memory[0] = 0; + + for(int i=1; i<=size; i++){ + int maximum = Integer.MIN_VALUE; + for(int j=0; j + +using namespace std; + +int main() + +{ + +int N,i=0; + +cin>>N; + +while(i1) - { - for(int i =0;i1) + { + for(int i =0;i +using namespace std; +#define R 3 +#define C 6 + +void spiralPrint(int m, int n, int a[R][C]) +{ + int i, k = 0, l = 0; + + while (k < m && l < n) + { + for (i = l; i < n; ++i) + cout << a[k][i] << " "; + k++; + + for (i = k; i < m; ++i) + cout << a[i][n - 1] << " "; + n--; + + if (k < m) + { + for (i = n - 1; i >= l; --i) + cout << a[m - 1][i] << " "; + m--; + } + + if (l < n) { + for (i = m - 1; i >= k; --i) + cout << a[i][l] << " "; + l++; + } + } +} + +int main() +{ + int a[R][C] = { { 1, 2, 3, 4, 5, 6 }, + { 7, 8, 9, 10, 11, 12 }, + { 13, 14, 15, 16, 17, 18 } }; + + spiralPrint(R, C, a); + return 0; +} \ No newline at end of file diff --git a/README.md b/README.md index 7f7b618..2acee2f 100644 --- a/README.md +++ b/README.md @@ -1,11 +1,24 @@ # Competitive Programming questions + This repo is open for all. Add your favourite competitive programming questions along with the solution. ## Guidelines -- Create a folder with the question name. +- Create a folder with the question name. - Add a .txt file with the problem statement and a solution file which contains the solution of the given problem. +## Folder Structure + +``` +├── Array +| ├── Question/Problem name +| | ├── Question.txt +| | ├── Solution.yourLanguageExt +``` + +- Try to maintain `👆above` folder structure. +- If your question/Problem folder doesn't lie in the above once fill free to create + ## Getting Started - Fork this repo (button on top) @@ -17,7 +30,7 @@ git clone https://github.com/your-username/Competitive-Programming-questions.git ``` - Create a new folder with the question name. -- Add your question and solution file in that folder. +- Add your question and solution file in that folder. - Commit and push ```markdown diff --git a/Factorial using Recursion/Factorial using recursion.cpp b/Recursion/Factorial using Recursion/Factorial using recursion.cpp similarity index 100% rename from Factorial using Recursion/Factorial using recursion.cpp rename to Recursion/Factorial using Recursion/Factorial using recursion.cpp diff --git a/Factorial using Recursion/Question.txt b/Recursion/Factorial using Recursion/Question.txt similarity index 100% rename from Factorial using Recursion/Question.txt rename to Recursion/Factorial using Recursion/Question.txt diff --git a/Recursion/Tower-of-Hanoi/Hanoi.java b/Recursion/Tower-of-Hanoi/Hanoi.java new file mode 100644 index 0000000..a6e0571 --- /dev/null +++ b/Recursion/Tower-of-Hanoi/Hanoi.java @@ -0,0 +1,22 @@ +import java.util.Scanner; + +class Hanoi{ + public static void main(String[] args){ + Scanner newInput = new Scanner(System.in); + System.out.print("Enter the value of n: "); + int n = newInput.nextInt(); + char[] rod = new char[]{'A','B','C'}; + move(n,rod[0],rod[2],rod[1]); + } + + + public static void move(int n, char from, char to, char aux){ + if (n == 1) { + System.out.println("Move " + n + " From " + from + " to " + to); + return; + } + move(n-1,from,aux,to); + System.out.println("Move " + n + " From " + from + " to " + to); + move(n-1,aux,to,from); + } +} \ No newline at end of file diff --git a/Recursion/Tower-of-Hanoi/Tower of Hanoi.txt b/Recursion/Tower-of-Hanoi/Tower of Hanoi.txt new file mode 100644 index 0000000..88ff2b5 --- /dev/null +++ b/Recursion/Tower-of-Hanoi/Tower of Hanoi.txt @@ -0,0 +1,16 @@ +Tower of Hanoi is a mathematical puzzle where we have three rods and n disks. The objective of the puzzle is to move the entire stack to another rod, obeying the following simple rules: +1) Only one disk can be moved at a time. +2) Each move consists of taking the upper disk from one of the stacks and placing it on top of another stack i.e. a disk can only be moved if it is the uppermost disk on a stack. +3) No disk may be placed on top of a smaller disk. + +The most ideal solution to this problem has 2^n-1 steps, where, n = number of disks. + +For example: +For 2 disks : +Let rod 1 = 'A', rod 2 = 'B', rod 3 = 'C'. +Number of Steps = 2^2-1 = 3. + +Therefore, +Step 1 : Shift first disk from 'A' to 'B'. +Step 2 : Shift second disk from 'A' to 'C'. +Step 3 : Shift first disk from 'B' to 'C'. \ No newline at end of file diff --git a/In search of an easy problem/problem_statement.txt b/Searching/In search of an easy problem/problem_statement.txt similarity index 100% rename from In search of an easy problem/problem_statement.txt rename to Searching/In search of an easy problem/problem_statement.txt diff --git a/In search of an easy problem/sol.cpp b/Searching/In search of an easy problem/sol.cpp similarity index 100% rename from In search of an easy problem/sol.cpp rename to Searching/In search of an easy problem/sol.cpp diff --git a/SGU_weeds_344/weed.cpp b/Searching/SGU_weeds_344/weed.cpp similarity index 100% rename from SGU_weeds_344/weed.cpp rename to Searching/SGU_weeds_344/weed.cpp diff --git a/SGU_weeds_344/weed.txt b/Searching/SGU_weeds_344/weed.txt similarity index 100% rename from SGU_weeds_344/weed.txt rename to Searching/SGU_weeds_344/weed.txt diff --git a/Sorting/Get Longest Sorted Sequence/answer.py b/Sorting/Get Longest Sorted Sequence/answer.py new file mode 100644 index 0000000..24a404f --- /dev/null +++ b/Sorting/Get Longest Sorted Sequence/answer.py @@ -0,0 +1,40 @@ +def get_longest_sorted_sequence(words): + count = 1 + total_letters = 0 + current = 0 + increasing_sum = 0 + is_sequence = True + + if len(words) == 0: + return 0 + else: + current = len(words[0]) + + for i in range (1, len(words)): + next = len(words[i]) + if current == next-1: + print(current) + # in sequence + count += 1 + current = len(words[i]) + print(current) + else: + current = len(words[i]) + + return count + + +# test cases +print ('Actual :' + str(get_longest_sorted_sequence(['a', 'is', 'ape', 'in']))) +print () + + +print ('Actual :' + str(get_longest_sorted_sequence(['apple', 'in', 'has', 'wed', 'code', 'rocks', 'bee']))) +print () + + +print ('Actual :' + str(get_longest_sorted_sequence(['apple']))) +print () + +print ('Actual :' + str(get_longest_sorted_sequence([]))) +print () diff --git a/Sorting/Get Longest Sorted Sequence/problem.txt b/Sorting/Get Longest Sorted Sequence/problem.txt new file mode 100644 index 0000000..a22267c --- /dev/null +++ b/Sorting/Get Longest Sorted Sequence/problem.txt @@ -0,0 +1,3 @@ +The function takes in as its parameter a list called words that contains strings. This function first calculates the length of each word, and then returns the count whereby the sequence formed by the length of the words is in increasing order. + +The function calculates the length of every string in the list. It has to then generate a sequence of numbers that are of increasing numberical value and return the length of the longest such sequence generated. \ No newline at end of file diff --git a/Sorting/Insertion_sort_using_classes/insertion_sort.cpp b/Sorting/Insertion_sort_using_classes/insertion_sort.cpp new file mode 100644 index 0000000..8aaa360 --- /dev/null +++ b/Sorting/Insertion_sort_using_classes/insertion_sort.cpp @@ -0,0 +1,182 @@ +#include +using namespace std; + +/* Hi I am using my own class to use in insertion sort function*/ + +template +class LinearList{ + private: + int MaxSize; + Item *element; // 1D dynamic array + int len; + public: + /* Default constructor. + * Should create an empty list that not contain any elements*/ + LinearList() + { + element=nullptr; + len=0; + }; + + /* This constructor should create a list containing MaxSize elements. You can intialize the elements with any values.*/ + LinearList(const int& MaxListSize) + { + MaxSize=MaxListSize; + element = new Item[MaxSize]; + len=0; + + }; + + /* Destructor. + * Must free all the memory contained by the list */ + ~LinearList(){}; + + /* Indexing operator. + * It should behave the same way array indexing does. i.e, + * LinearList L; + * L[0] should refer to the first element; + * L[1] to the second element and so on. + * */ + Item& operator[](const int& i) + { + return element[i]; + }; //return i'th element of list + + /* Returns true if the list is empty, false otherwise. + * */ + bool isEmpty() + { + if(len==0) + { + return true; + } + else + { + return false; + } + }; + + /* Returns the actual length (number of elements) in the list. + * */ + int length() + { + return len; + }; + + /* Returns the maximum size of the list. + * */ + int maxSize() + { + return maxSize; + }; + + /* Returns the k-th element of the list. + * */ + Item returnListElement(const int k) + { + return element[k-1]; + }; + /* Set x to the k-th element and + * return true if k-th element is present otherwise return false. + * */ + bool find(const int k, Item& x) + { + if(x==element[k-1]) + { + return true; + } + else + { + + return false; + } + }; + + /* Search for x and + * return the position if found, else return 0. + * */ + int search(Item& x) + { + for(int i=0;ik;i--) + { + element[i]=element[i-1]; + } + element[k]=x; + len=len+1; + }; + + +}; + +//insertion sort function +void insertionSort(LinearList& A) + { + int i,j,temp,len; + i=j=0; + len=A.length(); + j=len; + for(i=1;i-1;j--) + { + if(temp> n; + LinearList l(100); + + for(i=0;i> temp; + l.insert(i,temp); + } + insertionSort(l); + for(i=0;i { + if (arr.length <= 1) { + return arr; + } + + let midIdx = Math.floor(arr.length / 2); + let left = arr.slice(0, midIdx); + let right = arr.slice(midIdx); + + let leftSorted = mergeSort(left); + let rightSorted = mergeSort(right); + + return merge(leftSorted, rightSorted); + +}; + +const merge = (arr1, arr2) => { + let merged = []; + + while (arr1.length && arr2.length) { + if (arr1[0] < arr2[0]) { + merged.push(arr1.shift()); + } else { + merged.push(arr2.shift()); + } + } + + return [...merged, ...arr1, ...arr2]; +}; + +console.log(mergeSort(myArray)); \ No newline at end of file diff --git a/Sorting/Mergesort-JS/question.txt b/Sorting/Mergesort-JS/question.txt new file mode 100644 index 0000000..3d3188a --- /dev/null +++ b/Sorting/Mergesort-JS/question.txt @@ -0,0 +1,5 @@ +Sort the given by implementing Quicksort +[2, 4, 1, 6, -7, 8, 5, 9, 3, 4] + +answer: +[ -7, 1, 2, 3, 4, 4, 5, 6, 8, 9 ] \ No newline at end of file diff --git a/Sorting/Merging_Two_Sorted_Array/question.txt b/Sorting/Merging_Two_Sorted_Array/question.txt new file mode 100644 index 0000000..43fe95f --- /dev/null +++ b/Sorting/Merging_Two_Sorted_Array/question.txt @@ -0,0 +1 @@ +Given two sorted arrays arr1[] and arr2[] in non-decreasing order with size n and m. The task is to merge the two sorted arrays into one sorted array (in non-decreasing order) diff --git a/Sorting/Merging_Two_Sorted_Array/solution.cpp b/Sorting/Merging_Two_Sorted_Array/solution.cpp new file mode 100644 index 0000000..a61ab49 --- /dev/null +++ b/Sorting/Merging_Two_Sorted_Array/solution.cpp @@ -0,0 +1,54 @@ +#include +using namespace std; +int main() + { + int t; + cin>>t; + while(t--) + { + int x,y; + cin>>x>>y; + long a[x+1],b[y+1]; + for(int i=0;i>a[i]; + for(int i=0;i>b[i]; + + int i=0,j=0; + vector vec; + while(ib[j]) + { + vec.push_back(b[j]); + j++; + } + else if(a[i]==b[j]) + { + vec.push_back(a[i]); + vec.push_back(b[j]); + i++; + j++; + } + } + while(i +using namespace std; + +void copyArr(int from[], int si, int ei, int * to) { + // while (si <= ei) *to++ = *si++; + while (si <= ei) { + *to = from[si]; + ++si; + ++to; + } +} + + +void mergeSortedArray(int arr[], int si, int ei, int mid) { + + int tmp_A[100]; + int tmp_B[100]; + + copyArr(arr, si, mid, tmp_A); + copyArr(arr, mid + 1, ei, tmp_B); + + int i = 0; + int j = 0; + int k = si; + + //while a has elements and b has elements, I have to do something + int size_A = mid - si + 1; + int size_B = ei - (mid + 1) + 1; + + while (i < size_A && j < size_B) { + if (tmp_A[i] < tmp_B[j]) { + arr[k] = tmp_A[i]; + i++; + k++; + } + else { + arr[k++] = tmp_B[j++]; + } + } + + while (i < size_A) { + arr[k++] = tmp_A[i++]; + } + + while (j < size_B) arr[k++] = tmp_B[j++]; + + +} + + +void mergeSort(int arr[], int si, int ei) { + if (si >= ei) { + //no elements + return; + } + + int mid = (si + ei) / 2; + //sort the left part + mergeSort(arr, si, mid); + mergeSort(arr, mid + 1, ei); + + mergeSortedArray(arr, si, ei, mid); + +} + + +int main() { + int arr[100]; + int n; + cin >> n; + inputArr(arr, n); + + mergeSort(arr, 0, n - 1); + + printArr(arr, n); +} diff --git a/Sorting/Mersort_In_C++/mergesort.txt b/Sorting/Mersort_In_C++/mergesort.txt new file mode 100644 index 0000000..ba3cfe6 --- /dev/null +++ b/Sorting/Mersort_In_C++/mergesort.txt @@ -0,0 +1,13 @@ +Merge Sort is a Divide and Conquer algorithm. It divides input array in +two halves, calls itself for the two halves and then merges the two sorted halves. +Algorithm: +MergeSort(arr[], l, r) +If r > l +1. Find the middle point to divide the array into two halves: + middle m = (l+r)/2 +2. Call mergeSort for first half: + Call mergeSort(arr, l, m) +3. Call mergeSort for second half: + Call mergeSort(arr, m+1, r) +4. Merge the two halves sorted in step 2 and 3: + Call merge(arr, l, m, r) \ No newline at end of file diff --git a/Sorting/Quicksort-JS/question.txt b/Sorting/Quicksort-JS/question.txt new file mode 100644 index 0000000..3d3188a --- /dev/null +++ b/Sorting/Quicksort-JS/question.txt @@ -0,0 +1,5 @@ +Sort the given by implementing Quicksort +[2, 4, 1, 6, -7, 8, 5, 9, 3, 4] + +answer: +[ -7, 1, 2, 3, 4, 4, 5, 6, 8, 9 ] \ No newline at end of file diff --git a/Sorting/Quicksort-JS/quickSort.js b/Sorting/Quicksort-JS/quickSort.js new file mode 100644 index 0000000..e67e3e7 --- /dev/null +++ b/Sorting/Quicksort-JS/quickSort.js @@ -0,0 +1,21 @@ +const myArray = [2, 4, 1, 6, -7, 8, 5, 9, 3, 4]; + +const quickSortV1 = arr => { + if (arr.length <= 1) { + return arr; + } + + // shift takes out the element of the array + // so that it can reach the base case + let pivot = arr.shift(); + let left = arr.filter(el => el < pivot); + let right = arr.filter(el => el >= pivot); + + let leftSorted = quickSortV1(left); + let rightSorted = quickSortV1(right); + + return [...leftSorted, pivot, ...rightSorted]; + +}; + +console.log(quickSortV1(myArray)); \ No newline at end of file diff --git a/Quicksort-python/Question.txt b/Sorting/Quicksort-python/Question.txt similarity index 100% rename from Quicksort-python/Question.txt rename to Sorting/Quicksort-python/Question.txt diff --git a/Quicksort-python/algorithm.txt b/Sorting/Quicksort-python/algorithm.txt similarity index 100% rename from Quicksort-python/algorithm.txt rename to Sorting/Quicksort-python/algorithm.txt diff --git a/Quicksort-python/quickSort.py b/Sorting/Quicksort-python/quickSort.py old mode 100755 new mode 100644 similarity index 100% rename from Quicksort-python/quickSort.py rename to Sorting/Quicksort-python/quickSort.py diff --git a/Sorting/bubble_sort_c/question.txt b/Sorting/bubble_sort_c/question.txt new file mode 100644 index 0000000..bd6c83d --- /dev/null +++ b/Sorting/bubble_sort_c/question.txt @@ -0,0 +1,2 @@ +Make a C program to bubble sort this array of integers (smallest to biggest): {303, -909, 101, 42, 0, 42, 21, 1, 2} +Expected result => {-909, 0, 1, 2, 21. 42, 42, 101, 303} diff --git a/Sorting/bubble_sort_c/solution/bubble_sort.c b/Sorting/bubble_sort_c/solution/bubble_sort.c new file mode 100644 index 0000000..8f7ab02 --- /dev/null +++ b/Sorting/bubble_sort_c/solution/bubble_sort.c @@ -0,0 +1,23 @@ +#include "bubble_sort.h" + +void swap_values(int *a, int *b) +{ + int buffer = *a; + *a = *b; + *b = buffer; +} + +int *bubble_sort(int *arr, size_t arr_len) +{ + size_t i = 0; + + while (i++ < arr_len) + { + if (arr[i] < arr[i-1]) + { + swap_values(&arr[i], &arr[i-1]); + i = 0; + } + } + return(arr); +} diff --git a/Sorting/bubble_sort_c/solution/bubble_sort.h b/Sorting/bubble_sort_c/solution/bubble_sort.h new file mode 100644 index 0000000..4e69c28 --- /dev/null +++ b/Sorting/bubble_sort_c/solution/bubble_sort.h @@ -0,0 +1,5 @@ +#include +#include + +int *bubble_sort(int *arr, size_t arr_len); +void print_array(int *arr, size_t arr_len); diff --git a/Sorting/bubble_sort_c/solution/main.c b/Sorting/bubble_sort_c/solution/main.c new file mode 100644 index 0000000..9616442 --- /dev/null +++ b/Sorting/bubble_sort_c/solution/main.c @@ -0,0 +1,12 @@ +#include "bubble_sort.h" + +int main(void) +{ + int to_sort[] = {303, -909, 101, 42, 0, 42, 21, 1, 2}; + size_t arr_len = sizeof(to_sort) / sizeof(to_sort[0]); + int *sorted = bubble_sort(to_sort, arr_len); + + print_array(sorted, arr_len); + + return(EXIT_SUCCESS); +} diff --git a/Sorting/bubble_sort_c/solution/print_array.c b/Sorting/bubble_sort_c/solution/print_array.c new file mode 100644 index 0000000..39c130a --- /dev/null +++ b/Sorting/bubble_sort_c/solution/print_array.c @@ -0,0 +1,10 @@ +#include "bubble_sort.h" + +void print_array(int *arr, size_t arr_len) +{ + size_t i; + + printf("Sorted array:\n"); + for (i = 0; i < arr_len; i++) + printf("%d\n", arr[i]); +} diff --git a/Stack/Binary numbers/Question.txt b/Stack/Binary numbers/Question.txt new file mode 100644 index 0000000..d540fa0 --- /dev/null +++ b/Stack/Binary numbers/Question.txt @@ -0,0 +1 @@ +The question is how to make binary numbers using a stack. \ No newline at end of file diff --git a/Stack/Binary numbers/solution.cpp b/Stack/Binary numbers/solution.cpp new file mode 100644 index 0000000..a388706 --- /dev/null +++ b/Stack/Binary numbers/solution.cpp @@ -0,0 +1,27 @@ +#include +#include +using namespace std; +int main() +{ + int a,b,l,c; + stack stos; + cout << "Number to change: "; + cin >> a; + l=a; + + while(a!=0) + { + b=a%2; + a=a/2; + stos.push(b); + } + cout << "Number " << l << " is equal to: "; + while(!stos.empty()) + { + cout << stos.top(); + stos.pop(); + } + cout << " in binary system."; + +return 0; +} diff --git a/Stack/Generate Parentheses/Question.txt b/Stack/Generate Parentheses/Question.txt new file mode 100644 index 0000000..4b3c0df --- /dev/null +++ b/Stack/Generate Parentheses/Question.txt @@ -0,0 +1,11 @@ +Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses. + +For example, given n = 3, a solution set is: + +[ + "((()))", + "(()())", + "(())()", + "()(())", + "()()()" +] \ No newline at end of file diff --git a/Stack/Generate Parentheses/Solution b/Stack/Generate Parentheses/Solution new file mode 100644 index 0000000..c1d065f Binary files /dev/null and b/Stack/Generate Parentheses/Solution differ diff --git a/Stack/Generate Parentheses/Solution.cpp b/Stack/Generate Parentheses/Solution.cpp new file mode 100644 index 0000000..3153f05 --- /dev/null +++ b/Stack/Generate Parentheses/Solution.cpp @@ -0,0 +1,45 @@ +#include +using namespace std; + +void generate(int n, int opening, int closing, string combination, vector& result) { + int size = combination.size(); + if(size == n && closing == opening) { + result.push_back(combination); + return; + } + + if((closing < opening) && (size > 0)) { + combination.push_back(')'); + generate(n, opening, closing+1, combination, result); + combination.pop_back(); + } + + if(size < n-1) { + combination.push_back('('); + generate(n, opening+1, closing, combination, result); + combination.pop_back(); + } +} + +vector generateParenthesis(int n) { + vector result; + string combination; + generate(2*n, 0, 0, combination, result); + return result; +} + +int main() { + + int n; + vector result; + + scanf("%d", &n); + + result = generateParenthesis(n); + + for(int i=0; i {}'.format(s1, s2, are_anagram(s1, s2))) + print('{} / {} -> {}'.format(s1, s3, are_anagram(s1, s3))) + print('{} / {} -> {}'.format(s2, s3, are_anagram(s2, s3))) + +if __name__=='__main__': + main() diff --git a/String/AnagramChecking/anagram_checking.txt b/String/AnagramChecking/anagram_checking.txt new file mode 100644 index 0000000..43158e6 --- /dev/null +++ b/String/AnagramChecking/anagram_checking.txt @@ -0,0 +1,3 @@ +Anagram checking + +Write a function that check whether two given strings are anagram of each other. An anagram is a word or phrase formed by rearranging the letters of a different word or phrase using all the original letters exactly once. An optimized solution should have a O(n) time complexity and O(1) space complexity. diff --git a/Arrangement_of_Queue/Question.txt b/String/Arrangement_of_Queue/Question.txt similarity index 100% rename from Arrangement_of_Queue/Question.txt rename to String/Arrangement_of_Queue/Question.txt diff --git a/Arrangement_of_Queue/README.md b/String/Arrangement_of_Queue/README.md similarity index 100% rename from Arrangement_of_Queue/README.md rename to String/Arrangement_of_Queue/README.md diff --git a/Arrangement_of_Queue/Solution.py b/String/Arrangement_of_Queue/Solution.py similarity index 100% rename from Arrangement_of_Queue/Solution.py rename to String/Arrangement_of_Queue/Solution.py diff --git a/String/Cenit-Polar-Crypt/Issue.txt b/String/Cenit-Polar-Crypt/Issue.txt new file mode 100644 index 0000000..9014f79 --- /dev/null +++ b/String/Cenit-Polar-Crypt/Issue.txt @@ -0,0 +1,40 @@ +Create a solution that can be able to encrypt a string using Cenit-Polar Method + +- Solution +Cenit Polar it's a basic scout crytographic method based on replace characters +corresponding this order : +------------------------- +| C | E | N | I | T | +------------------------- +| P | O | L | A | R | +------------------------- + +The main idea is take a word and replace the characters which match in CENIT, with its equivalent on POLAR and viceversa. + +For example, if you want to encrypt the word COMPUTER, you should have to replace any character. +If some character don't have match, you should keep it in place: + +C = P +O = E +M = M +P = C +U = U +T = R +E = O +R = T + +If you want to decript the word generated, you have to do reverse the process, replacing any character which have match in POLAR, +with its equivalent on CENIT : + +P = C +E = O +M = M +C = P +U = U +R = T +O = E +T = R + +Cenit - Polar makes this alphabet table: +A B C D E F G H I J K L M N Ñ O P Q R S T U V W X Y Z +I B P D O F G H A J K N M L Ñ E C Q T S R U V W X Y Z \ No newline at end of file diff --git a/String/Cenit-Polar-Crypt/Solution.js b/String/Cenit-Polar-Crypt/Solution.js new file mode 100644 index 0000000..e5f1bfc --- /dev/null +++ b/String/Cenit-Polar-Crypt/Solution.js @@ -0,0 +1,21 @@ + +function processWord(encryptedWord){ + let splitedText = (encryptedWord.toLowerCase()).split(""); + let cenit = ["c", "e", "n", "i", "t"]; + var polar = ["p", "o", "l", "a", "r"]; + var encryptWordArray = []; + splitedText.map(function(i) { + if (cenit.indexOf(i) > -1) { + i = polar[cenit.indexOf(i)]; + encryptWordArray.push(i); + } else if (polar.indexOf(i) > -1) { + i = cenit[polar.indexOf(i)]; + encryptWordArray.push(i); + } else { + encryptWordArray.push(i); + } + }); + return encryptWordArray.join("").toUpperCase(); +} + +console.log(processWord("COMPUTER")); \ No newline at end of file diff --git a/Check_String_Palindrome/Source1.cpp b/String/Check_String_Palindrome/Source1.cpp similarity index 63% rename from Check_String_Palindrome/Source1.cpp rename to String/Check_String_Palindrome/Source1.cpp index 0fdda1d..8585e70 100644 --- a/Check_String_Palindrome/Source1.cpp +++ b/String/Check_String_Palindrome/Source1.cpp @@ -3,6 +3,7 @@ using namespace std; +//This is a function that returns a boolean value, after checking the string. bool checkStringPallindrome(string inputString); bool checkStringPallindrome(string inputString) { @@ -13,10 +14,11 @@ bool checkStringPallindrome(string inputString) { } return true; } -int main() { +void main() { - string input; - getline(cin, input); + clrscr(); //this inbuild function clears the screen + string input; //the string to check whether its palindrome or not + getline(cin, input); if (checkStringPallindrome(input)) { cout << "true" << endl; } @@ -24,6 +26,5 @@ int main() { cout << "false" << endl; } - system("pause"); - return 1; -} \ No newline at end of file + getch(); +} diff --git a/Check_String_Palindrome/problem.txt b/String/Check_String_Palindrome/problem.txt similarity index 100% rename from Check_String_Palindrome/problem.txt rename to String/Check_String_Palindrome/problem.txt diff --git a/String/FANCY/problem.txt b/String/FANCY/problem.txt new file mode 100644 index 0000000..50a5747 --- /dev/null +++ b/String/FANCY/problem.txt @@ -0,0 +1,32 @@ +Chef was reading some quotes by great people. Now, he is interested in classifying all the fancy quotes he knows. He thinks that all fancy quotes which contain the word "not" are Real Fancy; quotes that do not contain it are regularly fancy. + +You are given some quotes. For each quote, you need to tell Chef if it is Real Fancy or just regularly fancy. + +Input +The first line of the input contains a single integer T denoting the number of test cases. The description of T test cases follows. +The first and only line of each test case contains a single string S denoting a quote. + +Output +For each test case, print a single line containing the string "Real Fancy" or "regularly fancy" (without quotes). + +Constraints +1≤T≤50 +1≤|S|≤100 +each character of S is either a lowercase English letter or a space + +Subtasks +Subtask #1 (100 points): original constraints + +Example Input +2 +i do not have any fancy quotes +when nothing goes right go left + +Example Output +Real Fancy +regularly fancy + +Explanation +Example case 1: "i do not have any fancy quotes" + +Example case 2: The word "not" does not appear in the given quote. \ No newline at end of file diff --git a/String/FANCY/solution.py b/String/FANCY/solution.py new file mode 100644 index 0000000..056df26 --- /dev/null +++ b/String/FANCY/solution.py @@ -0,0 +1,16 @@ +# cook your dish here +x=int(input()) +p=0 +flag=0 +while(p +int main() +{ + int n, reversedInteger = 0, remainder, originalInteger; + printf("Enter an integer: "); + scanf("%d", &n); + originalInteger = n; + // reversed integer is stored in variable + while( n!=0 ) + { + remainder = n%10; + reversedInteger = reversedInteger*10 + remainder; + n /= 10; + } + // palindrome if orignalInteger and reversedInteger are equal + if (originalInteger == reversedInteger) + printf("%d is a palindrome.", originalInteger); + else + printf("%d is not a palindrome.", originalInteger); + + return 0; +} diff --git a/String/Palindrome/question.txt b/String/Palindrome/question.txt new file mode 100644 index 0000000..6e1fc41 --- /dev/null +++ b/String/Palindrome/question.txt @@ -0,0 +1,6 @@ + +A palindromic number (or a numeric palindrome) is a number that remains the same when its digits are reversed. +Like 16461, for example, it is "symmetrical". + +This program reverses an integer (entered by the user) using while loop. +Then, if statement is used to check whether the reversed number is equal to the original number or not. diff --git a/String/Python_Palindrome/PalindromeQues.txt b/String/Python_Palindrome/PalindromeQues.txt new file mode 100644 index 0000000..bedc45d --- /dev/null +++ b/String/Python_Palindrome/PalindromeQues.txt @@ -0,0 +1,9 @@ +Given a string, write a python function to check if it is palindrome or not. A string is said to be palindrome if reverse of the string is same as string. For example, “radar” is palindrome, but “radix” is not palindrome. + +Examples: + +Input : malayalam +Output : Yes + +Input : geeks +Output : No \ No newline at end of file diff --git a/String/Python_Palindrome/solution.py b/String/Python_Palindrome/solution.py new file mode 100644 index 0000000..aa14a75 --- /dev/null +++ b/String/Python_Palindrome/solution.py @@ -0,0 +1,22 @@ +# function which return reverse of a string +def reverse(s): + return s[::-1] + +def isPalindrome(s): + # Calling reverse function + rev = reverse(s) + + # Checking if both string are equal or not + if (s == rev): + return True + return False + + +# Driver code +s = "malayalam" +ans = isPalindrome(s) + +if ans == 1: + print("Yes") +else: + print("No") diff --git a/String/Reverse string in place/question.txt b/String/Reverse string in place/question.txt new file mode 100644 index 0000000..bce9195 --- /dev/null +++ b/String/Reverse string in place/question.txt @@ -0,0 +1,2 @@ +Write a program to reverse a String in place in Java, without using additional memory. +You cannot use any library classes or methods like e.g. StringBuilder to solve this problem. This restriction is placed because StringBuilder and StringBuffer class define a reverse() method which can easily reverse the given String. diff --git a/String/Reverse string in place/solution.java b/String/Reverse string in place/solution.java new file mode 100644 index 0000000..21999cc --- /dev/null +++ b/String/Reverse string in place/solution.java @@ -0,0 +1,74 @@ +import org.junit.Assert; +import org.junit.Test; + +/** + * Java Program to reverse a String in place, + * without any additional buffer in Java. + * + * @author WINDOWS 8 + * + */ +public class StringReversal { + + /** + * Java method to reverse a String in place + * @param str + * @return reverse of String + */ + public static String reverse(String str) { + if(str == null || str.isEmpty()){ + return str; + } + char[] characters = str.toCharArray(); + int i = 0; + int j = characters.length - 1; + while (i < j) { + swap(characters, i, j); + i++; + j--; + } + return new String(characters); + } + + /** + * Java method to swap two numbers in given array + * @param str + * @param i + * @param j + */ + private static void swap(char[] str, int i, int j) { + char temp = str[i]; + str[i] = str[j]; + str[j] = temp; + } + + @Test + public void reverseEmptyString(){ + Assert.assertEquals("", reverse("")); + } + + @Test + public void reverseString(){ + Assert.assertEquals("cba", reverse("abc")); + } + + @Test + public void reverseNullString(){ + Assert.assertEquals(null, reverse(null)); + } + + @Test + public void reversePalindromeString(){ + Assert.assertEquals("aba", reverse("aba")); + } + + @Test + public void reverseSameCharacterString(){ + Assert.assertEquals("aaa", reverse("aaa")); + } + + @Test + public void reverseAnagramString(){ + Assert.assertEquals("mary", reverse("yram")); + } +} diff --git a/String/ReverseChars/ReverseChars.java b/String/ReverseChars/ReverseChars.java new file mode 100644 index 0000000..bd0c68e --- /dev/null +++ b/String/ReverseChars/ReverseChars.java @@ -0,0 +1,26 @@ +class main { + + public static void main(String[] args){ + + System.out.println(reverseChars("These Chars will be in reverse")); + + } + + public static String reverseChars(String reverseIt) { + + int stringLength; + String itReversed; + + reverseIt = reverseIt; + + stringLength = reverseIt.length(); + itReversed = ""; + + for (int i = 1; i <= stringLength; i++){ + char backwardChars = reverseIt.charAt(stringLength - i); + + itReversed += backwardChars; + } + return itReversed; + } + } \ No newline at end of file diff --git a/String/ReverseChars/problem.txt b/String/ReverseChars/problem.txt new file mode 100644 index 0000000..bd800af --- /dev/null +++ b/String/ReverseChars/problem.txt @@ -0,0 +1 @@ +This is a program that takes a given string and loops through the string and places each character in reverse! \ No newline at end of file diff --git a/String/SplitString/Question.txt b/String/SplitString/Question.txt new file mode 100644 index 0000000..07ff26c --- /dev/null +++ b/String/SplitString/Question.txt @@ -0,0 +1,4 @@ +Given a string, break it into a vector of substrings separated by a specific +character. For example: get the string "name.midname.lastname" and the +character "." as separator, the function should return a list/vector with the +strings {"name", "midname", "lastname"} diff --git a/String/SplitString/Solution.cpp b/String/SplitString/Solution.cpp new file mode 100644 index 0000000..3ada9f2 --- /dev/null +++ b/String/SplitString/Solution.cpp @@ -0,0 +1,39 @@ +#include +#include +#include +using namespace std; + +/** Gets a string and separe through a separator _sep and returns into a + * std::vector */ +std::vector split(std::string _str, char _sep) { + std::vector v; + int begin = 0; + for (int i=0 ; i < _str.size() ; i++){ + if (_str[i] == _sep) { + v.push_back( _str.substr(begin, i-begin) ); + begin = i+1; + } + } + v.push_back(_str.substr(begin, _str.size())); + return v; +}; + + +int main() { + + string str1 = "name.midname.lastname"; + vector vecStr1 = split(str1, '.'); + for (string& s : vecStr1) { + cout << s << endl; + } + + cout << endl; + string str2 = "myname@emailservice.com"; + + vector vecStr2 = split(str2, '@'); + for (string& s : vecStr2) { + cout << s << endl; + } + + return 0; +} \ No newline at end of file diff --git a/String_Permutation/question.txt b/String/String_Permutation/question.txt similarity index 100% rename from String_Permutation/question.txt rename to String/String_Permutation/question.txt diff --git a/String_Permutation/solution.cpp b/String/String_Permutation/solution.cpp similarity index 100% rename from String_Permutation/solution.cpp rename to String/String_Permutation/solution.cpp diff --git a/String/StrongPassword/solution.py b/String/StrongPassword/solution.py new file mode 100644 index 0000000..01c2e43 --- /dev/null +++ b/String/StrongPassword/solution.py @@ -0,0 +1,55 @@ +#!/bin/python3 + +import math +import os +import random +import re +import sys + +def minimumNumber(n, password): + # Return the minimum number of characters to make the password strong + numbers = list("0123456789") + lower_case = list("abcdefghijklmnopqrstuvwxyz") + upper_case = list("ABCDEFGHIJKLMNOPQRSTUVWXYZ") + special_characters = list("!@#$%^&*()-+") + count = 0 + length = len(password) + flagn = 0 + flagl = 0 + flagu = 0 + flags = 0 + for i in password: + if i in numbers: + flagn = 1 + for i in password: + if i in lower_case: + flagl = 1 + for i in password: + if i in upper_case: + flagu = 1 + for i in special_characters: + if i in password: + flags = 1 + if flagn == 0: + count+=1 + if flagu == 0: + count+=1 + if flagl == 0: + count+=1 + if flags == 0: + count+=1 + + check = length + count + if check < 6: + count = count + (6 - (length + count)) + return count + +if __name__ == '__main__': + + n = int(input()) + + password = input() + + answer = minimumNumber(n, password) + + print(answer) diff --git a/String/StrongPassword/strongpasswordqn.txt b/String/StrongPassword/strongpasswordqn.txt new file mode 100644 index 0000000..12b2952 --- /dev/null +++ b/String/StrongPassword/strongpasswordqn.txt @@ -0,0 +1,51 @@ +Louise joined a social networking site to stay in touch with her friends. The signup page required her to input a name and a password. However, the password must be strong. The website considers a password to be strong if it satisfies the following criteria: + +Its length is at least 6. +It contains at least one digit. +It contains at least one lowercase English character. +It contains at least one uppercase English character. +It contains at least one special character. The special characters are: !@#$%^&*()-+ +She typed a random string of length n in the password field but wasn't sure if it was strong. Given the string she typed, can you find the minimum number of characters she must add to make her password strong? + +Note: Here's the set of types of characters in a form you can paste in your solution: + +numbers = "0123456789" +lower_case = "abcdefghijklmnopqrstuvwxyz" +upper_case = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" +special_characters = "!@#$%^&*()-+" +Input Format + +The first line contains an integer n denoting the length of the string. + +The second line contains a string consisting of n characters, the password typed by Louise. Each character is either a lowercase/uppercase English alphabet, a digit, or a special character. + +Constraints +1 <= n <= 100 + +Output Format + +Print a single line containing a single integer denoting the answer to the problem. + +Sample Input 0 + +3 +Ab1 +Sample Output 0 + +3 +Explanation 0 + +She can make the password strong by adding characters, for example, $hk, turning the password into Ab1$hk which is strong. + +2 characters aren't enough since the length must be at least 6. + +Sample Input 1 + +11 +#HackerRank +Sample Output 1 + +1 +Explanation 1 + +The password isn't strong, but she can make it strong by adding a single digit diff --git a/String/Subsequences/question.txt b/String/Subsequences/question.txt new file mode 100644 index 0000000..2bd6830 --- /dev/null +++ b/String/Subsequences/question.txt @@ -0,0 +1,6 @@ +Print all the subsequences of a string. A String is a subsequence of a given String, +that is generated by deleting some character of a given string without changing +its order. +Example: +Input : abc +Output : a, b, c, ab, bc, ac, abc diff --git a/String/Subsequences/subsequences.cpp b/String/Subsequences/subsequences.cpp new file mode 100644 index 0000000..9c0ec8c --- /dev/null +++ b/String/Subsequences/subsequences.cpp @@ -0,0 +1,27 @@ +//find all the sub sequences of a string +#include +using namespace std; +char output[100] = ""; + +void printSubSeq(char str[], int be, int idx) +{ + if (str[be] == '\0') + { + output[idx] = '\0'; + cout << output << endl; + return; + } + + printSubSeq(str, be + 1, idx); + output[idx] = str[be]; + printSubSeq(str, be + 1, idx + 1); +} + + +int main() { + char str[100]; + cin >> str; + + + printSubSeq(str, 0, 0); +} diff --git a/The Reversed World/Solution.cpp b/String/The Reversed World/Solution.cpp similarity index 100% rename from The Reversed World/Solution.cpp rename to String/The Reversed World/Solution.cpp diff --git a/The Reversed World/The Reversed World.txt b/String/The Reversed World/The Reversed World.txt similarity index 100% rename from The Reversed World/The Reversed World.txt rename to String/The Reversed World/The Reversed World.txt diff --git a/String/ToyObsession/problem.c b/String/ToyObsession/problem.c new file mode 100644 index 0000000..d59efa2 --- /dev/null +++ b/String/ToyObsession/problem.c @@ -0,0 +1,7 @@ +We are to input a string of characters(say, s1= XxxyXxxXXxY) and a character(say, X) that belongs to that string +( The string represents the collection of toys and the character represents the most beautiful toy) + we are to input a number that denotes the no. of beautiful toys needed ( smaller than equal to the maximum beautiful toys, say 2 ) + now we are to print the smallet length (as in no. of characters) of the substring +eg here 2 X containing substrigs are... XxxyX XxxX XX + 5 4 2 + max min therefor 2 printed. \(>o<)/ diff --git a/String/ToyObsession/solution.c b/String/ToyObsession/solution.c new file mode 100644 index 0000000..0855193 --- /dev/null +++ b/String/ToyObsession/solution.c @@ -0,0 +1,40 @@ +#include +#include +int main() +{ + long long int T,m; + scanf("%lld",&T); + for(m=0;m=0) + { + brr[i] = arr[j]-arr[j-(N-1)]+1; + i++; + j--; + } + + for(l=0;l 1){ + console.log(key); + } + } +} + +var inputVal = "Work hard and play hard and have fun at work."; + +printDuplicates(inputVal); \ No newline at end of file diff --git a/String/ginortS/Question.txt b/String/ginortS/Question.txt new file mode 100644 index 0000000..8c8b4c2 --- /dev/null +++ b/String/ginortS/Question.txt @@ -0,0 +1,16 @@ +You are given a string S + S contains alphanumeric characters only. + + Your task is to sort the string S in the following manner: + +All sorted lowercase letters are ahead of uppercase letters. +All sorted uppercase letters are ahead of digits. +All sorted odd digits are ahead of sorted even digits. + +Sample Input + +Sorting1234 + +Sample Output + +ginortS1234 \ No newline at end of file diff --git a/String/ginortS/Solution.py b/String/ginortS/Solution.py new file mode 100644 index 0000000..252193c --- /dev/null +++ b/String/ginortS/Solution.py @@ -0,0 +1,21 @@ +s=input() +upperCase=[] +lowerCase=[] +even=[] +odd=[] +for i in s: + if i >= 'A' and i<= 'Z': + upperCase.append(i) + elif i >='a' and i<= 'z': + lowerCase.append(i) + elif int(i)%2 == 0: + even.append(i) + elif int(i)%2 != 0: + odd.append(i) + +upperCase.sort() +lowerCase.sort() +even.sort() +odd.sort() + +print("".join(lowerCase+upperCase+odd+even)) diff --git a/Tree/size-of-tree-C++/problem_statement.txt b/Tree/size-of-tree-C++/problem_statement.txt new file mode 100644 index 0000000..16cfc27 --- /dev/null +++ b/Tree/size-of-tree-C++/problem_statement.txt @@ -0,0 +1 @@ +Program to find size of tree in c++ diff --git a/Tree/size-of-tree-C++/sizeoftree.cpp b/Tree/size-of-tree-C++/sizeoftree.cpp new file mode 100644 index 0000000..89b5c0a --- /dev/null +++ b/Tree/size-of-tree-C++/sizeoftree.cpp @@ -0,0 +1,37 @@ +class node +{ + public: + int data; + node* left; + node* right; +}; + +node* newNode(int data) +{ + node* Node = new node(); + Node->data = data; + Node->left = NULL; + Node->right = NULL; + + return(Node); +} + +int size(node* node) +{ + if (node == NULL) + return 0; + else + return(size(node->left) + 1 + size(node->right)); +} + +int main() +{ + node *root = newNode(1); + root->left = newNode(2); + root->right = newNode(3); + root->left->left = newNode(4); + root->left->right = newNode(5); + + cout << "Size of the tree is " << size(root); + return 0; +} diff --git a/Unknown/Acronym/instructions.txt b/Unknown/Acronym/instructions.txt new file mode 100644 index 0000000..f4f3cf7 --- /dev/null +++ b/Unknown/Acronym/instructions.txt @@ -0,0 +1,6 @@ +Acronym +Convert a phrase to its acronym. + +Techies love their TLA (Three Letter Acronyms)! + +Help generate some jargon by writing a program that converts a long name like Portable Network Graphics to its acronym (PNG). diff --git a/Unknown/Acronym/ruby_solution.rb b/Unknown/Acronym/ruby_solution.rb new file mode 100644 index 0000000..346c592 --- /dev/null +++ b/Unknown/Acronym/ruby_solution.rb @@ -0,0 +1,13 @@ +def abbreviate(string) + string_arr = string.scan(/\b\w/) + string_arr.join.upcase +end + + +# begin +# >> abbreviate("Portable Network Graphics") +# => "PNG" +# >> abbreviate("Ruby on Rails") +# => "ROR" +# >> abbreviate("GNU Image Manipulation Program") +# => "GIMP" diff --git a/CONTON/QUESTION.txt b/Unknown/CONTON/QUESTION.txt similarity index 100% rename from CONTON/QUESTION.txt rename to Unknown/CONTON/QUESTION.txt diff --git a/CONTON/solution.c b/Unknown/CONTON/solution.c similarity index 100% rename from CONTON/solution.c rename to Unknown/CONTON/solution.c diff --git a/Chefdil/ans.cpp b/Unknown/Chefdil/ans.cpp similarity index 100% rename from Chefdil/ans.cpp rename to Unknown/Chefdil/ans.cpp diff --git a/Chefdil/ques.txt b/Unknown/Chefdil/ques.txt similarity index 100% rename from Chefdil/ques.txt rename to Unknown/Chefdil/ques.txt diff --git a/Unknown/Chocolate_SPOJ/question.txt b/Unknown/Chocolate_SPOJ/question.txt new file mode 100644 index 0000000..8f45eef --- /dev/null +++ b/Unknown/Chocolate_SPOJ/question.txt @@ -0,0 +1,41 @@ +We are given a bar of chocolate composed of m*n square pieces. One should break the chocolate into single squares. Parts of the chocolate may be broken along the vertical and horizontal lines as indicated by the broken lines in the picture. + +A single break of a part of the chocolate along a chosen vertical or horizontal line divides that part into two smaller ones. Each break of a part of the chocolate is charged a cost expressed by a positive integer. This cost does not depend on the size of the part that is being broken but only depends on the line the break goes along. Let us denote the costs of breaking along consecutive vertical lines with x1, x2, ..., xm-1 and along horizontal lines with y1, y2, ..., yn-1. + +The cost of breaking the whole bar into single squares is the sum of the successive breaks. One should compute the minimal cost of breaking the whole chocolate into single squares. + + +For example, if we break the chocolate presented in the picture first along the horizontal lines, and next each obtained part along vertical lines then the cost of that breaking will be y1+y2+y3+4*(x1+x2+x3+x4+x5). + +Task +Write a program that for each test case: + +Reads the numbers x1, x2, ..., xm-1 and y1, y2, ..., yn-1 +Computes the minimal cost of breaking the whole chocolate into single squares, writes the result. +Input +One integer in the first line, stating the number of test cases, followed by a blank line. There will be not more than 20 tests. + +For each test case, at the first line there are two positive integers m and n separated by a single space, 2 <= m,n <= 1000. In the successive m-1 lines there are numbers x1, x2, ..., xm-1, one per line, 1 <= xi <= 1000. In the successive n-1 lines there are numbers y1, y2, ..., yn-1, one per line, 1 <= yi <= 1000. + +The test cases will be separated by a single blank line. + +Output +For each test case : write one integer - the minimal cost of breaking the whole chocolate into single squares. + + +Example +Input: +1 + +6 4 +2 +1 +3 +1 +4 +4 +1 +2 + +Output: +42 diff --git a/Unknown/Chocolate_SPOJ/solution.java b/Unknown/Chocolate_SPOJ/solution.java new file mode 100644 index 0000000..f04b8c2 --- /dev/null +++ b/Unknown/Chocolate_SPOJ/solution.java @@ -0,0 +1,182 @@ +import java.io.OutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.io.PrintWriter; +import java.util.Arrays; +import java.io.BufferedWriter; +import java.io.Writer; +import java.io.OutputStreamWriter; +import java.util.InputMismatchException; +import java.io.IOException; +import java.io.InputStream; + +/** + * Built using CHelper plug-in + * Actual solution is at the top + * + * @author Rishabhdeep Singh + */ +public class Main { + public static void main(String[] args) { + InputStream inputStream = System.in; + OutputStream outputStream = System.out; + InputReader in = new InputReader(inputStream); + OutputWriter out = new OutputWriter(outputStream); + MultipleTestcases solver = new MultipleTestcases(); + int testCount = Integer.parseInt(in.next()); + for (int i = 1; i <= testCount; i++) + solver.solve(i, in, out); + out.close(); + } + + static class MultipleTestcases { + public void solve(int testNumber, InputReader in, OutputWriter out) { + int n = in.nextInt(); + int m = in.nextInt(); + --n; + --m; + int[] x = in.nextIntArray(n); + int[] y = in.nextIntArray(m); + int s1 = 0, s2 = 0; + for (int i = 0; i < n; i++) { + s1 += x[i]; + } + for (int i = 0; i < m; i++) { + s2 += y[i]; + } + Arrays.sort(x); + Arrays.sort(y); + int ans = s1 + s2; + for (int i = n - 1, j = m - 1; i >= 0 && j >= 0; ) { + if (y[j] >= x[i]) { + ans += s1; + s2 -= y[j]; + --j; + } else { + ans += s2; + s1 -= x[i]; + --i; + } + } + out.println(ans); + } + + } + + static class OutputWriter { + private final PrintWriter writer; + + public OutputWriter(OutputStream outputStream) { + writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); + } + + public OutputWriter(Writer writer) { + this.writer = new PrintWriter(writer); + } + + public void close() { + writer.close(); + } + + public void println(int i) { + writer.println(i); + } + + } + + static class InputReader { + private InputStream stream; + private byte[] buf = new byte[1024]; + private int curChar; + private int numChars; + private InputReader.SpaceCharFilter filter; + + public InputReader(InputStream stream) { + this.stream = stream; + } + + public int read() { + if (numChars == -1) { + throw new InputMismatchException(); + } + if (curChar >= numChars) { + curChar = 0; + try { + numChars = stream.read(buf); + } catch (IOException e) { + throw new InputMismatchException(); + } + if (numChars <= 0) { + return -1; + } + } + return buf[curChar++]; + } + + public int nextInt() { + int c = read(); + while (isSpaceChar(c)) { + c = read(); + } + int sgn = 1; + if (c == '-') { + sgn = -1; + c = read(); + } + int res = 0; + do { + if (c < '0' || c > '9') { + throw new InputMismatchException(); + } + res *= 10; + res += c - '0'; + c = read(); + } while (!isSpaceChar(c)); + return res * sgn; + } + + public String nextString() { + int c = read(); + while (isSpaceChar(c)) { + c = read(); + } + StringBuilder res = new StringBuilder(); + do { + if (Character.isValidCodePoint(c)) { + res.appendCodePoint(c); + } + c = read(); + } while (!isSpaceChar(c)); + return res.toString(); + } + + public boolean isSpaceChar(int c) { + if (filter != null) { + return filter.isSpaceChar(c); + } + return isWhitespace(c); + } + + public static boolean isWhitespace(int c) { + return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; + } + + public String next() { + return nextString(); + } + + public int[] nextIntArray(int n) { + int[] array = new int[n]; + for (int i = 0; i < n; ++i) array[i] = nextInt(); + return array; + } + + public interface SpaceCharFilter { + public boolean isSpaceChar(int ch); + + } + + } +} + diff --git a/Fair Rations/Answer.cpp b/Unknown/Fair Rations/Answer.cpp similarity index 100% rename from Fair Rations/Answer.cpp rename to Unknown/Fair Rations/Answer.cpp diff --git a/Fair Rations/Problem Statement .txt b/Unknown/Fair Rations/Problem Statement .txt similarity index 100% rename from Fair Rations/Problem Statement .txt rename to Unknown/Fair Rations/Problem Statement .txt diff --git a/Unknown/Industrial Nim/Industrial_Nim.cpp b/Unknown/Industrial Nim/Industrial_Nim.cpp new file mode 100644 index 0000000..680db05 --- /dev/null +++ b/Unknown/Industrial Nim/Industrial_Nim.cpp @@ -0,0 +1,35 @@ +#include +using namespace std; + +vector vec; +bool nim() /* return true if the first player will win */ +{ + long long x=0; + for(int i=0;i0; +} + +long long f(long long n) /* n&3 equivalent to n%4 */ +{ + long long x=n&3; + if(x==0) return n; if(x==1) return 1; + if(x==2) return n+1; if(x==3) return 0; +} + + + +int main() +{ + long long n,x,m; + cin>>n; + while(n--) + { + cin>>x>>m; + vec.push_back(f(x+m-1)^f(x-1)); + } + if(nim()) + cout<<"tolik"< + +using namespace std; + +typedef long long int LL; +typedef vector VLL; +typedef std::complex CD; + +#define PB push_back +#define F first +#define s second +#define SZ(x) x.size() +#define ALL(a) std::begin(a), std::end(a) +#define IN_REP int _t; cin >> _t ; while(_t--) +#define IOS ios::sync_with_stdio(false);cin.tie(NULL) +#define FOR(i, a, b) for(int i=(a);i<(b);i++) +#define REP(i, n) FOR(i,0,n) +const double PI = acos(-1); +typedef std::valarray CArray; + +// Cooley–Tukey FFT (in-place) +void fft(CArray &x) { + // const size_t N = x.size(); + int N = SZ(x); + if (N <= 1) return; + + // divide + CArray even = x[std::slice(0, N / 2, 2)]; + CArray odd = x[std::slice(1, N / 2, 2)]; + + // conquer + fft(even); + fft(odd); + + // combine + // for (size_t k = 0; k < N/2; ++k){ + for (int k = 0; k < N / 2; ++k) { + CD t = std::polar(1.0, -2 * PI * k / N) * odd[k]; + x[k] = even[k] + t; + x[k + N / 2] = even[k] - t; + } +} + +// inverse fft (in-place) +void ifft(CArray &x) { + // conjugate the complex numbers + x = x.apply(std::conj); + + // forward fft + fft(x); + + // conjugate the complex numbers again + x = x.apply(std::conj); + + // scale the numbers + x /= x.size(); +} + +int main() { + IOS; + IN_REP { + int n; + cin >> n; + n++; // Given in question + int size = 2 * (1 << int(ceil(log2(n)))); + + CArray x(size), y(size); + FOR(i, size - n, size) cin >> x[i]; + fft(x); + FOR(i, size - n, size) cin >> y[i]; + fft(y); + + CArray res(size); + res = x * y; + ifft(res); + VLL ans; + REP(i, size - 1) { + ans.PB(round(res[i].real())); + } + for (int i = size - 1 - (2 * n - 1); i < size - 1; i++) { + cout << ans[i] << " "; + } + cout << endl; + } + return 0; +} diff --git a/Unknown/Strange_Food_Chain/question.txt b/Unknown/Strange_Food_Chain/question.txt new file mode 100644 index 0000000..ae9b410 --- /dev/null +++ b/Unknown/Strange_Food_Chain/question.txt @@ -0,0 +1,37 @@ +There are 3 kinds of animals A,B and C. A can eat B,B can eat C,C can eat A. It's interesting,isn't it? + +Now we have n animals,numbered from 1 to n. Each of them is one of the 3 kinds of animals:A,B,C. + +Today Mary tells us k pieces of information about these n animals. Each piece has one of the two forms below: + +1 x y: It tells us the kind of x and y are the same. +2 x y: It tells us x can eat y. +Some of these k pieces are true,some are false. The piece is false if it satisfies one of the 3 conditions below, otherwise it's true. + +X or Y in this piece is larger than n. +This piece tells us X can eat X. +This piece conflicts to some true piece before. +Input +The first line contains a single integer t.t blocks follow. + +To every block,the first line contains two integers n(1<=n<=50000) and k (1<=k<=100000). k lines follow,each contains 3 positive integers D(1<=D<=2),X,Y,separated by single spaces. + + +Output +t lines,each contains a single integer - the number of false pieces in the corresponding block. + + +Example +Sample input: +1 +100 7 +1 101 1 +2 1 2 +2 2 3 +2 3 3 +1 1 3 +2 3 1 +1 5 5 + +Sample output: +3 diff --git a/Unknown/Strange_Food_Chain/solution.cpp b/Unknown/Strange_Food_Chain/solution.cpp new file mode 100644 index 0000000..ba8dc5b --- /dev/null +++ b/Unknown/Strange_Food_Chain/solution.cpp @@ -0,0 +1,51 @@ +#include +#include + +using namespace std; + +const int N = 5e4 + 10; + +int n, k; +int par[N], lab[N]; + +int anc(int u) { + if (u == par[u]) return u; + int tmp = par[u]; + par[u] = anc(par[u]); + lab[u] = lab[tmp] + lab[u]; + return par[u]; +} + +int main() { + // freopen("input.in", "r", stdin); +// freopen("output.out", "w", stdout); + + int test; scanf("%d", &test); + while (test--) { + scanf("%d%d", &n, &k); + for (int i = 1; i <= n; ++i) { + par[i] = i; + lab[i] = 0; + } + int answer = 0; + while (k--) { + int t, x, y; scanf("%d%d%d", &t, &x, &y); + if (x > n || y > n) { answer++; continue; } + int px = anc(x), py = anc(y); + t--; + if (px == py) { + int tmp = (lab[x] - lab[y]) % 3; if (tmp < 0) tmp += 3; + if (tmp != t) answer++; + } else { + par[px] = py; + int i = (lab[x] - lab[y] - t) % 3; + lab[px] = i < 0 ? -i : -i + 3; + } + } + printf("%d\n", answer); + } + + return 0; +} + + diff --git a/Unknown/WATCHFB/Main.class b/Unknown/WATCHFB/Main.class new file mode 100644 index 0000000..539b6a7 Binary files /dev/null and b/Unknown/WATCHFB/Main.class differ diff --git a/Unknown/WATCHFB/Main.ctxt b/Unknown/WATCHFB/Main.ctxt new file mode 100644 index 0000000..b2ed59f --- /dev/null +++ b/Unknown/WATCHFB/Main.ctxt @@ -0,0 +1,19 @@ +#BlueJ class context +comment0.target=Main +comment1.params=stream +comment1.target=LCSin(java.io.InputStream) +comment2.params= +comment2.target=int\ read() +comment3.params= +comment3.target=int\ readInt() +comment4.params=c +comment4.target=boolean\ isSpaceChar(int) +comment5.params= +comment5.target=java.lang.String\ readString() +comment6.params= +comment6.target=byte\ readByte() +comment7.params= +comment7.target=long\ readLong() +comment8.params=args +comment8.target=void\ main(java.lang.String[]) +numComments=9 diff --git a/Unknown/WATCHFB/Main.java b/Unknown/WATCHFB/Main.java new file mode 100644 index 0000000..430dbef --- /dev/null +++ b/Unknown/WATCHFB/Main.java @@ -0,0 +1,195 @@ +import java.io.IOException; +import java.io.InputStream; +import java.util.InputMismatchException; +import java.util.Arrays; +class LCSin +{ + private InputStream stream; + private byte[] buf = new byte[1024]; + private int curChar; + private int numChars; + private SpaceCharFilter filter; + public LCSin(InputStream stream) { + this.stream = stream; + } + public interface SpaceCharFilter { + public boolean isSpaceChar(int ch); + } + public int read() { + if (numChars == -1) + throw new InputMismatchException(); + if (curChar >= numChars) { + curChar = 0; + try { + numChars = stream.read(buf); + } catch (IOException e) { + throw new InputMismatchException(); + } + if (numChars <= 0) + return -1; + } + return buf[curChar++]; + } + public int readInt() { + int c = read(); + while (isSpaceChar(c)) + c = read(); + int sgn = 1; + if (c == '-') { + sgn = -1; + c = read(); + } + int res = 0; + do { + if (c < '0' || c > '9') + throw new InputMismatchException(); + res *= 10; + res += c - '0'; + c = read(); + } while (!isSpaceChar(c)); + return res * sgn; + } + public boolean isSpaceChar(int c) { + if (filter != null) + return filter.isSpaceChar(c); + return c==' '||c=='\n'|| c == '\r' || c == '\t' || c == -1; + } + public String readString() { + int c = read(); + while (isSpaceChar(c)) + c = read(); + StringBuilder res = new StringBuilder(); + do { + res.appendCodePoint(c); + c = read(); + } + while (!isSpaceChar(c)); + return res.toString(); + } + public byte readByte() { + int c = read(); + while (isSpaceChar(c)) + c = read(); + byte res = 0; + do { + if (c < '0' || c > '9') + throw new InputMismatchException(); + res *= 10; + res += c - '0'; + c = read(); + } while (!isSpaceChar(c)); + return res; + } + public long readLong() { + int c = read(); + while (isSpaceChar(c)) + c = read(); + int sgn = 1; + if (c == '-') + { + sgn = -1; + c = read(); + } + long res = 0; + do + { + if (c < '0' || c > '9') + throw new InputMismatchException(); + res *= 10; + res += c - '0'; + c = read(); + } + while (!isSpaceChar(c)); + return res * sgn; + } +} + +public class Main +{ + public static void main(String args[]) + { + LCSin br= new LCSin(System.in); + int test= br.readInt(); + StringBuilder sb=new StringBuilder(); + for(int testcase= 0; testcaseprevmax) + { + System.out.println("NO"); + prevmax= max; + prevmin= min; + res= false; + continue; + } + + if((max>prevmax)&&(minprevmax)&&(min==prevmax)) + { + + System.out.println("NO"); + res= false; + prevmax= max; + prevmin= min; + continue; + + } + } + } + } +} \ No newline at end of file diff --git a/Unknown/WATCHFB/WATCHFB.txt b/Unknown/WATCHFB/WATCHFB.txt new file mode 100644 index 0000000..68b7e03 --- /dev/null +++ b/Unknown/WATCHFB/WATCHFB.txt @@ -0,0 +1,58 @@ +The solution given is created by the author and using it without prior written permission from the author can lead to legal actions. +Please contact amcs1729@gmail.com for any queries + + + +https://www.codechef.com/problems/WATCHFB + +Chef and his son Chefu want to watch a match of their favourite football team playing against another team, which will take place today. + +Unfortunately, Chef is busy in the kitchen preparing lunch, so he cannot watch the match. Therefore, every now and then, Chef asks Chefu about the current scores of the teams and Chefu tells him the score. However, Chefu sometimes does not specify the teams along with the score — for example, he could say "the score is 3 to 6", and there is no way to know just from this statement if it was their favourite team or the other team that scored 6 goals; in different statements, the order of teams may also be different. Other times, Chefu specifies which team scored how many goals. + +Chef asks for the score and receives a reply N times. There are two types of replies: + +1 A B: their favourite team scored A goals and the other team scored B goals +2 A B: one team scored A goals and the other scored B goals +Chef is asking you to help him determine the score of his favourite team after each of Chefu's replies. After each reply, based on the current reply and all previous information (but without any following replies), tell him whether it is possible to certainly determine the number of goals scored by his favourite team. + +Input +The first line of the input contains a single integer T denoting the number of test cases. The description of T test cases follows. +The first line of each test case contains a single integer N. +The following N lines describe Chefu's replies in the format described above. +Output +For each of Chefu's replies, print a single line containing the string "YES" if it is possible to determine the score of Chef's favourite team after this reply or "NO" if it is impossible. + +Constraints +1=T=100 +1=N=104 +0=A,B=109 +the sum of N over all test cases does not exceed 105 +there is at least one valid sequence of scored goals consistent with all replies +Subtasks +Subtask #1 (100 points): original constraints + +Example Input +1 +6 +2 0 1 +1 3 1 +2 2 4 +2 5 6 +2 8 8 +2 9 10 +Example Output +NO +YES +YES +NO +YES +NO +Explanation +Example case 1: + +Reply 1: Chef cannot know who scored the first goal. +Reply 2: Chefu told Chef that their favourite team has scored 3 goals so far. +Reply 3: Chef can conclude that his favourite team has scored 4 goals, since it already scored 3 goals earlier. +Reply 4: the favourite team could have scored 5 or 6 goals, but there is no way to know which option is correct. +Reply 5: since there is a tie, Chef knows that his favourite team has scored 8 goals. +Reply 6: again, Chef cannot know if his favourite team has scored 9 or 10 goals. diff --git a/chusky_adventurer/problem_statement.txt b/Unknown/chusky_adventurer/problem_statement.txt similarity index 100% rename from chusky_adventurer/problem_statement.txt rename to Unknown/chusky_adventurer/problem_statement.txt diff --git a/chusky_adventurer/solution.cpp b/Unknown/chusky_adventurer/solution.cpp similarity index 100% rename from chusky_adventurer/solution.cpp rename to Unknown/chusky_adventurer/solution.cpp diff --git a/Unknown/chusky_hunger/problem_statement.txt b/Unknown/chusky_hunger/problem_statement.txt new file mode 100644 index 0000000..5625b7b --- /dev/null +++ b/Unknown/chusky_hunger/problem_statement.txt @@ -0,0 +1,41 @@ +Chusky and Hunger +========================= + +Chusky lives in Dogland and as everyone in this city, he loves the local dish: Aguadito. There is a unique Polleria (a really nice place to eat Aguadito) in Dogland, hence, this eatery is really selective with its customers. To eat in the Polleria, Chusky must solve the next task: Given D boxes, each one has all integer numbers between L_i and R_i (1 <= i <= D) inclusive, indicate the K-th lowest unique existing element. Because there is big queue waiting after Chusky, he has just some seconds to give the correct answer, otherwise he will not be able to eat in the Polleria and will eat some boiled potatoes that has at home (he does not like it too much) . +Help Chusky to eat an Aguadito. + +Input +===== + +The first line of the input contains a number T (1 <= T <= 100) indicating the number of test cases. Each test case follows the next format: +The first line of each test case contains a number D (1 <= D <= 100) representing the number of boxes Chusky receives, the second line contains a number K (1 <= K <= 10 ^ 15) representing the K- th number Chusky must guess, then D lines follows, each one in has two integers L_i and R_i (1 <= L_i <= R_i <= 10 ^ 15) representing that box i has all integers between L_i and R_i (1 <= i <= D) inclusive. + +Output +===== + +For each test case, print the K-th lowest number between all boxes. Print -1 if no K-th lowest number exists. + +Example +====== + +Input + +2 +3 +2 +3 6 +3 4 +11 13 +1 +7 +1 5 + +Output + +4 +-1 + +Explanation: + +For the first test case, the first box has numbers {3, 4, 5, 6}, the second one has {3, 4} and the last one has {11, 13}, then all existing numbers are {3, 4 , 5, 6, 11, 13} and the 2nd lowest number is 4. In the second case the box has numbers {1, 2, 3, 4, 5}, thus there is no 7th lowest element. + diff --git a/Unknown/chusky_hunger/solution.cpp b/Unknown/chusky_hunger/solution.cpp new file mode 100644 index 0000000..4a65e79 --- /dev/null +++ b/Unknown/chusky_hunger/solution.cpp @@ -0,0 +1,75 @@ +#include +//#define DEBUG +using namespace std; +typedef vector < int > vi; +typedef pair < long long int, long long int > pii; +typedef vector < pii > vii; +typedef long long int i64; +int d; +i64 k; +bool byPairs(pii left, pii right) +{ + if(left.first != right.first) + return left.first < right.first; + return left.second < right.second; +} +i64 sol(vii &nums) +{ + sort(nums.begin(), nums.end(), byPairs); + + i64 ans = -1ll; + i64 last = -1ll; + int i = 0; + while(k>0ll && i < (int)nums.size()) + { + if(last < nums[i].first) // no overlap + { + i64 len = nums[i].second - nums[i].first + 1ll; +#ifdef DEBUG + + cout< " <>d>>k; + vii nums = vii(); + for(int i = 0; i < d; i++) + { + pii x; + cin>>x.first>>x.second; + nums.push_back(x); + } + cout<< sol(nums) <