diff --git a/.DS_Store b/.DS_Store new file mode 100644 index 00000000..de79271c Binary files /dev/null and b/.DS_Store differ diff --git a/.travis.yml b/.travis.yml index b164a023..1dd014fe 100644 --- a/.travis.yml +++ b/.travis.yml @@ -35,4 +35,4 @@ matrix: notifications: on_success: change - on_failure: change # `always` will be the setting once code changes slow down + on_failure: change # `always` will be the setting once code changes fast diff --git a/ASSIGNMENTS/12 hr to 24 hr format b/ASSIGNMENTS/12 hr to 24 hr format new file mode 100644 index 00000000..b20d1050 --- /dev/null +++ b/ASSIGNMENTS/12 hr to 24 hr format @@ -0,0 +1,26 @@ +Given a time in 12-hour AM/PM format, convert it to military (24-hour) time. + +Note: Midnight is 12:00:00AM on a 12-hour clock, and 00:00:00 on a 24-hour clock. Noon is 12:00:00PM on a 12-hour clock, and 12:00:00 on a 24-hour clock. + +Function Description + +Complete the timeConversion function in the editor below. It should return a new string representing the input time in 24 hour format. + +timeConversion has the following parameter(s): + +s: a string representing time in 12-hour format +Input Format + +A single string containing a time in -hour clock format (i.e. hh:mm:ss AM or hh:mm:ss PM ), where 01<=hh<=12 and 00<=mm,ss<=59 . + +Constraints + +All input times are valid +Output Format + +Convert and print the given time in 24-hour format, where 00<=hh<=24 . + +Sample Input 0: +07:05:45PM +Sample Output 0: +19:05:45 diff --git a/ASSIGNMENTS/3rd Largest number in Unsorted Array.md b/ASSIGNMENTS/3rd Largest number in Unsorted Array.md new file mode 100644 index 00000000..92bde715 --- /dev/null +++ b/ASSIGNMENTS/3rd Largest number in Unsorted Array.md @@ -0,0 +1,3 @@ +Use any language & write a program that takes an unsorted array in input & returns the third largest number form Array as output. + +Make sure, Solution has minimum complexity possible. diff --git a/ASSIGNMENTS/A Game of Robots.md b/ASSIGNMENTS/A Game of Robots.md new file mode 100644 index 00000000..7248f5a3 --- /dev/null +++ b/ASSIGNMENTS/A Game of Robots.md @@ -0,0 +1,39 @@ +You've built some robots and placed them on an one dimensional grid with n cells. Their arrangement is given by a string s of length n. Each character of the string is either '.' or a digit in the range '0' to '9'. A '.' represents that there is no robot at that cell initially. A digit represents a robot initially in that cell. Specifically, the digit x denotes that the range of the robot is from x cells to the left of its starting point to x cells to the right of its starting point. + +For example, suppose the 7th character of the string is 3, then that means that there is a robot starting from the 7th cell, and its range is from the 4th cell (7 - 3 = 4) to the 10th cell (7 + 3 = 10) (both end points inclusive). The robots can move only within their range, and even if their range allows it, they cannot move out of the grid. + +You want to play a game with these robots. Before starting the game, you can give each robot a starting direction (either left or right). When the robot is initialized with a direction, it will move in that direction until it can (ie. it can't go past its range, and neither can it go outside the grid) and will reverse its direction and go as far as possible in that direction, and then reverse, and so. It will keep going like this forever. Assume that the change of direction happens instantaneously. + +But the catch is that each of the robots can start their journey at any time. They don't all have to start at the same second. It won't stop once it starts moving though. And they all move at the same speed of one cell per second, once they start. + +The robots have gained consciousness, and have begun questioning their purpose in life. So given a chance, they will collide with each other and end their misery. They can coordinate with each other as well and decide when they should start their journeys. Two robots are said to have collided if they are at the same cell at the same moment. + +You are wondering whether it is possible to give the robots the initial directions in such a way that no robots collide with each other (ie. they'll all be safe), or if no matter what initial directions you give, some of them will end up colliding with each other (ie. unsafe). +

+Input +The first line of the input contains an integer T denoting the number of test cases. The description of the test cases follows. +The only line of each test case contains a string s.
+Output +For each test case, output a single line containing "safe" or "unsafe" (without quotes).
+Constraints
+1=T=3*104
+1= length of s=50
+s[i] will be one of the following characters {'.', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'}
+ Example +Input +4 +.... +.2..... +.2...2.. +1.1.1.
+Output +safe +safe +unsafe +unsafe
+Explanation +Example 1: No robots. Everything is safe. + +Example 2: Only one robot. Everything safe. To give an example of its movement, suppose you give it the starting direction as left and suppose it decides to start moving at time = 5 seconds. Then till t = 5, it is at cell 2 (its starting position, 1-based indexing). At t = 6, it is at cell 1. At t = 7, it is at cell 2, at t = 8, it will be at cell 3, at t = 9 it will be at cell 4 and at t = 10 it will be at cell 3. And so on. + +Example 3: No matter what initial directions you give, the two robots can coordinate and start their journeys such that they collide at the cell 4. diff --git a/ASSIGNMENTS/ACIIIproduct.txt b/ASSIGNMENTS/ACIIIproduct.txt index e0aee43e..a5e11286 100644 --- a/ASSIGNMENTS/ACIIIproduct.txt +++ b/ASSIGNMENTS/ACIIIproduct.txt @@ -8,4 +8,12 @@ Output : 6059 73 * 83 = 6059 Input : str = "GfG" -Output : 514182 \ No newline at end of file +Output : 514182 + + +Input : str = "ab" +Output : 9506 + +Input: str="AB" +Output: 4290 + diff --git a/ASSIGNMENTS/ATM problem.md b/ASSIGNMENTS/ATM problem.md index 1d5a70d7..563750f4 100644 --- a/ASSIGNMENTS/ATM problem.md +++ b/ASSIGNMENTS/ATM problem.md @@ -34,3 +34,5 @@ Explanation Example case 1: The ATM machine initially contains 10 units of money. The first person comes and withdraws 3 units, so the amount remaining in the machine is 7. Then the second person withdraws 5 units and the remaining amount is 2. The third person wants to withdraw 3 units, but since there are only 2 units of money in the machine, it throws an error and the third person must leave without getting anything. Then the fourth person withdraws 2 units, which leaves nothing in the machine, so the last person does not get anything. Example case 2: The ATM machine initially contains 6 units of money, so it cannot give anything to the first and second person. When the third person comes, it gives them all the money it has, so the last person does not get anything either. + +The operating system and compatibility of that server matters the working of an ATM machine. diff --git a/ASSIGNMENTS/Advanced prob_FizzBuzz b/ASSIGNMENTS/Advanced prob_FizzBuzz new file mode 100644 index 00000000..320ac0fb --- /dev/null +++ b/ASSIGNMENTS/Advanced prob_FizzBuzz @@ -0,0 +1,45 @@ +Q)FizzBuzz +--------------------------------------------------------------------------------- + +Write a program that prints the numbers in the given range. But for multiples of three print “Fizz” instead of the number and for the multiples of five print “Buzz”. For numbers which are multiples of both three and five print “FizzBuzz”. Print a new line after each string or number. +Input Format First line will be the number of testcases, T. Next line will have T integers, denoted by N. +Output Format For each testcase, print the number from 1 to N. But follow the rules given in the problem statement. +Constraints +1 <= T <= 10 +N is an integer. +Please read the below instructions carefully +You can choose any language from the given list to write your solution. +All input to the programming solution is to STDIN and output is to STDOUT. +You don't have to manually give the input to your program, just take the input from STDIN and the code evaluation engine will provide the input to your program. +For example if you are coding in C, and the first input is an integer then simply do scanf('%d', &i) assuming you are reading that integer to a variable named i. Similarly if you are using C++ simply do cin >> i +There are two different type of test cases. First type is the sample input and output for which you know both the input and output. You can look at them under the problem statement. +When you click Compile and Test the code will be compiled and tested only on the sample input that is shown to you. Compile and Test is for you to understand if you solution is compiling and running against the sample input. 5 When you click submit, your code will be judged on multiple test cases which are hidden. These tests are not available for you to see them so you will not know the input on which your code will be tested. But it is assured that all inputs will be in the given constraint limit and in the given format as stated in the problem statement. +In order for your code to get accepted, it must clear all the judge test cases. In cases where partial marking is allowed, you will awarded partial marks for the number of test cases your solution passes. +Please note that getting green mark when you hit 'Compile and Test' does not indicate anything on the correctness of your program. It just indicates that your code correctly compiled and ran successfully against the sample input. It can still fail for other test inputs that visible to you. +Do not output anything, except what it is asked for in the output section. Note that you have to output only in the way that is mentioned. Any extra strings in the output will be treated as wrong answer. Even an extra space can lead to the answer not being accepted. +Don't assume any constraints on the input based on the sample input that you see, the actual test cases will be much larger in size. But they will always be within the constraints mentioned in the problem. +To understand how the code is evaluated visit the judge page. There is also a sample code in each language there. +To further understand how the judge works, look at one of the actual test input file and the corresponding expected output for this problem + + +Sample Input Sample Output + +2 +3 15 1 + 2 + Fizz + 1 + 2 + Fizz + 4 + Buzz + Fizz + 7 + 8 + Fizz + Buzz + 11 + Fizz + 13 + 14 + FizzBuzz diff --git a/ASSIGNMENTS/ArmstrongNumber.txt b/ASSIGNMENTS/ArmstrongNumber.txt new file mode 100644 index 00000000..5ef67022 --- /dev/null +++ b/ASSIGNMENTS/ArmstrongNumber.txt @@ -0,0 +1,22 @@ +**Find given number is an armstrong number or not? +Armstrong Number +Input Number: 153 + 1=>1*1*1=1 + 5=>5*5*5=125 + 3=> 3*3*3=27 + Sum=>1+125+27=153 + i.e; 153 is an armstrong number + + Output: +153 is an armstrong number. + +Input Number:125 + 1=>1*1*1=1 + 2=> 2*2*2=8 + 5=>5*5*5=125 + Sum=>1+8+125!=125 + i.e; 153 is not an armstrong number + + Output: +125 is not an armstrong number. + diff --git a/ASSIGNMENTS/Beginners Problem 2.0 b/ASSIGNMENTS/Beginners Problem 2.0 new file mode 100644 index 00000000..42eac9a4 --- /dev/null +++ b/ASSIGNMENTS/Beginners Problem 2.0 @@ -0,0 +1,14 @@ +# Beginners Problem 2.0 +Our juniors has just entered in coding community. Their first task is to find the frequency of Best numbers present in given list of elements. Best numbers are numbers which are divisible by 2. + +SAMPLE INPUT +2 +5 +1 2 3 4 5 +3 +1 3 5 +SAMPLE OUTPUT +2 +0 +Explanation +Number of test cases=2 1st test case, number of elements =5 Best numbers are 2 , 4 ; frequency=2 2nd test case, number of elements =3 No Best numbers diff --git a/ASSIGNMENTS/Bishu and his Girlfriend.md b/ASSIGNMENTS/Bishu and his Girlfriend.md new file mode 100644 index 00000000..72c25396 --- /dev/null +++ b/ASSIGNMENTS/Bishu and his Girlfriend.md @@ -0,0 +1,28 @@ +Bishu and his Girlfriend + +There are N countries {1,2,3,4....N} and N-1 roads(i.e depicting a tree) + +Bishu lives in the Country 1 so this can be considered as the root of the tree. + +Now there are Q girls who lives in various countries (not equal to 1) . + +All of them want to propose Bishu.But Bishu has some condition. + +He will accept the proposal of the girl who lives at minimum distance from his country. + +Now the distance between two countries is the number of roads between them. + +If two or more girls are at the same minimum distance then he will accept the proposal of the girl who lives in a country with minimum id. + +No two girls are at same country. + +Input: First line consists of N,i.e number of countries Next N-1 lines follow the type u v which denotes there is a road between u and v. Next line consists of Q Next Q lines consists of x where the girls live. + +Output: Print the id of the country of the girl who will be accepted. + +Help Him!!!!! + +contraints: 2<=N<=1000 1<=u,v<=N 1<=Q<=(N-1) + +-------------------------------------------------------- +Author: https://www.hackerearth.com/@satishgpta007 diff --git a/ASSIGNMENTS/CompareLists b/ASSIGNMENTS/CompareLists index fb8c619b..d60b736a 100644 --- a/ASSIGNMENTS/CompareLists +++ b/ASSIGNMENTS/CompareLists @@ -1 +1,10 @@ Write a Python program to compare two unordered lists (not sets). + +The program are: + +from collections import Counter +def compare_lists(x, y): + return Counter(x) == Counter(y) +n1 = [20, 10, 30, 10, 20, 30] +n2 = [30, 20, 10, 30, 20, 50] +print(compare_lists(n1, n2)) diff --git a/ASSIGNMENTS/Directions Reduction.md b/ASSIGNMENTS/Directions Reduction.md new file mode 100644 index 00000000..3e9e47fe --- /dev/null +++ b/ASSIGNMENTS/Directions Reduction.md @@ -0,0 +1,73 @@ +# Directions Reduction + +## **Once upon a time, on a way through the old wild west,…** +… a man was given directions to go from one point to another. The directions were "NORTH", "SOUTH", "WEST", "EAST". Clearly "NORTH" and "SOUTH" are opposite, "WEST" and "EAST" too. Going to one direction and coming back the opposite direction is a needless effort. Since this is the wild west, with dreadfull weather and not much water, it's important to save yourself some energy, otherwise you might die of thirst! + +## How I crossed the desert the smart way. + +The directions given to the man are, for example, the following: + +``` +["NORTH", "SOUTH", "SOUTH", "EAST", "WEST", "NORTH", "WEST"]. +``` + +or + +``` +{ "NORTH", "SOUTH", "SOUTH", "EAST", "WEST", "NORTH", "WEST" }; +``` + +or (haskell) + +``` +[North, South, South, East, West, North, West] +``` + +You can immediatly see that going "NORTH" and then "SOUTH" is not reasonable, better stay to the same place! So the task is to give to the man a simplified version of the plan. A better plan in this case is simply: + +``` +["WEST"] +``` + +or + +``` +{ "WEST" } +``` + +or (haskell) + +``` +[West] +``` + +or (rust) + +``` +[WEST]; +``` + +## Other examples: + +In `["NORTH", "SOUTH", "EAST", "WEST"]`, the direction `"NORTH" + "SOUTH"` is going north and coming back right away. What a waste of time! Better to do nothing. + +The path becomes `["EAST", "WEST"]`, now `"EAST"` and `"WEST"` annihilate each other, therefore, the final result is `[]` (nil in Clojure). + +In ["NORTH", "EAST", "WEST", "SOUTH", "WEST", "WEST"], "NORTH" and "SOUTH" are not directly opposite but they become directly opposite after the reduction of "EAST" and "WEST" so the whole path is reducible to ["WEST", "WEST"]. + +## Task + +Write a function `dirReduc` which will take an array of strings and returns an array of strings with the needless directions removed (W<->E or S<->N side by side). + +The Haskell version takes a list of directions with `data Direction = North | East | West | South`. The Clojure version returns nil when the path is reduced to nothing. The Rust version takes a slice of `enum Direction {NORTH, SOUTH, EAST, WEST}`. + +## Examples +``` +dirReduc(["NORTH", "SOUTH", "SOUTH", "EAST", "WEST", "NORTH", "WEST"]) => ["WEST"] +dirReduc(["NORTH", "SOUTH", "SOUTH", "EAST", "WEST", "NORTH"]) => [] +``` + +## Note +Not all paths can be made simpler. The path ["NORTH", "WEST", "SOUTH", "EAST"] is not reducible. "NORTH" and "WEST", "WEST" and "SOUTH", "SOUTH" and "EAST" are not directly opposite of each other and can't become such. Hence the result path is itself : ["NORTH", "WEST", "SOUTH", "EAST"]. + +_Reference:_ https://www.codewars.com/kata/directions-reduction/ \ No newline at end of file diff --git a/ASSIGNMENTS/Don't Jump.md b/ASSIGNMENTS/Don't Jump.md new file mode 100644 index 00000000..6449a23e --- /dev/null +++ b/ASSIGNMENTS/Don't Jump.md @@ -0,0 +1,24 @@ +Chandu and Kundu are bored of dramatic games around. As they are very good friends and scholars they decided to discover a new game. +In total they had N number of marbles with value inscribed on each of them from 1 to N. +Chandu being from royal family has a treasure box. He emptied the box for the game to proceed. + +The game rule involved following operations : +- Operation C : Chandu places a marble in the box. Each different marble can move inside the box only once. +- Operation K : Kundu removes last entered marble from the box and notes down it's value on a chart. + +They were deciding further rules when a third person Mr. Chirp comes as a spoiler of the game. Chirp gives them a number N which is the maximum value inscribed among all marbles, and a sequence P. P can possibly be empty. In that case, in input an empty line would be there. + +Also, he added following restriction : +- Kundu can perform operation K to take out a marble M only when all the marbles from values 1 to M-1 have went in the box before. + +Mr. Chirp kept on chirping and told Chandu and Kundu to generate the sequence of C's and K's for the chart to get filled by pattern P. +Now, you have to help these kids before they jump out of their window in frustration. + + +SAMPLE INPUT +41 +6 11 8 + + +SAMPLE OUTPUT +CCCCCCKCCCCCKKKK \ No newline at end of file diff --git a/ASSIGNMENTS/First_Hundred_natural_no_cubic.md b/ASSIGNMENTS/First_Hundred_natural_no_cubic.md new file mode 100644 index 00000000..f37545a6 --- /dev/null +++ b/ASSIGNMENTS/First_Hundred_natural_no_cubic.md @@ -0,0 +1 @@ +Task : program to find out cube of first hundred natural no's(individually) in Python. diff --git a/ASSIGNMENTS/Hello world.md b/ASSIGNMENTS/Hello world.md index 995b7b62..061ae2b8 100644 --- a/ASSIGNMENTS/Hello world.md +++ b/ASSIGNMENTS/Hello world.md @@ -1,4 +1,4 @@ -This is a simple challenge to help you practice. +/*This is a simple challenge to help you practice. Input Format @@ -7,3 +7,10 @@ You do not need to read any input in this challenge. Output Format Print "Hello world". +*/ +#include +int main() +{ +printf("Hello world"); +return 0; +} diff --git a/ASSIGNMENTS/HelpKatekar.md b/ASSIGNMENTS/HelpKatekar.md new file mode 100644 index 00000000..457db5b3 --- /dev/null +++ b/ASSIGNMENTS/HelpKatekar.md @@ -0,0 +1,25 @@ +Sartaj's partner, Katekar is very loyal to his job and also to Sartaj. In his dedication towards his duty, he often neglects his wife who ends up alone and sad. Today, katekar has promised his wife to reach home early and spend time with her. However he and Sartaj are stuck with a problem which may decide the future of Mumbai. As Katekar cannot leave in such a situation, help him to solve the problem so that he can get back to his wife. + +You are given an array A of length N. You need to detemine the largest subsequence B from the given array A such that for any index i and j in B if B[i]>B[j] then the frequency of B[i] is strictly greater than the frequency of B[j]. + +Input format : + + First line : a single integer N denoting the length of given array. + Second line : N space seperated integers denoting the array elements. + +Output fromat : + + Print the length of largest subsequence B that can be formed. + +Constraints : + + 1≤N≤1000 + 1≤A[i]≤1000000 + +Sample Input:- +5 +1 2 2 3 3 + + +Sample Output:- +3 diff --git a/ASSIGNMENTS/LCS.cpp b/ASSIGNMENTS/LCS.cpp new file mode 100644 index 00000000..c4a3ea52 --- /dev/null +++ b/ASSIGNMENTS/LCS.cpp @@ -0,0 +1,55 @@ +#include + +using namespace std; + +int main(int argc, char** argv) { + + int s1[] = {1, 0, 1, 1, 0}; // m = 5 + int s2[] = {0, 1, 0, 0, 1, 0}; // n = 6 + + + int arr[6][7]; + string dir[6][7]; + + for(int i = 0; i < 6; i ++) { + for(int j = 0; j < 7; j++) { + arr[i][j] = 0; + } + } + + for(int i = 1; i < 6; i ++) { + for(int j = 1; j < 7; j++) { + if(s1[i-1] == s2[j-1]) { + arr[i][j] = arr[i-1][j-1] + 1; + dir[i][j] = "diagonal"; + } else { + if(arr[i][j-1] == arr[i-1][j]) { + arr[i][j] = arr[i][j-1]; + dir[i][j] = "both"; + } else if(arr[i][j-1] > arr[i-1][j]) { + arr[i][j] = arr[i][j-1]; + dir[i][j] = "left"; + } else { + arr[i][j] = arr[i-1][j]; + dir[i][j] = "up"; + } + } + } + } + + for(int i = 1; i < 6; i ++) { + for(int j = 1; j < 7; j++) { + cout << arr[i][j] << " "; + } + cout << endl; + } + + for(int i = 1; i < 6; i ++) { + for(int j = 1; j < 7; j++) { + cout << dir[i][j] << " "; + } + cout << endl; + } + + return 0; +} diff --git a/ASSIGNMENTS/Manhattan distance b/ASSIGNMENTS/Manhattan distance new file mode 100644 index 00000000..90dd14ca --- /dev/null +++ b/ASSIGNMENTS/Manhattan distance @@ -0,0 +1,34 @@ +Manyland is a grid with N rows and M columns. Each cell of this grid is either empty or contains a house. The distance between +a pair of houses is the Manhattan distance between the cells containing them. + +For each d between 1 and N+M−2 inclusive, Danny wants to calculate the number of unordered pairs of distinct houses with distance equal +to d. Please help him! + + +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 two space-separated integers N and M. +N lines follow. For each i (1≤i≤N), the i-th of these lines contains a binary string with length M; for each j (1≤j≤M), +the j-th character of this string is '1' if the cell in the i-th row and j-th column contains a house or '0' if it is empty. + + +Output +For each test case, print a single line containing N+M−2 space-separated integers. For each valid i, the i-th integer +should denote the number of pairs with distance i. + + +Constraints +1≤T≤3 +2≤N,M≤300 + + +Example Input +1 +3 4 +0011 +0000 +0100 + + +Example Output +1 0 1 1 0 diff --git a/ASSIGNMENTS/Question for practice b/ASSIGNMENTS/Question for practice new file mode 100644 index 00000000..73bedab3 --- /dev/null +++ b/ASSIGNMENTS/Question for practice @@ -0,0 +1,17 @@ +# Question for practice +Joseph came across the next question , which asked him to check if the word spelt the same backwards . + +A simple enough question , he started to solve the question only to be constrained by language allowed. + +(Input a string (of character <80) from the user and print whether the string is a palindrome or not. + +Assume no spaces between characters.) Sample Input: eergreejj + +Sample Output: Not At All + +(If it is a palindrome - print "Indeed") + +SAMPLE INPUT +eergreejj +SAMPLE OUTPUT +Not At All diff --git a/ASSIGNMENTS/ReadFile b/ASSIGNMENTS/ReadFile index c7f01af1..abd23b5a 100644 --- a/ASSIGNMENTS/ReadFile +++ b/ASSIGNMENTS/ReadFile @@ -1 +1 @@ -This program should read text from a file and stores it in a string until enter 'newline' character is encountered. +This program should read text from a file and stores it in a string until enter 'newline' character is encountered/assigned. diff --git a/ASSIGNMENTS/Reduction Game.md b/ASSIGNMENTS/Reduction Game.md new file mode 100644 index 00000000..e100cc3d --- /dev/null +++ b/ASSIGNMENTS/Reduction Game.md @@ -0,0 +1,36 @@ +You are playing a game called the Reduction Game. This game is played on an array a with n integers. You also have another integer k with you. The following operation will be made repeatedly on this array: + +Choose any two elements ai,aj such that i?j, and min(ai,aj)>k. Decrease both ai and aj by one. +This operation should be applied to the array if it's possible to apply it. But if there are multiple valid choices of ai and aj, you can choose which ones to do first and so on. The aim is to apply the operations in such a way, so as to maximize the sum of the elements in the array at the end. Your task is to find the maximum possible sum of the final array. + +Input +The first line of the input contains an integer T denoting the number of test cases. The description of the test cases follows. +The first line of each test case contains two integers n,k denoting the number of elements in the array a. +The second line contains n space-separated integers denoting the array a. +Output: +For each test case, output an integer corresponding to the maximum possible sum of the remaining array in a new line. + +Constraints +1=T=5000 +1=n=50 +1=ai,k=50000
+Sample Input: +3 +2 1 +1 2 +2 1 +2 2 +3 1 +2 3 2
+Sample Output: +3 +2 +5
+Explanation
+Example 1: The initial array is [1, 2]. In this case, there are no two elements > 1. So, no operations can be made, and this is the only final array possible. And the sum of this is 3, and hence that is the answer. + +Example 2: The initial array is [2, 2]. You can decrease 1 from both the elements and get the array to [1, 1]. This is the only valid pair available, so you are forced to reduce this pair. After doing so, you can't make any more operations. So, [1, 1] is the only final array achievable, and it's sum is is 2. + +Example 3: The initial array is [2, 3, 2]. You could pick the first two elements and reduce them, to get the array [1, 2, 2]. Now, you have to choose the last two elements and reduce them, to get [1, 1, 1]. This is one possible final array, whose sum is 3. + +Instead, you could initially have chosen the first and third element and reduced them to get [1, 3, 1]. After this, there is no operation possible, and so this is another final array achievable. Its sum is 5, and there is nothing better than this. Hence the answer is 5. diff --git a/ASSIGNMENTS/ReductionGame.py b/ASSIGNMENTS/ReductionGame.py new file mode 100644 index 00000000..843e0bcb --- /dev/null +++ b/ASSIGNMENTS/ReductionGame.py @@ -0,0 +1,73 @@ +#Author: Nirupam Gunwal + +# Issue Solve Reduction Game #573 + +#Detailed Solution to the Problem Described at https://github.com/hackerearthclub/CODE2RACE/blob/master/ASSIGNMENTS/Reduction%20Game.md +# in Python 3 + + + +def answer(arr): + + ntestcase = arr[0] + + narr = [] + k = [] + sumfinal = [] + + + arrn = [] + loopcount = len(arr) + i = 1 + while i < loopcount : + + n = arr[i] + narr.append(n) + k.append(arr[i+1]) + arrlist = arr[i + 2 : i + n + 2] + arrn.append(arrlist) + i = i + n + 2 + + + for i in range(ntestcase): + sortedarray = sorted(arrn[i]) + + j = 0 + while j < len(sortedarray) - 1: + + while min(sortedarray[j],sortedarray[j+1]) > k[i]: + sortedarray[j] = sortedarray [j] - 1 + sortedarray[j+1] = sortedarray [j+1] - 1 + + j = j + 1 + + sumfinal.append(sum(sortedarray)) + + + print("Output:") + print(sumfinal) + + +def main(): + + print("Use Test Case OR Input Your Own .(y for Your Own Input else Test Case will be considered)") + + if(str(input()) == 'y'): + print("Test Case Selected") + arr = [3,2,1,1,2,2,1,2,2,3,1,2,3,2] + + else: + + print("Input Selected .Give the input according to the question and use dont use spaces to seperate numbers :") + print(" Input Should be of the format like this : 32112212231232 (No spaces)") + arr = list(input()) + + for i in range(len(arr)): + arr[i] = int(arr[i]) + + + answer(arr) + +if __name__ == '__main__': + main() + diff --git a/ASSIGNMENTS/SwimmingPool.md b/ASSIGNMENTS/SwimmingPool.md new file mode 100644 index 00000000..2cf74a7d --- /dev/null +++ b/ASSIGNMENTS/SwimmingPool.md @@ -0,0 +1,105 @@ +The summer is coming and Chef wants to fill his swimming pool with water so that he could enjoy swimming in it during these hot days. + +The swimming pool is N metres in length (long course) and a fixed width 1 metre. Its long course is split into N equal parts, with possibly different depths. For each valid i, the i-th part has depth Di metres. + +You should process Q queries. There are two types of queries: + +1xv — pour v cubic metres of water into the x-th part of the pool +2x — find how much metres deep is the water surface from the ground in the x-th part of the pool. If there's no water on this part then the water surface depth is same as the depth of this part. +Water level obeys the following rules. As long as the water level in some part of the pool is higher than the water level in at least one of the adjacent parts, the water from it will move to adjacent parts with lower water levels until water levels become equal or there is no water left in this part. If the adjacent part from both sides (left and right) have lower water level then the half of the quantity of water in the current part will move to left and the other half will move to the right. The water on the leftmost part can't move to the left, and the water on the rightmost part can't move to the right. + +When the water level reaches the surface of the pool (i.e. its depth become 0), the pool overflows and the water level does not increase anymore. + +Please refer to the samples for more clarification. + + +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 two space-separated integers N and Q. +The second line contains N space-separated integers D1,D2,…,DN. +Q lines follow. Each of these lines describes a query in the format 1xv or 2x. + +Output +For each query of the second type, print a single line containing one real number — the depth of the water surface of the x-th part of the pool if it contains water, or Dx if it does not. Your answer will be considered correct if its relative or absolute error does not exceed 10−6. + +Constraints +1≤T≤100 +1≤N,Q≤105 +the sum of N in all test cases does not exceed 105 +the sum of Q in all test cases does not exceed 105 +1≤Di≤109 for each valid i +1≤v≤1014 + +Subtasks +Subtask #1 (30 points): there is at most one query of the first type + +Subtask #2 (30 points): all queries of the first type appear before any queries of the second type + +Subtask #3 (40 points): original constraints +Example Input:- +4 +5 6 +3 5 2 1 6 +1 4 2 +2 2 +1 2 3 +2 2 +2 5 +2 3 +6 8 +5 5 1 1 2 2 +1 4 1 +1 1 1 +2 1 +2 2 +2 3 +2 4 +2 5 +2 6 +7 8 +8 3 5 1 5 3 8 +1 4 7 +2 1 +2 2 +2 3 +2 4 +2 5 +2 6 +2 7 +3 4 +1 2 1 +1 1 10 +2 1 +2 2 +2 3 + +Output: +Example Output +4.0000000000 +2.0000000000 +5.0000000000 +2.0000000000 +4.2500000000 +4.2500000000 +1.0000000000 +1.0000000000 +1.7500000000 +1.7500000000 +6.5000000000 +3.0000000000 +3.0000000000 +1.0000000000 +3.0000000000 +3.0000000000 +6.5000000000 +0.0000000000 +0.0000000000 +0.0000000000 +Explanation +Example case 1: The pool is divided into 5 parts, the depths of the parts are 3 5 2 1 6, in first query we pour 2 cubic units of water into 4-th part, since both 3-th part and 5-th part are deeper than 4-th part then the water can't stay in 4-th part, 1 unit will go to left and 1 unit to right. the 1 unit that went to the right stayed in 5-th part and made its depth equal to 5, the 1 unit that went to the right couldn't stay in 3-th part because 2nd part is deeper than it so it moved to 2nd part and made its depth equal to 4. + +in the third query we pour 3 water units into 2nd part, in the beginning 2nd part is deeper than than 1st part and 3rd part so water will stay in 2nd part until its depth become 3 it will have same depth as 1st part so the remaining water will be evenly distributed between 1st and 2nd parts. + +Example case 2: in the first query we pour 1 cubic unit of water above 4th part, since it has same depth as 3rd part, and both 2nd and 5th parts are deeper than 4th part then 0.5 units of water will go to 5th part (and will be distributed equally between 5th and 6th parts) and 0.5 units of water will go to 2nd part (and will be ditributed equally between 1st and 2nd parts). so after first query depths of all parts will become (4.75 4.75 1.00 1.00 1.75 1.75). + +Example case 4: The pool overflowed so all parts has 0 depth diff --git a/ASSIGNMENTS/Unusual game.md b/ASSIGNMENTS/Unusual game.md new file mode 100644 index 00000000..662269c8 --- /dev/null +++ b/ASSIGNMENTS/Unusual game.md @@ -0,0 +1,28 @@ +#### Description +Recently Chef invented a two player game. The game is played on a horizontal strip consisting of n cells that are numbered from left to right with consecutive integers from 1 to n. +At the beginning of the game, a pawn is placed at the cell numbered x. The players make moves alternately, i.e. the first player makes all odd numbered moves (1st, 3rd, 5th and so on) and the second player all even numbered moves (2nd, 4th, 6th and so on). During the k-th move the player should move the pawn either exactly k cells to the left or exactly k cells to the right (provided the pawn doesn't land outside the strip). For example, in the k-th move, if the pawn is located at cell p before the move, it can be moved to either (p - k) or (p + k) if the appropriate cells are part of the strip . The player who is not able to make a move (i.e. both the above choices lead to cells outside of the strip) loses the game. Assume that both the players play optimally. +Before trying to play the game himself, Chef wants to understand the game more. So, he wants to find the outcome of m such games, +where in the i-th game the initial location of pawn is xi. Can you please help Chef in this? + +#### Input: +The first line of the input contains an integer T denoting the number of test cases. +For each test case, the first line of input contains two space separated integers ― n and m. +The second line contains m space separated integers ― x1, x2, ..., xm. + +#### Output: +For each test case, output a single line containing m space separated integers ― i-th of them should be an integer either 1 or 2, +corresponding to the player that will win if the game starts with the pawn located at cell xi. + +#### Constraints: +1 ≤ T ≤ 300 +1 ≤ the sum of n over all test cases ≤ 106 +1 ≤ m ≤ 50 +1 ≤ xi ≤ n + +#### Explanation: +There are three cells in the horizontal strip. + +If the pawn is initially located at cell 2, during the first move it will be moved to either 1 or 3. The second player can later move the pawn to cell 3 or 1, respectively. +Now, the first player has to move the pawn to three cells to the left or to the right, both of which end up moving the pawn outside the strip, so he is unable to make a move and will lose the game in this case. Hence, the second player wins the game. +If the pawn is initially located at cell 3, the first player will have to move to cell 2 during first move and then the second player will be have no available move that can still keep the pawn on the strip, +thus the second player loses the game. So, the first player is the winner in this case diff --git a/ASSIGNMENTS/bfs_spanni_tree b/ASSIGNMENTS/bfs_spanni_tree new file mode 100644 index 00000000..73f80712 --- /dev/null +++ b/ASSIGNMENTS/bfs_spanni_tree @@ -0,0 +1,5 @@ +There exist code we can find every where for creating a spannig tree for a given graph +but what if we want to create a spanning tree for just +one level or only some extend as + + like a cude and we just want spannig tree for one side -mean level one or fractals and we want to make spanning tree form inner fractul diff --git a/ASSIGNMENTS/fibonacci.md b/ASSIGNMENTS/fibonacci.md new file mode 100644 index 00000000..ea1f218e --- /dev/null +++ b/ASSIGNMENTS/fibonacci.md @@ -0,0 +1,12 @@ +The Fibonacci Sequence is the series of numbers: + +#### 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, ... + +The next number is found by adding up the two numbers before it. + + \ No newline at end of file diff --git a/ASSIGNMENTS/printPattern.txt b/ASSIGNMENTS/printPattern.txt new file mode 100644 index 00000000..2cb40aa0 --- /dev/null +++ b/ASSIGNMENTS/printPattern.txt @@ -0,0 +1 @@ +Print half pyramid, pyramid, inverted pyramid, Pascal's Triangle and Floyd's triangle in C Programming using control statements. diff --git a/ASSIGNMENTS/rockPaperScissor.md b/ASSIGNMENTS/rockPaperScissor.md index 14cd6f3c..b6116050 100644 --- a/ASSIGNMENTS/rockPaperScissor.md +++ b/ASSIGNMENTS/rockPaperScissor.md @@ -7,8 +7,8 @@ Remember the rules: * Scissors beats paper * Paper beats rock +``` C++ #include - using namespace std; int main() @@ -21,7 +21,9 @@ int main() cout << "What's your choose player 2(R - P - S): "; cin >> k2; cout << '\n'; - if (k1 == k2) cout << "DRAW"; + if (k1 == k2) cout << "DRAW"<0), +the first post contains the videos: 1,2,…,s1; +the second post contains the videos: s1+1,s1+2,…,s1+s2; +the third post contains the videos: s1+s2+1,s1+s2+2,…,s1+s2+s3; +... +the k-th post contains videos: n−sk+1,n−sk+2,…,n. +Polycarp is a perfectionist, he wants the total duration of videos in each post to be the same. + +Help Polycarp to find such positive integer values s1,s2,…,sk that satisfy all the conditions above. + +Input +The first line contains two integers n and k (1≤k≤n≤105). The next line contains n positive integer numbers a1,a2,…,an (1≤ai≤104), where ai is the duration of the i-th video. + +Output +If solution exists, print "Yes" in the first line. Print k positive integers s1,s2,…,sk (s1+s2+⋯+sk=n) in the second line. The total duration of videos in each post should be the same. It can be easily proven that the answer is unique (if it exists). + +If there is no solution, print a single line "No". + +Examples +input +6 3 +3 3 1 4 1 6 +output +Yes +2 3 1 +input +3 3 +1 1 1 +output +Yes +1 1 1 +input +3 3 +1 1 2 +output +No +input +3 1 +1 10 100 +output +Yes +3 diff --git a/COMPETITORS/Readme.md b/COMPETITORS/Readme.md index 48943db3..66ea1ef5 100644 --- a/COMPETITORS/Readme.md +++ b/COMPETITORS/Readme.md @@ -16,6 +16,7 @@ Make a PR and get yourself added to the list. ``` #### Name - [Github-Username](Link to your Github Profile) +- [Aathifnihas]https://github.com/Aathifnihas) --- ``` diff --git a/COMPETITORS/competitors.md b/COMPETITORS/competitors.md index 41081f90..54b713c3 100644 --- a/COMPETITORS/competitors.md +++ b/COMPETITORS/competitors.md @@ -1,93 +1,121 @@ -Member List - -#### Diego Bernal +## Member List + +### Praveen Kumar Purushothaman +- [praveenscience](https://github.com/praveenscience) +--- +### Arjun Mohnot +- [Arjun009](https://github.com/Arjun009) +--- +### Shreyansh Saurabh +- [binaryshrey](https://github.com/binaryshrey) +--- +### Amulya Gaur +- [amulyagaur](https://github.com/amulyagaur) +--- +### Diego Bernal - [diego95root](https://github.com/diego95root) --- - ### Doan Ngoc Huan - [dnhuan](https://github.com/dnhuan) --- - -#### Alvaro Tinoco +### Alvaro Tinoco - [MrMarble](https://github.com/MrMarble) --- - -#### Matteo Veraldi +### Matteo Veraldi - [mattveraldi](https://github.com/mattveraldi) --- - -#### Farzan F A +### Farzan F A - [farzanfa](https://github.com/Farzanfa) --- -#### Narender Singh Yadav +### Narender Singh Yadav - [narendersinghyadav](https://github.com/narendersinghyadav) --- - -#### Mohammed Faizaan Muzawar +### Mohammed Faizaan Muzawar - [faizaan-mm](https://github.com/faizaan-mm) --- - -#### GALLERIA +### Akshat Aggarwal +- [AkshatAggEm](https://github.com/AkshatAggEm) +--- +### GALLERIA - [Galleria](https://github.com/Galleria) --- - +### AMAN NIM +- [AMAN NIM](https://github.com/AmanNim98) +--- ### Vyshnavy - [Vyshnavy](https://github.com/vyshnavy) --- - +### HIMANSHI SINGHAL +- [HIMANSHI SINGHAL](https://github.com/himanshisinghal09) +--- ### Annalaura Ianiro - [Al1190](https://github.com/al1190) --- - -#### uf0h +### uf0h - [uf0h](https://github.com/uf0h) --- - -#### Saba Younis +### Saba Younis - [Saba Younis](https://github.com/sabayounis) - - +--- ### Connor Smith - [Titdirt](https://github.com/titdirt) --- - - -##Idácio Dad +### Idácio Dad - [idacioDad](https://github.com/idacioDad) --- - -#### Bec Braughton +### Bec Braughton - [beckton](https://github.com/beckton) --- -##Idácio Dad +### Idácio Dad - [idacioDad](https://github.com/idacioDad) --- -#### Munawar Villan +### Munawar Villan - [mvillan10](https://github.com/mvillan10) --- - - ### Tanya Sah - [tsah20](https://github.com/tsah20) --- - - +### Shivam Kumar +- [shivampkumar](https://github.com/shivampkumar) +--- ### Annas Amer - [annasamer3](https://github.com/annasamer3) - - +--- ### Amrutha - [Amrutha](https://github.com/amrutha3) --- - - - ### Jonathan Zhang - [jonathanzhang53](https://github.com/jonathanzhang53) - +--- ### Maaruf Dauda - [emkayDauda](https://github.com/emkayDauda) - --- - - +### Pavlina Mitsou +- [Pavlmits](https://github.com/Pavlmits) +--- +### Raj Shah +- [rajshah9914](https://github.com/rajshah9914) +--- +### Ayushi Jain +- [ayushijain218](https://github.com/ayushijain218) +--- +### Ahammad Hani +- [ahdhani](https://github.com/ahdhani) +--- +### Boughaba Otmane +- [Otman404](https://github.com/Otman404) +--- +### Melvin Abraham +- [melvinabraham](https://github.com/melvinabraham) +--- +### Navalona Ramanantoanina +- [Navds](https://github.com/Navds) +--- +### Chid +- [pvcpre](https://github.com/pvcpre) +--- +### Kevin Rojas +- [kevinrb](https://github.com/kevinrb) +--- +### Ted Jacobs +- [tedjacobs](https://github.com/tedjacobs) diff --git a/OPEN CHALLENGE/AVL_tree.cpp b/OPEN CHALLENGE/AVL_tree.cpp new file mode 100644 index 00000000..bb54d0d5 --- /dev/null +++ b/OPEN CHALLENGE/AVL_tree.cpp @@ -0,0 +1,161 @@ +#include +class avl_tree{ + private: + struct Node{ + int key; + Node* left; + Node* right; + int height; + }; + Node *root = nullptr; + + int get_alt(Node* no){ + if (no == nullptr){ + return 0; + } + return no->height; + } + + int top_val(int a, int b){ + if(a > b){ + return a; + } + return b; + } + + Node* createNO(int dado){ + Node* node = new Node; + node->key = dado; + node->left = nullptr; + node->right = nullptr; + node->height = 1; + return node; + } + + Node* ROTdir(Node* no){ + Node* fl = no->left; + Node* flr = fl->right; + fl->right = no; + no->left = flr; + + no->height = top_val(get_alt(no->left), get_alt(no->right)) + 1; + fl->height = top_val(get_alt(fl->left), get_alt(fl->right)) + 1; + return fl; + } + + Node* ROTesq(struct Node* no){ + Node* fr = no->right; + Node* frl = fr->left; + fr->left = no; + no->right = frl; + + no->height = top_val(get_alt(no->left), get_alt(no->right)) + 1; + fr->height = top_val(get_alt(fr->left), get_alt(fr->right)) + 1; + return fr; + } + + int getBalance(Node* no){ + if (no == nullptr){ + return 0; + } + return get_alt(no->left) - get_alt(no->right); + } + + Node* HELPinsert(Node* no, int key){ + if (no == nullptr){ + return createNO(key); + } + if(key < no->key){ + no->left = HELPinsert(no->left, key); + } + else if (key > no->key){ + no->right = HELPinsert(no->right, key); + } + + no->height = top_val(get_alt(no->left),get_alt(no->right)) +1; + int balance = getBalance(no); + //rotacoes simples + if (balance > 1 && key < no->left->key){ + return ROTdir(no); + } + if (balance < -1 && key > no->right->key){ + return ROTesq(no); + } + //rotacoes duplas + if (balance > 1 && key > no->left->key) { + no->left = ROTesq(no->left); + return ROTdir(no); + } + if (balance < -1 && key < no->right->key) { + no->right = ROTdir(no->right); + return ROTesq(no); + } + return no; + } + + void HelpPREorder(Node *root){ + if(root != nullptr){ + printf("%d ", root->key); + HelpPREorder(root->left); + HelpPREorder(root->right); + } + } + + bool Helpfind(int val, Node* no){ + if(no == nullptr){ + return false; + } + if(no->key == val){ + return true; + }if(no->key> val){ + return Helpfind(val, no->left); + } + if(no->key < val){ + return Helpfind(val, no->right); + } + return false; + } + + public: + void insert(int val){ + root = HELPinsert(root, val); + } + + bool find(int val){ + if(root == nullptr){ + return false; + } + return Helpfind(val,root); + } + + void preOrder(){ + if(root != nullptr){ + HelpPREorder(root); + } + printf("\n"); + } +}; +int main() { + avl_tree arv; + arv.insert(9); + arv.insert(5); + arv.insert(10); + arv.insert(0); + arv.insert(6); + arv.insert(11); + arv.insert(-1); + arv.insert(1); + arv.insert(2); + + printf("Pre-order of AVL tree is\n"); + arv.preOrder(); + + for(int i = 0; i < 10; i++){ + if(arv.find(i)){ + printf("the AVL tree have %d\n", i); + }else{ + printf("the AVL tree don't have %d\n", i); + } + } + return 0; +} diff --git a/OPEN CHALLENGE/ArrayOperations.cpp b/OPEN CHALLENGE/ArrayOperations.cpp index 865d1cda..595a90eb 100644 --- a/OPEN CHALLENGE/ArrayOperations.cpp +++ b/OPEN CHALLENGE/ArrayOperations.cpp @@ -1,5 +1,6 @@ #include #include +#include #include using namespace std; class arrays{ @@ -41,7 +42,7 @@ void arrays::search_l(int *&arr,int num) first = middle + 1; } else if(arr[middle] == a) { - cout< +function New-DomainToSPOSite +{ + param ( + [Parameter(Mandatory = $true, HelpMessage = 'The extension of the domain we need to add EX: outlook.com')] + [string]$ExternalExtension, + [Parameter(Mandatory = $true, HelpMessage = 'A list of users to send the invites to')] + [string[]]$Users, + [Parameter(Mandatory = $true, HelpMessage = 'The full URL to the sharepoint site')] + [string[]]$SPOSiteURL + ); + BEGIN + { + # Add the moduls of Azure and SPOnline + if (-not (Get-Module -ListAvailable AzureADPreview)) + { + Write-Host "Azure module not found. Please Install the module by Running Install-Module Azure" + exit + } + + if (-not (Get-Module -ListAvailable Microsoft.Online.SharePoint.PowerShell)) + { + Write-Host "Sharepoint Module not found. Please Install the module by Running Install-Module SPOnline" + exit + } + try + { + Write-Host "Connecting to Share Point and Azure" + $userName = "" + $password = "" + $cred = New-Object -TypeName System.Management.Automation.PSCredential -argumentlist $userName, $(convertto-securestring $password -asplaintext -force) + # This will need some configuration for accessing your company's Sharepoint admin URL' + Connect-SPOService -Credential $cred -URL "YOUR COMPANY SHAREPOINT ADMIN URL" + Connect-MSOLService -Cred $cred + Connect-AzureAD -Credential $cred + } + catch + { + Write-Verbose "Did not connect correctly" + exit + } + + } + PROCESS + { + #Check if the users are in the domain specified + foreach ($u in $Users) + { + if (-not ($u.Contains($ExternalDomainExtension))) + { + Write-Host "One of those user is not part of the specified domain" + exit + } + Write-Host "$u is part of the $ExternalDomainExtension " + } + + #Add the domain to the lists of acceptable Domain + $FoundPolicy = Get-AzureADPolicy | ?{ $_.Type -eq 'B2BManagementPolicy' } | select Definition, ID + $TheDefinition = $FoundPolicy.Definition + $ParsedDefinition = $FoundPolicy.Definition -split '(?=:)' + #Look for the allowed domains portion of the List that comes back. + foreach ($i in $ParsedDefinition) + { + if ($i.Contains("AllowedDomains")) + { + $DomainsIndex = $ParsedDefinition.IndexOf($i) + } + } + + if ($DomainsIndex -and (-not ($ParsedDefinition[$DomainsIndex + 1].Contains($ExternalExtension)))) + { + $TheAllowedDomains = $ParsedDefinition[$DomainsIndex + 1].Replace("]}", ',"' + $ExternalExtension + '"]}') + $ParsedDefinition[$DomainsIndex + 1] = $TheAllowedDomains + [Collections.Generic.List[String]]$lst = $ParsedDefinition -join "" + Write-Host $lst + Set-AzureADPolicy -Id $FoundPolicy.ID -Definition $lst + } + elseif ($DomainsIndex -and $ParsedDefinition[$DomainsIndex + 1].Contains($ExternalExtension)) + { + Write-Host "The domain already exists in the allowed domains. Moving onto the invite portion." + } + else + { + Write-Host "The policy you specified did not contain the Allowed domains." + exit + } + #Send a request to the people that need to be added to the site. These will be people that are now added. + foreach ($NewUser in $Users) + { + Write-Verbose "Inviting $NewUser to Azure" + # This will also require the redirect to your Azure invites + New-AzureADMSInvitation -InvitedUserEmailAddress $NewUser -SendInvitationMessage $True -InviteRedirectUrl "https://myapps.microsoft.com/" + } + #Go to the SPO Site + $theFoundSite = Get-SPOSite -Identity $SPOSiteURL + if ($theFoundSite) + { + Set-SPOSite $theFoundSite.URL -SharingCapability ExistingExternalUserSharingOnly + } + else + { + Write-Host "The site could not be found.Did you specify the entire url?" + exit + } + + } + END + { + Write-Host "Added the domain $ExternalExtension to Azure and added $($Users.Count) to $SPOSiteURL" + + } + +} \ No newline at end of file diff --git a/OPEN CHALLENGE/Bellman_Ford.py b/OPEN CHALLENGE/Bellman_Ford.py new file mode 100644 index 00000000..513da179 --- /dev/null +++ b/OPEN CHALLENGE/Bellman_Ford.py @@ -0,0 +1,67 @@ +from __future__ import print_function +from collections import defaultdict + +#Class to represent a graph +class Graph: + + def __init__(self,vertices): + self.V= vertices #No. of vertices + self.graph = [] # default dictionary to store graph + + # function to add an edge to graph + def addEdge(self,u,v,w): + self.graph.append([u, v, w]) + + # utility function used to print the solution + def printArr(self, dist): + print("Vertex Distance from Source") + for i in range(self.V): + print("%d \t\t %d" % (i, dist[i])) + + # The main function that finds shortest distances from src to + # all other vertices using Bellman-Ford algorithm. The function + # also detects negative weight cycle + def BellmanFord(self, src): + + # Step 1: Initialize distances from src to all other vertices + # as INFINITE + dist = [float("Inf")] * self.V + dist[src] = 0 + + + # Step 2: Relax all edges |V| - 1 times. A simple shortest + # path from src to any other vertex can have at-most |V| - 1 + # edges + for i in range(self.V - 1): + # Update dist value and parent index of the adjacent vertices of + # the picked vertex. Consider only those vertices which are still in + # queue + for u, v, w in self.graph: + if dist[u] != float("Inf") and dist[u] + w < dist[v]: + dist[v] = dist[u] + w + + # Step 3: check for negative-weight cycles. The above step + # guarantees shortest distances if graph doesn't contain + # negative weight cycle. If we get a shorter path, then there + # is a cycle. + + for u, v, w in self.graph: + if dist[u] != float("Inf") and dist[u] + w < dist[v]: + print("Graph contains negative weight cycle") + return + + # print all distance + self.printArr(dist) + +g = Graph(5) +g.addEdge(0, 1, -1) +g.addEdge(0, 2, 4) +g.addEdge(1, 2, 3) +g.addEdge(1, 3, 2) +g.addEdge(1, 4, 2) +g.addEdge(3, 2, 5) +g.addEdge(3, 1, 1) +g.addEdge(4, 3, -3) + +#Print the solution +g.BellmanFord(0) \ No newline at end of file diff --git a/OPEN CHALLENGE/Dinosaur.py b/OPEN CHALLENGE/Dinosaur.py new file mode 100644 index 00000000..1d18a069 --- /dev/null +++ b/OPEN CHALLENGE/Dinosaur.py @@ -0,0 +1,92 @@ +# -*- coding: utf_8 -*- +from threading import Timer +import time +import random +while True: + alive = True + score = -1 + timeout = 3 + + def print_plan(right_move): + if right_move == "1": + print("───────────████████──────────────────────────────────────────") + print("──────────███▄███████─────────────────────────██─────────────") + print("──────────███████████────────────────────█───████────────────") + print("──────────███████████───────────────────███──████────────────") + print("──────────██████────────────────────────███──████────────────") + print("──────────█████████─────────────────────███──████───█────────") + print("█───────███████─────────────────────────███──████──███───────") + print("██────████████████──────────────────────███──████──███───────") + print("███──██████████──█──────────────────────█████████──███───────") + print("███████████████─────────────────────────█████████──███───────") + print("███████████████──────────────────────────────█████████───────") + print("─█████████████───────────────────────────────█████████───────") + print("──███████████────────────────────────────────████────────────") + print("────████████─────────────────────────────────████────────────") + print("─────███──██─────────────────────────────────████────────────") + print("─────██────█─────────────────────────────────████────────────") + print("─────█─────█─────────────────────────────────████────────────") + print("─────██────██────────────────────────────────████────────────") + else: + print("───────────████████────────────────────██─────────────────────────") + print("──────────███▄███████──────────────────████───────────────────────") + print("──────────███████████──────────────────██████─────────────────────") + print("──────────███████████─────────────███────██████───────────────────") + print("──────────██████────────────────█████────████████─────────────────") + print("──────────█████████───────────█████████──██████████───────────────") + print("█───────███████─────────────███████████──████████████─────────────") + print("██────████████████────────███████████████████████████─────────────") + print("███──██████████──█───────────────────██████████████████───────────") + print("███████████████────────────────────────█████████████████████████──") + print("███████████████──────────────────────────██████████████████───────") + print("─█████████████─────────────────────────────███████████████████────") + print("──███████████────────────────────────────────████████████─────────") + print("────████████──────────────────────────────────────────────────────") + print("─────███──██──────────────────────────────────────────────────────") + print("─────██────█──────────────────────────────────────────────────────") + print("─────█─────█──────────────────────────────────────────────────────") + print("─────██────██─────────────────────────────────────────────────────") + + + def make_move(move): + global alive + global right_move + if move != right_move: + alive = False + print("Wrong move!") + + def change_state(): + global alive + alive = False + print("Time's up!\n") + + print("Enter 1 to jump or 2 to crouch.") + print("Run begins in 3,", end = " ") + time.sleep(1) + print("2,", end = " ") + time.sleep(1) + print("1...") + time.sleep(1) + print("GO!") + time.sleep(1) + + while alive: + global right_move + right_move = random.choice(["1","2"]) + print_plan(right_move) + + t = Timer(timeout, change_state) + t.start() + prompt = "You have %f seconds to make a move...\n" % timeout + move = input(prompt) + t.cancel() + make_move(move) + + score += 1 + timeout = timeout * 0.99 + + print("You died. Your score is %d." % score) + if input("To play again, press enter.\nTo exit game, press any other key and enter.\n") != "": + break + + diff --git a/OPEN CHALLENGE/FizzBuzz.py b/OPEN CHALLENGE/FizzBuzz.py new file mode 100644 index 00000000..a3dc8cd5 --- /dev/null +++ b/OPEN CHALLENGE/FizzBuzz.py @@ -0,0 +1,32 @@ +""" + +https://en.wikipedia.org/wiki/Fizz_buzz + +Fizz buzz is a group word game for children to teach them about division. Players take turns to +count incrementally, replacing any number divisible by 3 with the word "fizz", and any +number divisible by 5 with the word "buzz". + +Players generally sit in a circle. The player designated to go first says the number "1", and +each player thenceforth counts one number in turn. However, any number divisible by 3 is +replaced by the word fizz and any divisible by 5 by the word buzz. Numbers divisible by both +become fizz buzz. A player who hesitates or makes a mistake is eliminated from the game. + +For example, a typical round of fizz buzz would start as follows: + +1, 2, Fizz, 4, Buzz, Fizz, 7, 8, Fizz, Buzz, 11, Fizz, 13, 14, Fizz Buzz, 16, 17, Fizz, 19, Buzz, Fizz, 22, +23, Fizz, Buzz, 26, Fizz, 28, 29, Fizz Buzz, 31, 32, Fizz, 34, Buzz, Fizz, ... + +It has been used as an interview screening device for computer programmers. Writing a program to +output the first 100 FizzBuzz numbers is a trivial problem for any would-be computer programmer, +so interviewers can easily sort out those with insufficient programming ability. +""" + +def FizzBuzz(limit): + for i in range(1, limit+1): + if(i%3 == 0 and i%5 == 0): print("FizzBuzz") + elif(i%3 == 0): print("Fizz") + elif(i%5 == 0): print("Buzz") + else: print(i) + +FizzBuzz(100) + \ No newline at end of file diff --git a/OPEN CHALLENGE/HELLO WORLD.cpp b/OPEN CHALLENGE/HELLO WORLD.cpp new file mode 100644 index 00000000..d14ea15b --- /dev/null +++ b/OPEN CHALLENGE/HELLO WORLD.cpp @@ -0,0 +1,8 @@ + +#include +using namespace std; +int main() +{ +cout<<"HELLO WORLD!"< { + console.log(`Hello ${name} in my fascinating ES6 world`) +} + +hello(process.env.USERNAME); \ No newline at end of file diff --git a/OPEN CHALLENGE/HellodearWorld.py b/OPEN CHALLENGE/HellodearWorld.py index 500ce805..b22a6d1b 100644 --- a/OPEN CHALLENGE/HellodearWorld.py +++ b/OPEN CHALLENGE/HellodearWorld.py @@ -1,2 +1 @@ - print("Hellloo , dear world!") diff --git a/OPEN CHALLENGE/MO_ALGO.cpp b/OPEN CHALLENGE/MO_ALGO.cpp new file mode 100644 index 00000000..54e80355 --- /dev/null +++ b/OPEN CHALLENGE/MO_ALGO.cpp @@ -0,0 +1,98 @@ +#include +using namespace std; +#define M 1000000007 +int n,m,root,BLOCK; +vector< vector > g(400005); +int color[400005],temp[400005],h[400005]; +vector c; +vector< pair< pair ,int> > qry; + +void dfs(int u,int par) +{ + pair p; + p.first=c.size(); + c.push_back(color[u]); + for(int i=0;i,int> &a,const pair< pair,int> &b) +{ + int l1 = a.first.first/BLOCK; + int l2 = b.first.first/BLOCK; + if(l1 != l2) + return (l1 b.first.second); +} +int main() +{ + scanf("%d",&n); + BLOCK = static_cast(sqrt(n)); + for(int i=2;i<=n;i++) + { + int u; + scanf("%d",&u); + u++; + g[u].push_back(i); + g[i].push_back(u); + } + for(int i=1;i<=n;i++) + { + scanf("%d",&color[i]); + temp[i]=color[i]; + } + sort(temp,temp+n+1); + for(int i=1;i<=n;i++) + color[i]= lower_bound(temp,temp+n+1,color[i])-temp; + dfs(1,0); + sort(qry.begin(),qry.end(),cmp); + int ml = 0,mr = -1; + int cans=0; + for(int i=0;i l) + { + ml--; + h[c[ml]]++; + if(h[c[ml]]==1) + cans++; + } + while(mr > r) + { + h[c[mr]]--; + if(h[c[mr]]==0) + cans--; + mr--; + } + while(ml < l) + { + h[c[ml]]--; + if(h[c[ml]]==0) + cans--; + ml++; + } + temp[qry[i].second]=cans; + } + long long res=1; + for(int i=1;i<=n;i++) + { + res = (res%M*(long long)temp[i]%M)%M; + } + printf("%lld\n",res); + return 0; +} diff --git a/OPEN CHALLENGE/MathPractice.java b/OPEN CHALLENGE/MathPractice.java new file mode 100644 index 00000000..64ce3599 --- /dev/null +++ b/OPEN CHALLENGE/MathPractice.java @@ -0,0 +1,132 @@ +import java.util.Scanner; +import java.util.*; + +public class MathPractice { + + public static void main(String[] args) + { + boolean play = true; + + while (play) + { + Scanner scan = new Scanner(System.in); + + System.out.println("What would you like to practice?"); + System.out.println("[1] Addition\n[2] Subtraction (No negatives)\n[3] Multiplication\n[4] Division\n[5] Close\nPlease choose an option."); + + int operator = scan.nextInt(); + + // Addition Operation \\ + if (operator == 1) + { + int num1 = (int)(Math.random() * 11); + int num2 = (int)(Math.random() * 11); + int result = (num1+num2); + System.out.println("What is " + num1 + " + " + num2 + "?"); + int answer = scan.nextInt(); + // Addition Analysis \\ + if (answer == result) + { + System.out.println("Correct! The answer is " + answer + "!"); + } + else + { + System.out.println("Oops! You guessed " + answer + ", but the correct answer is " + result + "!"); + } + } + + // Subtraction Operation \\ + if (operator == 2) + { + int num1 = (int)(Math.random() * 11); + int num2 = (int)(Math.random() * 11); + // Positive Result Check \\ + if (num1 > num2) + { + int result = (num1-num2); + System.out.println("What is " + num1 + " - " + num2 + "?"); + int answer = scan.nextInt(); + if (answer == result) + { + System.out.println("Correct! The answer is " + answer + "!"); + } + else + { + System.out.println("Oops! You guessed " + answer + ", but the correct answer is " + result + "!"); + } + } + else + { + int result = (num2-num1); + System.out.println("What is " + num2 + " - " + num1 + "?"); + int answer = scan.nextInt(); + if (answer == result) + { + System.out.println("Correct! The answer is " + answer + "!"); + } + else + { + System.out.println("Oops! You guessed " + answer + ", but the correct answer is " + result + "!"); + } + } + } + + //Multiplication Operation\\ + if (operator == 3) + { + int num1 = (int)(Math.random() * 11); + int num2 = (int)(Math.random() * 11); + int result = num1 * num2; + System.out.println("What is " + num1 + " * " + num2 + "?"); + int answer = scan.nextInt(); + if (answer == result) + { + System.out.println("Correct! The answer is " + answer + "!"); + } + else + { + System.out.println("Oops! You guessed " + answer + ", but the correct answer is " + result + "!"); + } + } + + //Division Operation\\ + if (operator == 4) + { + int num1 = (int)(Math.random() * 11); + int num2 = (int)(Math.random() * 10 + 1); + int result = (int)(num1 / num2); + System.out.println("What is " + num1 + " / " + num2 + "? Do not include the remainder!"); + int answer = scan.nextInt(); + if (answer == result) + { + System.out.println("Correct! The answer is " + answer + "!"); + } + else + { + System.out.println("Oops! You guessed " + answer + ", but the correct answer is " + result + "!"); + } + } + + //Close the program\\ + if (operator == 5) + { + System.out.println("Closed!"); + } + + //Check Continuation\\ + System.out.println("Would you like to keep practicing?\n[1] Yes\n[2] No"); + int choice = scan.nextInt(); + + if (choice == 1) + { + play = true; + } + else + { + play = false; + System.out.println("Thanks for practicing!"); + } + } + } + +} \ No newline at end of file diff --git a/OPEN CHALLENGE/MillerRabin.cpp b/OPEN CHALLENGE/MillerRabin.cpp new file mode 100644 index 00000000..5e6b2f61 --- /dev/null +++ b/OPEN CHALLENGE/MillerRabin.cpp @@ -0,0 +1,86 @@ +#include +using namespace std; +#define endl '\n' +long long mulmod(long long a,long long b,long long c){ + long long x = 0,y=a%c; + while(b > 0){ + if(b%2 == 1){ + x = (x+y)%c; + } + y = (y*2)%c; + b /= 2; + } + return x%c; +} +long long int modulo_exp(long long int a,long long int b,long long int c) +{ + long long x=1,y=a; + while(b > 0){ + if(b%2 == 1){ + x = mulmod(x,y,c); + } + y = mulmod(y,y,c); + b /= 2; + } + return x%c; +} +bool Fermat(long long p,int iterations){ + if(p == 1){ // 1 isn't prime + return false; + } + for(int i=0;i>t; + while(t--) + { + long long p; + cin>>p; + + if(Miller(p,18)) + { + cout<<"YES"<= numbers[i]){ + converted += roman[i]; + num -= numbers[i]; + } + } + console.log(converted); + return converted; + +} + +convert(3200) diff --git a/OPEN CHALLENGE/SegmentTree.java b/OPEN CHALLENGE/SegmentTree.java new file mode 100644 index 00000000..7cca0de0 --- /dev/null +++ b/OPEN CHALLENGE/SegmentTree.java @@ -0,0 +1,84 @@ +import java.util.*; + +class Solution { + + static void buildTree(int a[], int tree[], int start, int end, int treeNode) { + if(start == end) { + tree[treeNode] = a[start]; + return; + } + int mid = (start+end)/2; + buildTree(a, tree, start, mid, 2*treeNode); + buildTree(a, tree, mid + 1, end, 2*treeNode+1); + tree[treeNode] = Math.max(tree[2*treeNode], tree[2*treeNode+1]); + } + + static void update(int a[], int tree[], int start, int end, int treeNode, int idx, int value) { + if(start == end) { + a[idx] = value; + tree[treeNode] = value; + return; + } + int mid = (start + end)/2; + if(idx > mid) { + update(a, tree, mid+1, end, 2*treeNode+1, idx, value); + } + else { + update(a, tree, start, mid, 2*treeNode, idx, value); + } + tree[treeNode] = Math.max(tree[2*treeNode], tree[2*treeNode + 1]); + } + + static int query(int tree[], int start, int end, int treeNode, int l, int r) { + if(end < l || start > r) { + return 0; + } + if(l <= start && end <= r) { + return tree[treeNode]; + } + int mid = (start+end)/2; + int res1 = query(tree, start, mid, 2*treeNode, l, r); + int res2 = query(tree, mid + 1, end, 2*treeNode + 1, l, r); + return Math.max(res1, res2); + } + + public static void main(String[] args) { + // Write your code here + Scanner sc = new Scanner(System.in); + int n = sc.nextInt(); + int q = sc.nextInt(); + int a[] = new int[n]; + int tree[] = new int[4*n]; + for(int i = 0; i < n; i++) a[i] = sc.nextInt(); + buildTree(a, tree, 0, n-1, 1); + //System.out.println(Arrays.toString(tree)); + while(q-- > 0) { + sc.nextLine(); + char qu = sc.next().charAt(0); + int l = sc.nextInt(); + int r = sc.nextInt(); + if(qu == 'q') { + //System.out.println("0"); + System.out.println(query(tree, 0, n-1, 1, l-1, r-1)); + } + else { + update(a, tree, 0, n-1, 1, l-1, r); + //System.out.println(Arrays.toString(tree)); + } + //System.out.println(Arrays.toString(tree)); + sc.close(); + } + } + +} + +/* +Input: +5 5 +1 5 2 4 3 +q 1 5 +q 1 3 +q 3 5 +u 3 6 +q 1 5 +*/ diff --git a/OPEN CHALLENGE/Special Pythagorean triplet b/OPEN CHALLENGE/Special Pythagorean triplet new file mode 100644 index 00000000..420770c6 --- /dev/null +++ b/OPEN CHALLENGE/Special Pythagorean triplet @@ -0,0 +1,20 @@ +#include +using namespace std; + +int main() +{ + int c=0,k=1; + for(int a=0;a<1000/3;a++) + for(int b=0; b<1000/2;b++) + { + c = 1000 - a - b; + if(c*c == a*a + b*b) + if(a+b+c==1000) + { + k = a*b*c; + break; + } + } + + cout << k << '\n'; +} diff --git a/OPEN CHALLENGE/StopPanel.html b/OPEN CHALLENGE/StopPanel.html new file mode 100644 index 00000000..06b033df --- /dev/null +++ b/OPEN CHALLENGE/StopPanel.html @@ -0,0 +1,40 @@ + + + + + + + + + +
click the panel to slide down
+
hello world
+ + + + diff --git a/OPEN CHALLENGE/Tic-tac-toe.py b/OPEN CHALLENGE/Tic-tac-toe.py new file mode 100644 index 00000000..8a6ca1c8 --- /dev/null +++ b/OPEN CHALLENGE/Tic-tac-toe.py @@ -0,0 +1,98 @@ +#modify size of plan +size = 10 +#modify win condition +num_to_win = 4 +plan = [["-" for i in range(size)] for j in range(size)] +current_symbol = "o" + +def print_plan(): + for i in range(len(plan)): + if i == 0: + print(" ", end = "") + for k in range(len(plan[i])): + print(chr(65+k), end = " ") + print() + for j in range(len(plan[i])): + if j == 0: + if i < 9: + print(i+1, end = " ") + else: + print(i+1, end = " ") + if plan[i][j] == "-": + print("-", end = " ") + elif plan[i][j] == "x": + print("x", end = " ") + else: + print("o", end = " ") + print() + +def check_for_win(x,y,current_symbol): + # check row + count = 0 + for i in range(size): + if plan[x][i] == current_symbol: + count += 1 + if count == num_to_win: + return True + else: + count = 0 + # check column + count = 0 + for i in range(size): + if plan[i][y] == current_symbol: + count += 1 + if count == num_to_win: + return True + else: + count = 0 + # check diagonal one + count = 0 + m = x + n = y + while m > 0 and n > 0: + m -= 1 + n -= 1 + while m <= size-1 and n <= size-1: + if plan[m][n] == current_symbol: + count += 1 + if count == num_to_win: + return True + m += 1 + n += 1 + # check diagonal two + count = 0 + m = x + n = y + while m > 0 and n < size-1: + m -= 1 + n += 1 + while m <= size-1 and n >= 0: + if plan[m][n] == current_symbol: + count += 1 + if count == num_to_win: + return True + m += 1 + n -= 1 + return False +print("Enter coordinates. Sample input \"c4\" (without the quotes).") +while True: + print("Player {}'s turn.".format(current_symbol)) + print_plan() + inp = input() + y = ord(inp[0].upper())-65 + x = int(inp[1:])-1 + if plan[x][y] == "-": + plan[x][y] = current_symbol + if check_for_win(x,y,current_symbol): + print(x,y) + print_plan() + break + if current_symbol == "o": + current_symbol = "x" + else: + current_symbol = "o" + else: + print("Invalid position, play again.") + +print("Player {} wins!!!".format(current_symbol)) +input() diff --git a/OPEN CHALLENGE/TopoSort.cpp b/OPEN CHALLENGE/TopoSort.cpp new file mode 100644 index 00000000..84939355 --- /dev/null +++ b/OPEN CHALLENGE/TopoSort.cpp @@ -0,0 +1,43 @@ +//Prints the Lexicographically smallest TS order. +#include +using namespace std; +#define endl '\n' +vector< vector > v(100); +vector visit(100,false); +stack st; +void toposort(int s) +{ + visit[s]=true; + for(int i=0;i>n>>m; + while(m--) + { + int x,y; + cin>>x>>y; + v[x].push_back(y); + } + for(int i=1;i<=n;i++) + sort(v[i].rbegin(),v[i].rend()); + for(int i=n;i>=1;i--) + if(visit[i]==false) + toposort(i); + while(!st.empty()) + { + cout< + +using namespace std; + +int main() +{ + int arr[100],n,i,flag; + cout<<"Enter the size of the array."<>n; + + cout<<"Enter the array elements."<>arr[i]; + cout< +using namespace std; + +int main() +{ + int n, t1 = 0, t2 = 1, nextTerm = 0; + + cout << "Enter the number of terms: "; + cin >> n; + + cout << "Fibonacci Series: "; + + for (int i = 1; i <= n; ++i) + { + // Prints the first two terms. + if(i == 1) + { + cout << " " << t1; + continue; + } + if(i == 2) + { + cout << t2 << " "; + continue; + } + nextTerm = t1 + t2; + t1 = t2; + t2 = nextTerm; + + cout << nextTerm << " "; + } + return 0; +} diff --git a/OPEN CHALLENGE/hello-world.pas b/OPEN CHALLENGE/hello-world.pas new file mode 100644 index 00000000..86ba0515 --- /dev/null +++ b/OPEN CHALLENGE/hello-world.pas @@ -0,0 +1,9 @@ + begin + + WriteLn; + + WriteLn( 'Hello World!'); + + WriteLn; + + End. diff --git a/OPEN CHALLENGE/helloworld.c b/OPEN CHALLENGE/helloworld.c new file mode 100644 index 00000000..4679c31b --- /dev/null +++ b/OPEN CHALLENGE/helloworld.c @@ -0,0 +1,6 @@ +#include +int main() +{ +printf("helloworld.c"); +return 0; +} diff --git a/OPEN CHALLENGE/heloctober.py b/OPEN CHALLENGE/heloctober.py new file mode 100644 index 00000000..f745445e --- /dev/null +++ b/OPEN CHALLENGE/heloctober.py @@ -0,0 +1,3 @@ +def hello_world(): + print('Hello, Hactoberfest!') +hello_world() diff --git a/OPEN CHALLENGE/mockApi.go b/OPEN CHALLENGE/mockApi.go new file mode 100644 index 00000000..2d6a4d9a --- /dev/null +++ b/OPEN CHALLENGE/mockApi.go @@ -0,0 +1,46 @@ +package main + +import ( + "encoding/json" + "log" + "net/http" +) + +func writeCORS(w http.ResponseWriter) http.ResponseWriter { + w.Header().Set("Access-Control-Allow-Origin", "*") + return w +} + +// Use this to serve json file +func fileServer(filename string) func(w http.ResponseWriter, r *http.Request) { + return func(w http.ResponseWriter, r *http.Request) { + w = writeCORS(w) + http.ServeFile(w, r, filename) + } +} + +type Message struct { + Name string + Body string + Time int64 +} + +// Use this to return json represantation of an object +func jsonServer(v interface{}) func(w http.ResponseWriter, r *http.Request) { + return func(w http.ResponseWriter, r *http.Request) { + w = writeCORS(w) + json, _ := json.Marshal(v) + w.Write(json) + } +} + +// Put hellothere.json next to executable/script +func main() { + http.HandleFunc("/hello-there", fileServer("hellothere.json")) + http.HandleFunc("/message", jsonServer(Message{"Alice", "Hello", 1294706395881547000})) + + err := http.ListenAndServe(":8081", nil) + if err != nil { + log.Fatal("Something went wrong: ", err) + } +} diff --git a/OPEN CHALLENGE/palidromo.c b/OPEN CHALLENGE/palidromo.c new file mode 100644 index 00000000..61f139d9 --- /dev/null +++ b/OPEN CHALLENGE/palidromo.c @@ -0,0 +1,28 @@ +#include +#include + + +int chkpal(char word[]){ + int i, j; + j = strlen(word) - 1; + for(i = 0; i < strlen(word); i++){ + if(word[i] != word[j]) + return 0; + j--; + } + return 1; +} + +int main(){ + char palv[50]; + int i = 0; + while(i < 3){ + scanf("%s", palv); + if(chkpal(palv)) + printf("palindroma"); + else + printf("n palindroma"); + printf("\n"); + i++; + } +} diff --git a/OPEN CHALLENGE/parlindrome.js b/OPEN CHALLENGE/parlindrome.js new file mode 100644 index 00000000..c1754a52 --- /dev/null +++ b/OPEN CHALLENGE/parlindrome.js @@ -0,0 +1,7 @@ +// PARLINDROME WITH REDUCE HELPER + + function pal (str) { + return str === [...str].reduce((previous, current) => current + previous, ''); + } + + console.log(pal('abba')) diff --git a/OPEN CHALLENGE/reverse-word.js b/OPEN CHALLENGE/reverse-word.js index e69de29b..8b137891 100644 --- a/OPEN CHALLENGE/reverse-word.js +++ b/OPEN CHALLENGE/reverse-word.js @@ -0,0 +1 @@ + diff --git a/OPEN CHALLENGE/reverse.js b/OPEN CHALLENGE/reverse.js new file mode 100644 index 00000000..fb802714 --- /dev/null +++ b/OPEN CHALLENGE/reverse.js @@ -0,0 +1,4 @@ +function reverse (str) { + return [...str].reverse().join(''); +} +console.log(reverse('pick')) \ No newline at end of file diff --git a/OPEN CHALLENGE/robotgame.cpp b/OPEN CHALLENGE/robotgame.cpp new file mode 100644 index 00000000..2a336bfc --- /dev/null +++ b/OPEN CHALLENGE/robotgame.cpp @@ -0,0 +1,64 @@ +#include +#define fastio ios_base::sync_with_stdio(false) +#define fastcin cin.tie(NULL) +using namespace std; + +int main(){ + // For file input and output + freopen("input.txt", "r", stdin); + freopen("output.txt", "w", stdout); + fastio; + fastcin; + int t; +cin>>t; +while(t--){ + string a; + cin>>a; + bool arr[a.length()]; + for(int i=0;i=max(0,(i)-(int(a[i])-48));j--){ + if(arr[j]){ + count = 1; + break; + } + else + { + arr[j] = true; + } + } + int n = a.length()-1; + int mini = min(n,i+(int(a[i])-48)); + for(int k=i+1;k<=mini;k++){ + if(arr[k]){ + count = 1; + break; + } + else + { + arr[k] = true; + } + } + if(count==1){ + break; + } + + } + } + if(count==1){ + cout<<"unsafe\n"; + } + else + { + cout<<"safe\n"; + } +} +return 0; +} \ No newline at end of file diff --git a/OPEN CHALLENGE/shapeSizenColor b/OPEN CHALLENGE/shapeSizenColor.py similarity index 99% rename from OPEN CHALLENGE/shapeSizenColor rename to OPEN CHALLENGE/shapeSizenColor.py index 5e7c3961..752fb1f3 100644 --- a/OPEN CHALLENGE/shapeSizenColor +++ b/OPEN CHALLENGE/shapeSizenColor.py @@ -1,3 +1,4 @@ +from __future__ import print_function #classes and subclasses to import import cv2 @@ -646,7 +647,7 @@ def angle(pt1, pt2, pt0): filep.close() #process the image data = main(fp) - print data + print(data) #open the csv filep = open('results1B_943.csv','a') #make a newline entry so that the next image data is written on a newline diff --git a/OPEN CHALLENGE/sudokusolver.cpp b/OPEN CHALLENGE/sudokusolver.cpp new file mode 100644 index 00000000..f9636593 --- /dev/null +++ b/OPEN CHALLENGE/sudokusolver.cpp @@ -0,0 +1,170 @@ +#include +#include + +using namespace std; +#define MAX 25 +// Here the Sudoku is solved using backtracking +// The time complexity of backtracking is N^M +// Here N: Number of possibilities for each square +// M: Number of Spaces that are blank +int Sudoku[MAX][MAX],size; + +// Function to Enter the values of Sudoku initially +void EnterSudoku(){ + + cout<<"Enter the size of the sudoku board\n"; + cin>>size; + assert(size<=25); + cout<<"Enter the board at its present state\n"; + cout<<"Enter '0' for blank\n"; + for(int i=0;i>Sudoku[i][j]; + } + } +} + +// Function to display the solved Sudoku +void displaysolved(int Sudoku[MAX][MAX], int size){ + + for(int i=0;i +using namespace std; +int main() +{ + int var=0, i; + for(i=3; i<1000; i++) + { + if(i%3 == 0 && i%5 == 0) + var = var+i; + else if(i%3 == 0) + var = var+i; + else if(i%5 == 0) + var = var+i; + } + cout<0: + first_container_amount = int(input()) + second_container_amount = int(input()) + final_amount = int(input()) + if final_amount>max(first_container_amount,second_container_amount): + print(-1) + elif final_amount%gcd(first_container_amount,second_container_amount)!=0: + print(-1) + elif final_amount==first_container_amount or final_amount == second_container_amount: + print(1) + else: + print(min(problem(first_container_amount,second_container_amount,final_amount),problem(second_container_amount,first_container_amount,final_amount))) + t = t-1 + diff --git a/OPEN CHALLENGE/youtube/README.md b/OPEN CHALLENGE/youtube/README.md new file mode 100644 index 00000000..068c73a0 --- /dev/null +++ b/OPEN CHALLENGE/youtube/README.md @@ -0,0 +1,3 @@ +# Youtube Video download using python 3 +This script will help you download any youtube video to a specified folder in your PC. Works well with both Windows and Linux OS. +You will need install pytube python library before running this script. Install the library using **pip install pytube**. \ No newline at end of file diff --git a/OPEN CHALLENGE/youtube/youtube.py b/OPEN CHALLENGE/youtube/youtube.py new file mode 100644 index 00000000..cdfefafa --- /dev/null +++ b/OPEN CHALLENGE/youtube/youtube.py @@ -0,0 +1,18 @@ +from pytube import YouTube + +def ytDownload(link,path): + #Youtube obj + yt = YouTube(link) + try: + #downloading the video + yt.streams.first().download(path) + except: + print("Exception caught") + + +s = input("YouTube Video URL: ") +p = input("Folder Path: ") +#raw path +path = r'%s'%p +#print(path) +ytDownload(s,path) diff --git a/OPEN CHALLENGE/z-algorithm.cpp b/OPEN CHALLENGE/z-algorithm.cpp new file mode 100644 index 00000000..55a3bd03 --- /dev/null +++ b/OPEN CHALLENGE/z-algorithm.cpp @@ -0,0 +1,40 @@ +#include +using namespace std; +int z[100005]; +void Zfunction(string &s) +{ + int n=s.size(); + int L = 0, R = 0; + for (int i = 1; i < n; i++) + { + if (i > R) + { + L = R = i; + while (R < n && s[R-L] == s[R]) R++; + z[i] = R-L; R--; + } + else + { + int k = i-L; + if (z[k] < R-i+1) z[i] = z[k]; + else + { + L = i; + while (R < n && s[R-L] == s[R]) R++; + z[i] = R-L; R--; + } + } + } + for(int i=0;i>x; + Zfunction(x); + + return 0; +} diff --git a/README.md b/README.md index 331118ca..ae58f5cb 100644 --- a/README.md +++ b/README.md @@ -1,21 +1,22 @@ -# CODE2RACE --- Dive into coding world +Hello World. This is the change. +# CODE2RACE --- Dive into a coding world +[![Gitter](https://img.shields.io/gitter/room/bvphec/Lobby.svg?style=flat-square)](https://gitter.im/bvphec/Lobby) -## Questions will be given as an issue. 😁 +## Questions will be given as an issue. 😁😁 Access the problem statement in assignment subdirectory. #### Submit your solutions as pull-requests to the *solutions* subdirectory in this repository. (i.e. submit your solution file in the SOLUTIONS subdirectory.) You are free to choose any language you wish.
-#### ADD YOUR OWN FILE OF CODE. No editings in previous code.😊 +#### ADD YOUR OWN FILE OF CODE. No editings in the previous code.😊😊 You may also add reference of question you have solved in your PR description : #### #[issue no] Guidelines ========== -Make a PR for the solution to the question, specify the issue number in comment. +Make a PR for the solution to the question, specify the issue number in the comment.

+thanks!! :-) ## IF YOU LIKE US, GIVE THIS REPOSITORY A ⭐. -#### Join the Gitter discussion room
-https://gitter.im/bvphec/Lobby -## NOTE - Only valid PR's related to issues will be merged. +## NOTE - Only valid PR's related to issues will be merged....... :-) diff --git a/SOLUTIONS/ OctalDecimalConversion.c b/SOLUTIONS/ OctalDecimalConversion.c new file mode 100644 index 00000000..5e58a4d9 --- /dev/null +++ b/SOLUTIONS/ OctalDecimalConversion.c @@ -0,0 +1,63 @@ +#include +#include + +int convertDecimalToOctal(int decimalNumber); +long long convertOctalToDecimal(int octalNumber); +int main() +{ + int choice,decimalNumber,octalNumber; + printf("Select what you want to convert:\n"); + printf("1. Decimal to Octal:\n"); + printf("2. Octal to Decimal:\n"); + scanf("%d",&choice); + switch(choice) + { + case 1: + printf("Enter a decimal number: "); + scanf("%d",&decimalNumber); + printf("%d in decimal = %d in octal", decimalNumber, convertDecimalToOctal(decimalNumber)); + break; + + case 2: + printf("Enter an octal number: "); + scanf("%d", &octalNumber); + printf("%d in octal = %lld in decimal", octalNumber, convertOctalToDecimal(octalNumber)); + break; + default : + printf("Wrong choice!\n"); + + + + } + return 0; +} + +int convertDecimalToOctal(int decimalNumber) +{ + int octalNumber = 0, i = 1; + + while (decimalNumber != 0) + { + octalNumber += (decimalNumber % 8) * i; + decimalNumber /= 8; + i *= 10; + } + + return octalNumber; +} + +long long convertOctalToDecimal(int octalNumber) +{ + int decimalNumber = 0, i = 0; + + while(octalNumber != 0) + { + decimalNumber += (octalNumber%10) * pow(8,i); + ++i; + octalNumber/=10; + } + + i = 1; + + return decimalNumber; +} \ No newline at end of file diff --git a/SOLUTIONS/12 hr format to 24 hr format b/SOLUTIONS/12 hr format to 24 hr format new file mode 100644 index 00000000..c2bcc8cd --- /dev/null +++ b/SOLUTIONS/12 hr format to 24 hr format @@ -0,0 +1,23 @@ +import os +import sys + + +def timeConversion(s): + if s[-2:] == "AM" and s[:2] == "12": + return "00" + s[2:-2] + elif s[-2:] == "AM": + return s[:-2] + elif s[-2:] == "PM" and s[:2] == "12": + return s[:-2] + else: + return str(int(s[:2]) + 12) + s[2:8] +if __name__ == '__main__': + f = open(os.environ['OUTPUT_PATH'], 'w') + + s = input() + + result = timeConversion(s) + + f.write(result + '\n') + + f.close() diff --git a/SOLUTIONS/12hrto24hrformat.js b/SOLUTIONS/12hrto24hrformat.js new file mode 100644 index 00000000..77db1209 --- /dev/null +++ b/SOLUTIONS/12hrto24hrformat.js @@ -0,0 +1,16 @@ +function convertTimeTo24Hr(time_12hr) { + var time = time_12hr.split(':'); + var time_24hr = ''; + if (time_12hr.substr(-2) === 'AM' && time[0] === '12') { + time_24hr = '00'; + } + else if (time_12hr.substr(-2) == 'PM' && time[0] < 12) { + time_24hr = parseInt(time[0]) + 12; + } + else { + time_24hr = time[0]; + } + time_24hr += time_12hr.substr(2,6); + return time_24hr; +} +console.log(convertTimeTo24Hr('07:05:45PM')); diff --git a/SOLUTIONS/1_Common_Elements.c b/SOLUTIONS/1_Common_Elements.c new file mode 100644 index 00000000..1682ed92 --- /dev/null +++ b/SOLUTIONS/1_Common_Elements.c @@ -0,0 +1,39 @@ +//To print all comman elements in the Given three sorted Array + +#include +void Common_Elements(int A[], int B[], int C[], int a, int b, int c) { + int i = 0,j = 0, k = 0; // Intializing the Index + // Transverse Through all three arrays simultaneously using indexes i,j,k. + printf("Comman Elements are :\n"); + while(i +// Function to find the kth Even Natural Number +int Num(int k) +{ + if(k > 0) + return Num(k-1) + 2; //Num is reducing and addition of 2 each time + else + return 0; //Loop Terminating Condition +} + +int main() +{ + int n; + printf("Enter the Value of K:\n "); + scanf("%d", &n); + printf("The kth Even Natural Number is %d\n", Num(n)); // Printing The kth Even Natural Number + return 0; +} diff --git a/SOLUTIONS/3rd Largest number in Unsorted Array b/SOLUTIONS/3rd Largest number in Unsorted Array new file mode 100644 index 00000000..48e11427 --- /dev/null +++ b/SOLUTIONS/3rd Largest number in Unsorted Array @@ -0,0 +1,12 @@ +#python +n = input("enter the size of array") +l =[] +for i in range(0,n+1): + l[i] = input("enter element") +for i in range(0,3): + large = l[0] + for j in range(0,n+1): + if l[i] > large : + large = l[i] + l.remove(large) +print("3rd largest element is ",large) diff --git a/SOLUTIONS/3rd largest.py b/SOLUTIONS/3rd largest.py new file mode 100644 index 00000000..09f4153b --- /dev/null +++ b/SOLUTIONS/3rd largest.py @@ -0,0 +1,10 @@ +Arr = list(map(int, input("enter numbers separated by space = ").split())) + +Max1 = Max2 = Max3 = min(Arr) + +for x in range(1, len(Arr)): + if(Arr[x] > Max1): Max1, Max2, Max3 = Arr[x], Max1, Max2 + elif(Max1 >= Arr[x] > Max2): Max2, Max3 = Arr[x], Max2 + elif(Max1 >= Max2 >= Arr[x] > Max3): Max3 = Arr[x] + +print("third Max = ", Max3) diff --git a/SOLUTIONS/3rd-Largest-number-in-Unsorted-Array.swift b/SOLUTIONS/3rd-Largest-number-in-Unsorted-Array.swift new file mode 100644 index 00000000..53624db1 --- /dev/null +++ b/SOLUTIONS/3rd-Largest-number-in-Unsorted-Array.swift @@ -0,0 +1,32 @@ +import Foundation + +/* + This method takes an unsorted array in input & returns the third largest number form Array as input + Time complexoty: O(n) + */ +func thirdLargetInArray(arr:[Int]) { + var first:Int = arr[0] + var second:Int = 0 + var third:Int = 0 + + for i in 0.. first && arr[i] != first { + third = second + second = first + first = arr[i] + } + else if arr[i] > second && arr[i] != second && arr[i] != first { + third = second + second = arr[i] + } + else if arr[i] > third && arr[i] != third && arr[i] != first && arr[i] != second { + print(second) + third = arr[i] + print("Third after changing = \(third)") + } + } + print("Third largest element in array is \(third)") +} + +let inputArr = [4,5,3,2,15,7,6,25,13,14,17,8,9,18,17,17,25,26] +thirdLargetInArray(arr: inputArr) diff --git a/SOLUTIONS/3rdMax.py b/SOLUTIONS/3rdMax.py new file mode 100644 index 00000000..9db1696e --- /dev/null +++ b/SOLUTIONS/3rdMax.py @@ -0,0 +1,22 @@ +# arr, m = list(map(int, input().strip().split())), 0 +import random +randArr = [] + +def randomArray(n): + for v in range(n): + randArr.append(random.randrange(100, 1000)) + return randArr + + +from time import time + +t1 = time() +# arr = [1, 21, 31, 25, 68, 98, 56] +arr = randomArray(1000) +m = 0 +for v in range(3): + m = max(arr) + arr.remove(m) +t2 = time() +print(m) +print("It took ", t2 - t1, " time to finish this algorithm.") diff --git a/SOLUTIONS/A game of robots.cpp b/SOLUTIONS/A game of robots.cpp new file mode 100644 index 00000000..29e2c214 --- /dev/null +++ b/SOLUTIONS/A game of robots.cpp @@ -0,0 +1,37 @@ +#include +#include +#include +#include +#define ll long long int + +using namespace std; +int main(void) { + int t; + cin >> t; + + while (t--) { + string str; + cin >> str; + int l = str.length(), flag = 1;//cout << l; + int a[l] = {0}; + + for (int i = 0; i < l; i++) { + if (str[i] != '.') { + int temp = str[i]-'0'; + for (int j = i; j <= i+temp && j < l; j++) a[j]++; + for (int j = i-1; j >= i-temp && j >= 0; j--) a[j]++; + + } + } + + for (int i = 0; i < l; i++) {//cout<< a[i] << " "; + if (a[i] > 1) { + flag = 0; + break; + } + } + + if (flag) cout << "safe\n"; + else cout << "unsafe\n"; + } +} diff --git a/SOLUTIONS/A new way to say hello world.java b/SOLUTIONS/A new way to say hello world.java new file mode 100644 index 00000000..153e1cb4 --- /dev/null +++ b/SOLUTIONS/A new way to say hello world.java @@ -0,0 +1,20 @@ +public class hello +{ + + public static void main(String args[]) + { + + System.out.print("H"); + System.out.print("E"); + System.out.print("Y"); + System.out.print("L"); + System.out.print("L"); + System.out.print("O"+\t); + System.out.print("W"); + System.out.print("O"); + System.out.print("R"); + System.out.print("L"); + System.out.print("D"); + + } + } //end class diff --git a/SOLUTIONS/ACIIIProduct.py b/SOLUTIONS/ACIIIProduct.py index 2b762a63..f1724183 100644 --- a/SOLUTIONS/ACIIIProduct.py +++ b/SOLUTIONS/ACIIIProduct.py @@ -1,8 +1,9 @@ -inputString = input() +# author: Higor Santos de Brito Dantas -result = 1 +string = raw_input() +product = 1 -for i in range(len(inputString)) : - result = result * ord(inputString[i]) +for e in string: + product *= ord(e) -print(result) \ No newline at end of file +print product \ No newline at end of file diff --git a/SOLUTIONS/ACIIIproduct.py b/SOLUTIONS/ACIIIproduct.py new file mode 100644 index 00000000..465f3b4e --- /dev/null +++ b/SOLUTIONS/ACIIIproduct.py @@ -0,0 +1,10 @@ +from __future__ import print_function +# author: Higor Santos de Brito Dantas + +string = raw_input() +product = 1 + +for e in string: + product *= ord(e) + +print(product) \ No newline at end of file diff --git a/SOLUTIONS/ASCII.PY b/SOLUTIONS/ASCII.PY new file mode 100644 index 00000000..424f3d42 --- /dev/null +++ b/SOLUTIONS/ASCII.PY @@ -0,0 +1,12 @@ +# Convertion from text to ASCII codes +def ASCIISentence( str ): + c =1 + for i in str: + print(ord(i), end = '') + c*=ord(i) + print('\nproduct of ascii values=\n', c) + +# Driver code +str = input("Enter an ASCII Sentence: ") +print("ASCII Sentence:") +ASCIISentence(str) diff --git a/SOLUTIONS/ASCII_product.c b/SOLUTIONS/ASCII_product.c new file mode 100644 index 00000000..0fd500d6 --- /dev/null +++ b/SOLUTIONS/ASCII_product.c @@ -0,0 +1,20 @@ +#include +#include +#include + +int main(void) +{ + char str=(char*)malloc(64*sizeof(char)); + printf("Enter characters : "); + gets(str); + int len = strlen(str)-1; + int count = 0; + int total = 1; + while (count <= len) + { + total *= str[count]; + count++; + } + printf("Result : %d\n", total); + return 0; +} diff --git a/SOLUTIONS/ATM_Problem_Solution b/SOLUTIONS/ATM_Problem_Solution new file mode 100644 index 00000000..1209c3f2 --- /dev/null +++ b/SOLUTIONS/ATM_Problem_Solution @@ -0,0 +1,15 @@ +a = int(input()) + +for _ in range(a): + n,total_amt = [int(v) for v in input().split()] + people_amt = [int(v) for v in input().split()] + result="" + for i in range(len(people_amt)): + if(total_amt>=people_amt[i]): + total_amt=total_amt-people_amt[i] + result=result+"1" + else: + result+="0" + + +print(result) diff --git a/SOLUTIONS/ATM_problem_sol.c b/SOLUTIONS/ATM_problem_sol.c new file mode 100644 index 00000000..51f06158 --- /dev/null +++ b/SOLUTIONS/ATM_problem_sol.c @@ -0,0 +1,26 @@ +#include +void main() +{ + int i,j,n,t,a[100]; + long k,a[100]s; + scanf("%d",&t); + for(i=0;i1: + print('unsafe') + break + else: + print('safe') diff --git a/SOLUTIONS/Advanced prob_FizzBuzz.py b/SOLUTIONS/Advanced prob_FizzBuzz.py new file mode 100644 index 00000000..82e5b3d6 --- /dev/null +++ b/SOLUTIONS/Advanced prob_FizzBuzz.py @@ -0,0 +1,20 @@ +import numpy +T=int(input("No.of Test Cases")) +s=input() +l=s.split() +for i in range (0,T): + for j in range (1,int(l[i])+1): + count=0 + if(j%15==0): + print("FizzBuzz") + count=1 + else: + if(j%3==0): + print("Fizz") + count=1 + if(j%5==0): + print("Buzz") + count=1 + if(count==0): + print(j) + diff --git a/SOLUTIONS/Armstrong.py b/SOLUTIONS/Armstrong.py new file mode 100644 index 00000000..9d513c8d --- /dev/null +++ b/SOLUTIONS/Armstrong.py @@ -0,0 +1,11 @@ +Num = int(input("Enter a number = ")) + +temp = Num + +arm = 0 +while(temp): + arm += (temp%10)**3 + temp//=10 + +if(arm == Num): print(Num, "is Armstrong") +else: print(Num, "is NOT Armstrong") diff --git a/SOLUTIONS/BeginerProblem2.py b/SOLUTIONS/BeginerProblem2.py new file mode 100644 index 00000000..0e440fbf --- /dev/null +++ b/SOLUTIONS/BeginerProblem2.py @@ -0,0 +1,11 @@ +#BeginerProblem2 +n = int(input()) +countBest = [] +for i in range(0,n): + countBest.append(0) + nums = int(input()) + for j in range(0,nums): + if int(input())%2 == 0: + countBest[i] += 1 +for i in countBest: + print (i) diff --git a/SOLUTIONS/BeginnerProblem.js b/SOLUTIONS/BeginnerProblem.js new file mode 100644 index 00000000..48748895 --- /dev/null +++ b/SOLUTIONS/BeginnerProblem.js @@ -0,0 +1,42 @@ +function beginnerProblem(arrNumber) { + try { + if(arrNumber.length == 1) { + return arrNumber[0] + } else { + let sort = arrNumber.sort(); + let count = 0; + let arrObj = [] + let now = 0; + for(let i = 0 ;i currentCounter) { + current = num.num + currentCounter = num.count + } + } + return current; + } + } catch(err) { + return 'MUST BE AN ARRAY OF NUMBER' + } +} + +let arr1 = [2] +let arr2 = [1,2,3] +let arr3 = [1,1,2] +let arr4 = [9,2,2,3,1,3,9,3,2,3,1,3] +console.log(beginnerProblem(arr4)) \ No newline at end of file diff --git a/SOLUTIONS/BeginnerProblem2.go b/SOLUTIONS/BeginnerProblem2.go new file mode 100644 index 00000000..7eef1f5d --- /dev/null +++ b/SOLUTIONS/BeginnerProblem2.go @@ -0,0 +1,36 @@ +package main + +import "fmt" + +func main() { + // - input number of iteration + I := 0 + fmt.Scanf("%d", &I) + for i := 0; i < I; i++ { + fmt.Printf("Iteration#%d\n", i+1) + N := 0 + arr := []int{} + fmt.Scanf("%d", &N) + + // - input number to check + for j := 0; j < N; j++ { + tmp := 0 + fmt.Scanf("%d", &tmp) + arr = append(arr, tmp) + } + // - print out result + res := divBy2(arr) + fmt.Printf("Output#%d: %d\n\n", (i + 1), res) + } + +} + +func divBy2(arr []int) (counter int) { + for i := 0; i < len(arr); i++ { + if arr[i]%2 == 0 { + counter++ + } + } + + return +} diff --git a/SOLUTIONS/BeginnerProblem_2.0.c b/SOLUTIONS/BeginnerProblem_2.0.c new file mode 100644 index 00000000..19dbf6b8 --- /dev/null +++ b/SOLUTIONS/BeginnerProblem_2.0.c @@ -0,0 +1,30 @@ +#include + +int main() +{ +int t,p, count[10]={0},a[20],i,j,k; + +scanf("%d",&t); + + for(i=0;i int + Returns the number of even numbers in a given list. + ''' + a=0 + for x in alist: + if x%2==0: + a+=1 + return a + +t = int(input("Please enter the number of test cases ")) +l = [] +for x in range(t): + b = input("Enter a list of numbers ").strip().split() + for x in range(len(b)): + b[x]=int(b[x]) + l.append(b) +for x in range(t): + print(find_best_numbers(l[x])) + + diff --git a/SOLUTIONS/BeginnersProblem2.0.py b/SOLUTIONS/BeginnersProblem2.0.py new file mode 100644 index 00000000..292efc3a --- /dev/null +++ b/SOLUTIONS/BeginnersProblem2.0.py @@ -0,0 +1,7 @@ +#Beginners problem +#python +n = input() +for i in range(0,n) + num = input() + if num%2 == 0: + print(num) diff --git a/SOLUTIONS/BeginnersProblem2.c b/SOLUTIONS/BeginnersProblem2.c new file mode 100644 index 00000000..8919966a --- /dev/null +++ b/SOLUTIONS/BeginnersProblem2.c @@ -0,0 +1,28 @@ +#include +int even(int n1); +int main(){ + int n; + scanf("%d",&n); + for(int i=0;i +using namespace std; +#define pb push_back +#define ll long long int + +int main() +{ + ll t,n,m,l,s,x,y,mn,mx,sumh,suma,mid; + vector h,a; + cin>>t; + while(t--) + { + h.clear(); + a.clear(); + cin>>n>>m>>l; + + sumh=suma=0; + mx=INT_MAX; + for(int i=0;i>x>>y; + h.pb(x); + a.pb(y); + sumh+=x; + suma+=y; + mx=min(mx,(ll)ceil(((m-x)*1.0)/y)); + } + mn=(ll)ceil(((m-sumh)*1.0)/suma); + if(mn<0) + mn=0; + + if(mx<0) + mx=0; + + //binary search + + while(mn<=mx) + { + mid=mn+(mx-mn)/2; + sumh=suma=0; + for(int i=0;i=l) + sumh+=th; + + if(ta>=l) + suma+=ta; + } + if((sumh>=m)&&(suma=m) + mx=mid; + else + mn=mid+1; + } + cout< +#include +#include + +using namespace std; + +int main() { + + int qtd, count = 0, len, exponent; + cin >> qtd; + + for(int i = 0; i < qtd; i++) { + char binary[100]; + cin >> binary; + + len = strlen(binary); + for (int i = len; i >= 0; i--) { + if(binary[i-1] == '1') { + exponent = len - i; + count += pow(2, exponent); + } + } + + if (count % 3 == 0){ + cout << "1" << endl; + } else { + cout << "0" << endl; + } + + count = 0; + } + + return 0; +} \ No newline at end of file diff --git a/SOLUTIONS/Binary_Multiple_of_3.py b/SOLUTIONS/Binary_Multiple_of_3.py new file mode 100644 index 00000000..4eb4be3c --- /dev/null +++ b/SOLUTIONS/Binary_Multiple_of_3.py @@ -0,0 +1,16 @@ + + + +ntcases = int(input("Please type the number of test cases: ")) +for i in range(ntcases): + binaryString = input("Please type a binary number: ") + exp = 0 + result = 0 + for bit in binaryString: + result += int(bit)*(2**exp) + exp = exp+1 + if (result%3 == 0): + print("1") + else: + print("0") + \ No newline at end of file diff --git a/SOLUTIONS/Choosing the judges.cpp b/SOLUTIONS/Choosing the judges.cpp new file mode 100644 index 00000000..e195d3a3 --- /dev/null +++ b/SOLUTIONS/Choosing the judges.cpp @@ -0,0 +1,36 @@ +#include +# include + +using namespace std; + +int main() +{ + int tests; + cin >> tests; + + while (tests --){ + + long int n; + cin >> n; + vector marks, solution ; + + marks.resize(n); + solution.resize(n); + + for ( int i = 0 ; i < n ; i ++) + cin >> marks[i]; + + solution[0] = marks [0]; + + solution[1] = max ( marks[1], marks[0]); + + + for ( int i = 2 ; i < n ; i ++) + solution[i] = max ( solution[i-2] + marks[i], marks[i-1] ); + + cout << marks[n-1] << endl; + + } + +return 0; +} diff --git a/SOLUTIONS/Circular primes.py b/SOLUTIONS/Circular primes.py new file mode 100644 index 00000000..d3adacd1 --- /dev/null +++ b/SOLUTIONS/Circular primes.py @@ -0,0 +1,39 @@ +primes = [] +a=int(input()) +for possiblePrime in range(2,a): + isPrime = True + for num in range(2, int(possiblePrime ** 0.5) + 1): + if possiblePrime % num == 0: + isPrime = False + break + + if isPrime: + primes.append(possiblePrime) +j=0 +counter=0 +l=[] +while(j +using namespace std; + +long long solve (long long K, long long N) { + // write code here + + + + vector < long long > vec (N+1); + //vector vecK (K+1); + //iota ( begin(vecK), end(vecK), 0); + + vec[0] = 1; + long long sum = 1; + + for ( long long i = 1 ; i < K+1; i ++){ + vec[i] = sum ; + sum += sum ; + sum = sum % 1000000007; + } + + sum -= vec[0]; + //cout << sum << endl; + for ( long long i = K+1; i <= N; i ++){ + for ( int j = i-1 ; j >= i-K; j--) + vec[i] += vec[j] ; + vec[i] %= 1000000007; + + } + + for ( int i = 0 ; i <= N ; i ++ ) + cout << vec[i] << " "; + + return vec[N]; +} + +int main() { + + ios::sync_with_stdio(0); + cin.tie(0); + int T; + cin >> T; + for(int t_i=0; t_i> N; + long long K; + cin >> K; + + long long out_; + out_ = solve(K, N); + cout << out_; + cout << "\n"; + } +} diff --git a/SOLUTIONS/DBT.dev b/SOLUTIONS/DBT.dev new file mode 100644 index 00000000..9ea4c94b --- /dev/null +++ b/SOLUTIONS/DBT.dev @@ -0,0 +1,68 @@ +#include +#include +#include +#include +using namespace std; +struct bst{ + int data; + struct bst *left; + struct bst *right; +}; +struct bst *root=NULL; +struct bst * create(struct bst *root,int data){ + struct bst *temp=(struct bst *)malloc(sizeof(struct bst )); + temp->data=data; + temp->left=NULL; + temp->right=NULL; + return temp; +} +struct bst * insert(struct bst *root,int data){ + if(root==NULL){ + struct bst *temp; + temp=create(root,data); + root=temp; + + return root; + } + else if(datadata){ + root->left=insert(root->left,data); + } + else{ + root->right=insert(root->right,data); + } + return root; +} +void diagonal(struct bst *root){ int dl; + queue > q; + map > m; + q.push(make_pair(root,0)); + while(!q.empty()){ + pair p=q.front(); + root=p.first; + dl=p.second; + q.pop(); + m[dl].push_back(root->data); + if(root->left) + q.push(make_pair(root->left,dl+1)); + if(root->right) + q.push(make_pair(root->right,dl)); + } + map >::iterator it; + for(it=m.begin();it!=m.end();it++){ + vector::iterator iter; + for(iter=it->second.begin();iter!=it->second.end();iter++){ + cout<<*iter; + } + cout< +void main(){ + +int s, d, n = 1; + +printf("Enter the number:\n"); +scanf("%d", &s); + +d=s; + +while(s>0){ + n = n*s; + s--; + } + + printf(" Factorial of %d is %d", d, n); +} diff --git a/SOLUTIONS/Fibonacci.cob b/SOLUTIONS/Fibonacci.cob new file mode 100644 index 00000000..5375b78e --- /dev/null +++ b/SOLUTIONS/Fibonacci.cob @@ -0,0 +1,25 @@ +IDENTIFICATION DIVISION. + PROGRAM-ID. "Fibonacci". + ENVIRONMENT DIVISION. + DATA DIVISION. + WORKING-STORAGE SECTION. + 01 ix BINARY-C-LONG VALUE 0. + 01 first-number BINARY-C-LONG VALUE 0. + 01 second-number BINARY-C-LONG VALUE 1. + 01 temp-number BINARY-C-LONG VALUE 1. + 01 display-number PIC Z(19)9. + PROCEDURE DIVISION. +* This is the start of the program + START-PROGRAM. + MOVE first-number TO display-number. + DISPLAY display-number. + MOVE second-number TO display-number. + DISPLAY display-number. + PERFORM VARYING ix FROM 1 BY 1 UNTIL ix = 90 + ADD first-number TO second-number GIVING temp-number + MOVE second-number TO first-number + MOVE temp-number TO second-number + MOVE temp-number TO display-number + DISPLAY display-number + END-PERFORM. + STOP RUN. \ No newline at end of file diff --git a/SOLUTIONS/Fibonacci.java b/SOLUTIONS/Fibonacci.java new file mode 100644 index 00000000..79c3dba2 --- /dev/null +++ b/SOLUTIONS/Fibonacci.java @@ -0,0 +1,20 @@ +public class Fibonacci { + + + static int n1=0,n2=1,n3=0; + static void printFibonacci(int count){ + if(count>0){ + n3 = n1 + n2; + n1 = n2; + n2 = n3; + System.out.print(" "+n3); + printFibonacci(count-1); + } + } + public static void main(String args[]){ + int count=10; + System.out.print(n1+" "+n2);//printing 0 and 1 + printFibonacci(count-2);//n-2 because 2 numbers are already printed + + } + } diff --git a/SOLUTIONS/Find Sum square Difference.py b/SOLUTIONS/Find Sum square Difference.py new file mode 100644 index 00000000..644a8010 --- /dev/null +++ b/SOLUTIONS/Find Sum square Difference.py @@ -0,0 +1,17 @@ +def calculate(n): + t1 = 0 + t2 = 0 + for x in range(n+1): + t1 += x*x + for x in range(n+1): + t2 += x + t2 = t2*t2 + return t2-t1 + +line1 = int(input("How many test cases do you have?")) +list1 = [] +for x in range(line1): + n = int(input("Enter an integer")) + list1.append(n) +for x in range(line1): + print(calculate(list1[x])) diff --git a/SOLUTIONS/Find_Sum_square_Difference.py b/SOLUTIONS/Find_Sum_square_Difference.py index 39e8a7d2..5a6ca79d 100644 --- a/SOLUTIONS/Find_Sum_square_Difference.py +++ b/SOLUTIONS/Find_Sum_square_Difference.py @@ -1,34 +1,21 @@ -# -*- coding: utf-8 -*- -""" -Spyder Editor +def sum_square_diff(N): + sum1 = 0 + sum2 = 0 + for num in range(1, N+1): + sum1 += num ** 2 -This is a temporary script file. -""" + for num in range(1, N+1): + sum2 += num -message = "Pick a number:" -a = input(message) -a = int(a) + sum2 = sum2 ** 2 + return abs(sum1-sum2) -if a > 10**4: - print("Number needs to be less than 10,000") +N_list = [] +T = int(input()) -if a <= 10**4: - - #computing the sum of the squares - somma_square = 0 - for i in range(1,a+1): - square1 = i**2 - somma_square1 = somma_square + square1 - somma_square = somma_square1 - - #computing the square of the sum - somma = 0 - for i in range(1,a+1): - somma1 = somma + i - somma = somma1 - square_somma = somma**2 - - #taking the absolute value of the difference - diff = abs(somma_square - square_somma) - print(diff) - +for _ in range(T): + N = int(input()) + N_list.append(N) + +for N in N_list: + print(sum_square_diff(N), end="\n") diff --git a/SOLUTIONS/Finding_Successor_in_BST b/SOLUTIONS/Finding_Successor_in_BST new file mode 100644 index 00000000..a48e1245 --- /dev/null +++ b/SOLUTIONS/Finding_Successor_in_BST @@ -0,0 +1,24 @@ +public BSTNode findSuccessor(BSTNode root, BSTNode target) { + + if(target.right != null) { // if target has a right child, we can go on just by checking for the leftest node in the right subtree. + BSTNode min = root; + while(root != null) + min = min.left; + return min; + } + + // if target doesn't have right child, we will go down starting from root till the target node. While going down, we will check + the deepest number that is greater than the target. + BSTNode successor; + while(root != null) { + if(target == root) // That means we reach to the target and we have already found the successor. + break; + else if(target.data < root.data) { + successor = root; + root = root.left; + } + else // if target's data is greater than the root's data. + root = root.right; + } + return successor; +} diff --git a/SOLUTIONS/First_Hundred_natural_no_cubic.py b/SOLUTIONS/First_Hundred_natural_no_cubic.py new file mode 100644 index 00000000..6720f75f --- /dev/null +++ b/SOLUTIONS/First_Hundred_natural_no_cubic.py @@ -0,0 +1,5 @@ +cubic_natural_no=[] +for number in range(1,101): + cubic_natural_no.append(number**3) + +print(cubic_natural_no) diff --git a/SOLUTIONS/FizzBuzz.cpp b/SOLUTIONS/FizzBuzz.cpp new file mode 100644 index 00000000..f15dd4da --- /dev/null +++ b/SOLUTIONS/FizzBuzz.cpp @@ -0,0 +1,17 @@ +#include +using namespace std; +int main() { + int n, t; + cin >> t; + while(t--) { + cin >> n; + for (int i = 1; i <= n; ++i) + { + if((i%3 != 0) && (i%5 != 0)) cout << i; + if(i%3 == 0) cout << "Fizz"; + if(i%5 == 0) cout << "Buzz"; + cout << endl; + } + } + return 0; +} \ No newline at end of file diff --git a/SOLUTIONS/FizzBuzz.go b/SOLUTIONS/FizzBuzz.go new file mode 100644 index 00000000..8307f097 --- /dev/null +++ b/SOLUTIONS/FizzBuzz.go @@ -0,0 +1,26 @@ +package main + +import "fmt" + +func main() { + I := 0 + fmt.Scanf("%d", &I) + for i := 0; i < I; i++ { + fmt.Printf("Iteration#%d\n", i+1) + N := 0 + fmt.Scanf("%d", &N) + + for n := 1; n <= N; n++ { + if n%3 == 0 && n%5 == 0 { + fmt.Println("FizzBuzz") + } else if n%3 == 0 { + fmt.Println("Fizz") + } else if n%5 == 0 { + fmt.Println("Buzz") + } else { + fmt.Println(n) + } + } + } + +} diff --git a/SOLUTIONS/FizzBuzz.py b/SOLUTIONS/FizzBuzz.py new file mode 100644 index 00000000..b089dc1a --- /dev/null +++ b/SOLUTIONS/FizzBuzz.py @@ -0,0 +1,11 @@ +r1=int(input("Please enter the starting number: ")) +r2=int(input("Please enter the ending number: ")) +for i in range(r1,r2+1): + if(i%3==0 and i%5!=0): + print("Fizz") + elif(i%3!=0 and i%5==0): + print("Buzz") + elif(i%3==0 and i%5==0): + print("FizzBuzz") + else: + print(i) diff --git a/SOLUTIONS/Fizzbuzz Assignment Answer b/SOLUTIONS/Fizzbuzz Assignment Answer new file mode 100644 index 00000000..efde8d49 --- /dev/null +++ b/SOLUTIONS/Fizzbuzz Assignment Answer @@ -0,0 +1,40 @@ +import java.io.BufferedReader; +import java.io.InputStreamReader; + + +class TestClass { + public static void main(String args[] ) throws Exception { + + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + String line = br.readLine(); + int N = Integer.parseInt(line); + line=br.readLine(); + String str[]=new String[N]; + int arr[]=new int[N]; + str=line.split(" "); + for(int l=0;l +int main() +{ + int rows, i, j, k, number= 1; + + printf("Enter number of rows: "); + scanf("%d",&rows); + + for(i=1; i <=rows; i++) + { + for(j=1; j <=i ; j++) + { + printf("%d ",number++); + } + printf("\n"); + } + return 0; +} \ No newline at end of file diff --git a/SOLUTIONS/Game Of Robots b/SOLUTIONS/Game Of Robots new file mode 100644 index 00000000..99cfe51f --- /dev/null +++ b/SOLUTIONS/Game Of Robots @@ -0,0 +1,17 @@ +for _ in range(int(input())): + s = input() + ans = 'safe' + arr = [] + for i in range(len(s)): + if s[i] != '.': + if s[i] == '0': + arr.append(i) + else: + arr.append(i-int(s[i])) + arr.append(i+int(s[i])) + for i in range(len(arr)-1): + if arr[i+1] - arr[i] <= 0: + ans = 'unsafe' + break + + print(ans) diff --git a/SOLUTIONS/GirlFriend.java b/SOLUTIONS/GirlFriend.java new file mode 100644 index 00000000..e59c5b7b --- /dev/null +++ b/SOLUTIONS/GirlFriend.java @@ -0,0 +1,157 @@ +import java.util.HashMap; +import java.util.HashSet; +import java.util.LinkedList; +import java.util.Scanner; + +public class GirlFriend +{ + private HashMap nodeLookup = new HashMap(); + + public static class Response { + int distance; + boolean exists; + Response(int d, boolean e) + { + this.distance = d; + this.exists = e; + } + + public void setExists(boolean p) + { + this.exists = p; + } + + public void setDistance(int d) + { + this.distance = d; + } + + public int getDistance() + { + return this.distance; + } + } + + public static class Node { + private int id; + LinkedList children = new LinkedList(); + private Node(int nodeid) + { + this.id = nodeid; + } + } + + private Node getNode(int id) + { + return nodeLookup.get(id); + } + + public void addEdge(int source, int destination) + { + Node s = getNode(source); + Node d = getNode(destination); + s.children.add(d); + } + + public Response hasPathDFS(int source, int destination) + { + Node s = getNode(source); + Node d = getNode(destination); + HashSet visited = new HashSet(); + + return hasPathDFS(s, d, visited, new Response(0, false)); + } + + public Response hasPathDFS(Node source, Node destination, HashSet visited, Response r) + { + + // if the node is already visited, it means that no path exists from source to destination + if(visited.contains(source.id)) + { + r.setExists(false); + return r; + } + + // add node to visited set + visited.add(source.id); + + // if the source node is the destination + if(source == destination) + { + r.setExists(true); + return r; + } + + + // check if a path exists from any child of source to destination + for(Node child : source.children) + { + if(hasPathDFS(child, destination, visited, r).exists) + { + r.setDistance(r.getDistance() + 1); + r.setExists(true); + return r; + } + } + + // no path exists from any child of source to destination + return r; + } + + public static void main(String[] args) + { + // TODO Auto-generated method stub + Scanner sc = new Scanner(System.in); + GirlFriend graph = new GirlFriend(); + int countries = sc.nextInt(); + + for(int i = 0; i < countries - 1; i++) + { + int a = sc.nextInt(); + int b = sc.nextInt(); + + if(!graph.nodeLookup.containsKey(a)) + { + Node x = new Node(a); + graph.nodeLookup.put(a, x); + } + if(!graph.nodeLookup.containsKey(b)) + { + Node y = new Node(b); + graph.nodeLookup.put(b, y); + } + + graph.addEdge(a, b); + graph.addEdge(b, a); + } + + int girls = sc.nextInt(); + int girlFriend = -1, distance = -1; + for(int i = 0; i < girls; i++) + { + int girl = sc.nextInt(); + Response r = graph.hasPathDFS(1, girl); + if(r.exists) + { + if(distance == -1) + { + girlFriend = girl; + distance = r.distance; + } + else if(r.distance < distance) + { + girlFriend = girl; + distance = r.distance; + } + else if(r.distance == distance) + { + if(girl < girlFriend) + { + girlFriend = girl; + } + } + } + } + System.out.println(girlFriend); + } +} diff --git a/SOLUTIONS/HELLOWORLD.PY b/SOLUTIONS/HELLOWORLD.PY new file mode 100644 index 00000000..88c154d6 --- /dev/null +++ b/SOLUTIONS/HELLOWORLD.PY @@ -0,0 +1 @@ +print("HELLO WORLD") diff --git a/SOLUTIONS/Hacktoberfest.py b/SOLUTIONS/Hacktoberfest.py new file mode 100644 index 00000000..872aefd2 --- /dev/null +++ b/SOLUTIONS/Hacktoberfest.py @@ -0,0 +1 @@ +print("I want a Tshirt") diff --git a/SOLUTIONS/HeLLoWoLd.py b/SOLUTIONS/HeLLoWoLd.py new file mode 100644 index 00000000..8e235769 --- /dev/null +++ b/SOLUTIONS/HeLLoWoLd.py @@ -0,0 +1 @@ +print("Hello World") \ No newline at end of file diff --git a/SOLUTIONS/Hello b/SOLUTIONS/Hello new file mode 100644 index 00000000..fd12ebb1 --- /dev/null +++ b/SOLUTIONS/Hello @@ -0,0 +1 @@ +Hello hi diff --git a/SOLUTIONS/Hello World.c b/SOLUTIONS/Hello World.c new file mode 100644 index 00000000..7cdced7a --- /dev/null +++ b/SOLUTIONS/Hello World.c @@ -0,0 +1,6 @@ +#include //preprocessor directive and command +int main()//main method starts +{//main block starts +printf("Hello world");//prints the output ie Hello world +returrn 0;// return 0 after the execution of main method +}//main block ends diff --git a/SOLUTIONS/Hello World.html b/SOLUTIONS/Hello World.html new file mode 100644 index 00000000..4b1dc1f5 --- /dev/null +++ b/SOLUTIONS/Hello World.html @@ -0,0 +1,15 @@ + + + + First html + + +

Hello World

+

Hello World

+

Hello World

+

Hello World

+
Hello World
+
Hello World
+ + + \ No newline at end of file diff --git a/SOLUTIONS/Hello World.java b/SOLUTIONS/Hello World.java deleted file mode 100644 index 8fce9aad..00000000 --- a/SOLUTIONS/Hello World.java +++ /dev/null @@ -1 +0,0 @@ -System.out.println("Hello, World"); diff --git a/SOLUTIONS/Hello world.cpp b/SOLUTIONS/Hello world.cpp new file mode 100644 index 00000000..c1c7ac5e --- /dev/null +++ b/SOLUTIONS/Hello world.cpp @@ -0,0 +1,5 @@ +#include +void main() +{ +cout<<"Hello world"; +} \ No newline at end of file diff --git a/SOLUTIONS/Hello.ts b/SOLUTIONS/Hello.ts new file mode 100644 index 00000000..18716b51 --- /dev/null +++ b/SOLUTIONS/Hello.ts @@ -0,0 +1,7 @@ +let x = function HelloWorld(Name?) { + let hellow = "Hello World " + Name ? hellow+=` ${Name}`:"" + return hellow +} + +console.log(x()) \ No newline at end of file diff --git a/SOLUTIONS/HelloWorld.kt b/SOLUTIONS/HelloWorld.kt index 0b69e213..2330ae5c 100644 --- a/SOLUTIONS/HelloWorld.kt +++ b/SOLUTIONS/HelloWorld.kt @@ -1,3 +1,3 @@ -fun main(args: Array) { - println("Hello, World!") -} +fun main(args : Array) { + println("Hello, world!") +} \ No newline at end of file diff --git a/SOLUTIONS/HelloWorld.php b/SOLUTIONS/HelloWorld.php new file mode 100644 index 00000000..c400e8ca --- /dev/null +++ b/SOLUTIONS/HelloWorld.php @@ -0,0 +1,3 @@ + diff --git a/SOLUTIONS/HelloWorld.pike b/SOLUTIONS/HelloWorld.pike new file mode 100644 index 00000000..ae226fb1 --- /dev/null +++ b/SOLUTIONS/HelloWorld.pike @@ -0,0 +1,8 @@ +int main() + +{ + write("Hello World!"); + + return 0; + +} diff --git a/SOLUTIONS/HelloWorldProgram.java b/SOLUTIONS/HelloWorldProgram.java new file mode 100644 index 00000000..f27f8f56 --- /dev/null +++ b/SOLUTIONS/HelloWorldProgram.java @@ -0,0 +1,6 @@ +public class HelloWorldProgram { + public static void main(String[] args) { + // Prints "Hello, World" to the terminal window. + System.out.println("Hello, World"); + } +} diff --git a/SOLUTIONS/HelloWorld__SagarSuri.cpp b/SOLUTIONS/HelloWorld__SagarSuri.cpp new file mode 100644 index 00000000..ed642a65 --- /dev/null +++ b/SOLUTIONS/HelloWorld__SagarSuri.cpp @@ -0,0 +1,8 @@ +#include +using namespace std; + +int main() +{ + cout <<"\nHello World"<< endl; + return 0; +} diff --git a/Hello_World(in_C++).cpp b/SOLUTIONS/Hello_World(in_C++).cpp similarity index 100% rename from Hello_World(in_C++).cpp rename to SOLUTIONS/Hello_World(in_C++).cpp diff --git a/SOLUTIONS/Hello_World.cpp b/SOLUTIONS/Hello_World.cpp new file mode 100644 index 00000000..37743d45 --- /dev/null +++ b/SOLUTIONS/Hello_World.cpp @@ -0,0 +1,8 @@ +#include + +using namespace std; + +int main() { + cout << "Hello world" << endl; + return 0; +} \ No newline at end of file diff --git a/SOLUTIONS/Hello_World.html b/SOLUTIONS/Hello_World.html new file mode 100644 index 00000000..96508e0b --- /dev/null +++ b/SOLUTIONS/Hello_World.html @@ -0,0 +1,10 @@ + + + + Aman Nim + + +

"Hello World"

+

#HacktoberFest

+ + \ No newline at end of file diff --git a/SOLUTIONS/Hello_World.py b/SOLUTIONS/Hello_World.py new file mode 100644 index 00000000..f301245e --- /dev/null +++ b/SOLUTIONS/Hello_World.py @@ -0,0 +1 @@ +print("Hello World!") diff --git a/SOLUTIONS/Helloworld.php b/SOLUTIONS/Helloworld.php new file mode 100644 index 00000000..1e9db100 --- /dev/null +++ b/SOLUTIONS/Helloworld.php @@ -0,0 +1,12 @@ + + + + +

Idacio Dad Arnaldo Zibia

+ + + + + \ No newline at end of file diff --git a/SOLUTIONS/HidePage.html b/SOLUTIONS/HidePage.html new file mode 100644 index 00000000..93007198 --- /dev/null +++ b/SOLUTIONS/HidePage.html @@ -0,0 +1,24 @@ + + + + + + + +

this is heading

+

this is paragraph

+

my name is antima

+ + + + diff --git a/SOLUTIONS/LargestSubarrayPrime.py b/SOLUTIONS/LargestSubarrayPrime.py new file mode 100644 index 00000000..bd45122b --- /dev/null +++ b/SOLUTIONS/LargestSubarrayPrime.py @@ -0,0 +1,58 @@ +def isPrime(n): + """ + Simple primality test + """ + if n < 2: + return False + + for k in range(2, n): + if n % k == 0: + return False + return True + + +def findSubArray(list): + """ + Finds the largest sub-array having primes strictly greater than non-primes + i.e. + findSubArray([4, 7, 4, 7, 11, 5, 4, 4, 4, 5]) = + findSubArray([1, 9, 3, 4, 5, 6, 7, 8 ]) = + """ + # converts number list to a list of 0,1 indicated by its primality + binaryArray = [int(isPrime(k)) for k in list] + + # explore subarrays from biggest (length of list) to smallest (length=2) + # breaks when one subarray matches the requirements + lengthSubArray = len(binaryArray) + found = False + while( lengthSubArray > 1 and not found ): + + # move startIndex to create subarrays from same length + numberSubArrays = len(binaryArray) - lengthSubArray + 1 + for startIndex in range(0, numberSubArrays): + endIndex = startIndex + lengthSubArray + binarySubArray = binaryArray[startIndex:endIndex] + + # verify condition requested in subarray is met + found = sum(binarySubArray) > (lengthSubArray / 2) + if found: break + + lengthSubArray -= 1 + + # returns the subarray using the indexes from the binarySubArray found + return list[startIndex:endIndex] + + +def solveProblem(list): + """ + trivial function to return the specific length that problem asked + """ + return len(findSubArray(list)) + + +# Tests +arrays = [[4, 7, 4, 7, 11, 5, 4, 4, 4, 5],[1, 9, 3, 4, 5, 6, 7, 8 ]] +for array in arrays : + subArray = findSubArray(array) + print("The array {} has an ideal subarray {} of length {}.".format( + array, subArray, len(subArray))) diff --git a/SOLUTIONS/NUMBGAME.java b/SOLUTIONS/NUMBGAME.java new file mode 100644 index 00000000..0c5b829f --- /dev/null +++ b/SOLUTIONS/NUMBGAME.java @@ -0,0 +1,360 @@ +import java.util.*; +import java.io.*; +import java.math.BigInteger; + +class NUMBGAME +{ + + static int mod = (int) (1e9+7); + static InputReader in; + static PrintWriter out; + static int[] freq; + static int cnt; + static boolean[] vis; + static ArrayList[] g; + + static void dfs(int u) { + vis[u] = true; + cnt += freq[u]; + for(int v: g[u]) + if(!vis[v]) + dfs(v); + } + + static void solve() + { + in = new InputReader(System.in); + out = new PrintWriter(System.out); + + int t = in.nextInt(); + + while(t-- > 0){ + String A = in.readString(); + int n = A.length(); + int m = in.nextInt(); + + int[] pre = new int[n + 1]; + int[] suf = new int[n + 1]; + + for(int i = 0; i < n; i++) { + int x = (int)(A.charAt(i) - '0'); + pre[i + 1] = (pre[i] * 10 + x) % m; + } + + freq = new int[m]; + int[] pow = new int[n + 1]; + pow[0] = 1; + for(int i = 1; i <= n; i++) + pow[i] = (pow[i - 1] * 10) % m; + + for(int i = 0; i < n; i++) { + int x = ((pre[i] - pre[i + 1] + m)* pow[n - i - 1]) % m + pre[n]; + freq[x % m]++; + } + + g = new ArrayList[m]; + + for(int i = 0; i < m; i++) + g[i] = new ArrayList<>(); + + for(int i = 0; i < m; i++) { + for(int j = 0; j < m; j++) { + if(freq[j] == 0) continue; + g[(i * pow[n - 1] + j) % m].add(i); + } + } + + vis = new boolean[m]; + cnt = 0; + dfs(0); + + out.println(cnt); + } + + out.close(); + } + + static long add(long a, long b) { + return (a + b) % mod; + } + + static long mul(long a, long b) { + return (a * b) % mod; + } + + static long sub(long a, long b) { + return (a - b + mod) % mod; + } + + public static void main(String[] args) + { + new Thread(null ,new Runnable(){ + public void run() + { + try{ + solve(); + } catch(Exception e){ + e.printStackTrace(); + } + } + },"1",1<<26).start(); + } + + static class Pair implements Comparable + { + + int x,y; + int i; + + Pair (int x, int y) + { + this.x = x; + this.y = y; + } + + public int compareTo(Pair o) + { + return -Integer.compare(this.x, o.x); + } + + public boolean equals(Object o) + { + if (o instanceof Pair) + { + Pair p = (Pair)o; + return p.x == x && p.y==y; + } + return false; + } + + @Override + public String toString() + { + return x + " "+ y + " "+i; + } + + /*public int hashCode() + { + return new Long(x).hashCode() * 31 + new Long(y).hashCode(); + }*/ + + } + + + static String rev(String s){ + StringBuilder sb=new StringBuilder(s); + sb.reverse(); + return sb.toString(); + } + + static long gcd(long x,long y) + { + if(y==0) + return x; + else + return gcd(y,x%y); + } + + static int gcd(int x,int y) + { + if(y==0) + return x; + else + return gcd(y,x%y); + } + + static long pow(long n,long p,long m) + { + long result = 1; + if(p==0){ + return 1; + } + + while(p!=0) + { + if(p%2==1) + result *= n; + if(result >= m) + result %= m; + p >>=1; + n*=n; + if(n >= m) + n%=m; + } + + return result; + } + + static long pow(long n,long p) + { + long result = 1; + if(p==0) + return 1; + + while(p!=0) + { + if(p%2==1) + result *= n; + p >>=1; + n*=n; + } + return result; + } + + static void debug(Object... o) + { + System.out.println(Arrays.deepToString(o)); + } + + static class InputReader + { + + private final InputStream stream; + private final byte[] buf = new byte[8192]; + private int curChar, snumChars; + private SpaceCharFilter filter; + + public InputReader(InputStream stream) + { + this.stream = stream; + } + + public int snext() + { + if (snumChars == -1) + throw new InputMismatchException(); + if (curChar >= snumChars) + { + curChar = 0; + try + { + snumChars = stream.read(buf); + } catch (IOException e) + { + throw new InputMismatchException(); + } + if (snumChars <= 0) + return -1; + } + return buf[curChar++]; + } + + public int nextInt() + { + int c = snext(); + while (isSpaceChar(c)) + { + c = snext(); + } + int sgn = 1; + if (c == '-') + { + sgn = -1; + c = snext(); + } + int res = 0; + do + { + if (c < '0' || c > '9') + throw new InputMismatchException(); + res *= 10; + res += c - '0'; + c = snext(); + } while (!isSpaceChar(c)); + return res * sgn; + } + + public long nextLong() + { + int c = snext(); + while (isSpaceChar(c)) + { + c = snext(); + } + int sgn = 1; + if (c == '-') + { + sgn = -1; + c = snext(); + } + long res = 0; + do + { + if (c < '0' || c > '9') + throw new InputMismatchException(); + res *= 10; + res += c - '0'; + c = snext(); + } while (!isSpaceChar(c)); + return res * sgn; + } + + public int[] nextIntArray(int n) + { + int a[] = new int[n]; + for (int i = 0; i < n; i++) + { + a[i] = nextInt(); + } + return a; + } + + public long[] nextLongArray(int n) + { + long a[] = new long[n]; + for (int i = 0; i < n; i++) + { + a[i] = nextLong(); + } + return a; + } + + public String readString() + { + int c = snext(); + while (isSpaceChar(c)) + { + c = snext(); + } + StringBuilder res = new StringBuilder(); + do + { + res.appendCodePoint(c); + c = snext(); + } while (!isSpaceChar(c)); + return res.toString(); + } + + public String nextLine() + { + int c = snext(); + while (isSpaceChar(c)) + c = snext(); + StringBuilder res = new StringBuilder(); + do + { + res.appendCodePoint(c); + c = snext(); + } while (!isEndOfLine(c)); + return res.toString(); + } + + public boolean isSpaceChar(int c) + { + if (filter != null) + return filter.isSpaceChar(c); + return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; + } + + private boolean isEndOfLine(int c) + { + return c == '\n' || c == '\r' || c == -1; + } + + public interface SpaceCharFilter + { + public boolean isSpaceChar(int ch); + } + + } +} diff --git a/SOLUTIONS/NthPowerOfDigit.cpp b/SOLUTIONS/NthPowerOfDigit.cpp index 966417ef..10bd69eb 100644 --- a/SOLUTIONS/NthPowerOfDigit.cpp +++ b/SOLUTIONS/NthPowerOfDigit.cpp @@ -1,12 +1,23 @@ #include #include using namespace std; - +int fastexp(int a,int b) +{ + int ans=1; + while(b>0) + { + if(b&1) + ans=(ans*a); + b>>=1; + a=(a*a); + } + return ans; +} int sumNthPowerOfDigit(int N) { int finalSum = 0; // (N+1)*pow(9,N) is the upper limit of the brute-force search - for (int number = 2; number < (N+1)*pow(9,N); number++) { + for (int number = 2; number < (N+1)*fastexp(9,N); number++) { int sumOfPowers = 0; //go through each digit, calculate digit^N, and add to sumOfPowers @@ -14,7 +25,7 @@ int sumNthPowerOfDigit(int N) { while (tempNumber > 0) { int digit = tempNumber % 10; tempNumber /= 10; - sumOfPowers += pow(digit,N); + sumOfPowers += fastexp(digit,N); } if (sumOfPowers == number) { diff --git a/SOLUTIONS/OctalDecimal b/SOLUTIONS/OctalDecimal new file mode 100644 index 00000000..c8c22f14 --- /dev/null +++ b/SOLUTIONS/OctalDecimal @@ -0,0 +1,49 @@ +import java.util.*; // import scanner class +public class switchclass { + + public static void main(String args[]) + { + int ch,dec,num,rem,oct,decnum=0,orig,i=0; + char dig[]={'0','1','2','3','4','5','6','7'}; + String str=""; + Scanner obj=new Scanner(System.in); + System.out.println("Enter your choice :"); + // choice==1 for dec to oct + // choice==2 for oct to dec + ch=obj.nextInt(); + + if(ch==1) + { + System.out.println("Enter a decimal number :"); + num=obj.nextInt(); + while(num>0) + { + rem=num%8; + str=dig[rem]+str; + num=num/8; + } + System.out.println("Decimal to octal: "+str); + } + else if(ch==2) + { + System.out.println("Enter an octal number :"); + oct=obj.nextInt(); + orig = oct; + + while(oct != 0) + { + decnum = decnum + (oct%10) * (int) Math.pow(8, i); + i++; + oct = oct/10; + } + + System.out.print("Equivalent Decimal Value of " + orig + " is :\n"); + System.out.print(decnum); + } + else + { + System.out.print("Invalid Entry ....Please give a valid entry"); + } + } + } + diff --git a/SOLUTIONS/Palindrome.java b/SOLUTIONS/Palindrome.java new file mode 100644 index 00000000..7cbb8113 --- /dev/null +++ b/SOLUTIONS/Palindrome.java @@ -0,0 +1,33 @@ + import java.util.*; + +class Palindrome +{ + public static boolean isPalindrome(String original){ + String reverse =""; + int length = original.length(); + for (int i = length - 1; i >= 0; i--) + reverse = reverse + original.charAt(i); + + if (original.equals(reverse)) + // System.out.println("The string is a palindrome."); + return true; + else + // System.out.println("The string isn't a palindrome."); + return false; + } + + public static void main(String args[]) + { + String original; // Objects of String class + Scanner in = new Scanner(System.in); + + System.out.println("Enter a string to check if it is a palindrome"); + original = in.nextLine(); + + if (isPalindrome(original)) + System.out.printf("%s is a palindrome.",original); + else + System.out.printf("%s isn't a palindrome.",original); + + } +} diff --git a/SOLUTIONS/PalindromeNumber.java b/SOLUTIONS/PalindromeNumber.java new file mode 100644 index 00000000..49eade5e --- /dev/null +++ b/SOLUTIONS/PalindromeNumber.java @@ -0,0 +1,22 @@ +public class PalindromeNumber { + + public static void main(String[] args){ + System.out.println(isPalindrome(11)); + } + + public static boolean isPalindrome(int number) { + int reverse = 0; + while (number != 0) { + int lastDigit = number % 10; + reverse = (lastDigit * 10)+reverse; + number /= 10; + } + if (number == reverse) { + return true; + } else { + return false; + } + } + + +} \ No newline at end of file diff --git a/SOLUTIONS/Palindrome_check_for_word.py b/SOLUTIONS/Palindrome_check_for_word.py new file mode 100644 index 00000000..f837e8ae --- /dev/null +++ b/SOLUTIONS/Palindrome_check_for_word.py @@ -0,0 +1,20 @@ +def palindrome_check(): + word= input("Enter a word: ") + reverse="" + for i in word: + reverse= i + reverse + if reverse== word: + print (word,"is a palindrome") + return True,word,"is a palindrome" + + else: + print(word,"is not a palindrome") + return False,word,"is not a palindrome" + + +palindrome_check() + + + + + diff --git a/SOLUTIONS/Program.cs b/SOLUTIONS/Program.cs new file mode 100644 index 00000000..88491514 --- /dev/null +++ b/SOLUTIONS/Program.cs @@ -0,0 +1,48 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace BeginnersProblem2._0 +{ + class Program + { + static void Main(string[] args) + { + var numberofTestCases = int.Parse(Console.ReadLine()); + var resultsArray = new int[numberofTestCases]; + for(var i = 0; i < numberofTestCases; i++) + { + var numberofTestableValues = int.Parse(Console.ReadLine()); + var testableValues = new int[numberofTestableValues]; + + var testableValuesStringArray = Console.ReadLine().Split(' '); + + for(var j = 0; j< numberofTestableValues; j++) + { + testableValues[j] = int.Parse(testableValuesStringArray[j]); + } + resultsArray[i] = findFrequencyofBestValues(testableValues); + } + + foreach(var result in resultsArray) + { + Console.WriteLine(result); + } + } + + private static int findFrequencyofBestValues(int [] testableValues) + { + var frequency = 0; + foreach(var testValue in testableValues) + { + if(testValue % 2 == 0) + { + frequency++; + } + } + return frequency; + } + } +} diff --git a/SOLUTIONS/Question Paper.py b/SOLUTIONS/Question Paper.py new file mode 100644 index 00000000..dd7fee4a --- /dev/null +++ b/SOLUTIONS/Question Paper.py @@ -0,0 +1,11 @@ +T=int(input()) +for _ in range(T): + N,a,b=map(int,input().split()) + l=[0] + i=N + j=0 + while i!=0: + l.extend([i*a-m*(a+b) for m in range(i+1)]) + i-=1 + l=list(set(l)) + print(len(l)) \ No newline at end of file diff --git a/SOLUTIONS/REVERSE_WORDS_IN_PYTHON.py b/SOLUTIONS/REVERSE_WORDS_IN_PYTHON.py new file mode 100644 index 00000000..c9657350 --- /dev/null +++ b/SOLUTIONS/REVERSE_WORDS_IN_PYTHON.py @@ -0,0 +1,12 @@ +#[615] + +def main(): + u_Inp = input('Please enter a string: ') + words = u_Inp.split(' ') + revwrd = ''; + for w in reversed(words): + revwrd += w + ' ' + print(revwrd) + +if __name__ == '__main__': + main() \ No newline at end of file diff --git a/SOLUTIONS/Reduction-game.cpp b/SOLUTIONS/Reduction-game.cpp new file mode 100644 index 00000000..539a0427 --- /dev/null +++ b/SOLUTIONS/Reduction-game.cpp @@ -0,0 +1,36 @@ +#include +using namespace std; + +int main() +{ + int t,i,n,j,k; + long s; + scanf("%d",&t); + for(i=0;i= 0; i--) { + System.out.print(arrayOfString[i] + " "); + } + System.out.println(" "); + } + +} \ No newline at end of file diff --git a/SOLUTIONS/Rock, paper, scissors.. b/SOLUTIONS/Rock, paper, scissors.. new file mode 100644 index 00000000..a68895ba --- /dev/null +++ b/SOLUTIONS/Rock, paper, scissors.. @@ -0,0 +1,32 @@ +from random import randint + #create a list of play options +t = ["Rock", "Paper", "Scissors"] + #assign a random play to the computer +computer = t[randint(0,2)] + #set player to False +player = False + while player == False: +#set player to True + player = input("Rock, Paper, Scissors?") + if player == computer: + print("Tie!") + elif player == "Rock": + if computer == "Paper": + print("You lose!", computer, "covers", player) + else: + print("You win!", player, "smashes", computer) + elif player == "Paper": + if computer == "Scissors": + print("You lose!", computer, "cut", player) + else: + print("You win!", player, "covers", computer) + elif player == "Scissors": + if computer == "Rock": + print("You lose...", computer, "smashes", player) + else: + print("You win!", player, "cut", computer) + else: + print("That's not a valid play. Check your spelling!") + #player was set to True, but we want it to be False so the loop continues + player = False + computer = t[randint(0,2)] diff --git a/SOLUTIONS/Rock_paper_scissors2.py b/SOLUTIONS/Rock_paper_scissors2.py new file mode 100644 index 00000000..a2ce706c --- /dev/null +++ b/SOLUTIONS/Rock_paper_scissors2.py @@ -0,0 +1,15 @@ +def main(): + print("Welcome to RPS") + start_game = input("Would you like to play a new game? Y/N") + while start_game != "N": + player1 = input("What's your choose player 1(R - P - S): ") + player2 = input("What's your choose player 2(R - P - S): ") + if player1 == player2: + print("DRAW") + elif player1 == "R" and player2 == "S" or player1 == "S" and player2 == "P" or player1 == "P" and player2 == "R": + print("Congrat player 1, you won !!!") + else: + print("Congrat player 2, you won !!!") + start_game = input("Would you like to play a new game? Y/N") + +main() \ No newline at end of file diff --git a/SOLUTIONS/Roman_num_conversion.cpp b/SOLUTIONS/Roman_num_conversion.cpp new file mode 100644 index 00000000..5a4183f2 --- /dev/null +++ b/SOLUTIONS/Roman_num_conversion.cpp @@ -0,0 +1,42 @@ +#include +using namespace std; +int main(){ + int i; + cin>>i; + while(i--){ + cout<0){ + if(n<4*a[j]){ + if(n==9){ + cout<<"IX"; + break;} + else if(n>=90&&n<100){ + cout<<"XC"; + n=n%90; + } + else if(n>=900&&n<1000){ + cout<<"CM"; + n=n%900; + } + int c=n/a[j]; + while(c--){ + cout<=4*a[j]){ + cout< + + + Score Keeper + + + +

0 vs 0

+

Playing to: 0

+ + +
+ + +
+ +
+ + +
+ +
+ + +
+ + + + diff --git a/SOLUTIONS/ScoreKeeper.js b/SOLUTIONS/ScoreKeeper.js new file mode 100644 index 00000000..8155d6dd --- /dev/null +++ b/SOLUTIONS/ScoreKeeper.js @@ -0,0 +1,71 @@ +// header +var h1 = document.getElementById("plone"); +var h2 = document.getElementById("pltwo"); +var h3 = document.getElementById("playto"); + +// buttons +var b1 = document.getElementById("pluno"); +var b2 = document.getElementById("pluto"); +var reset = document.getElementById("reset"); + +// limit +var inputRange = document.getElementById("limit"); +// var winningLimit = parseInt(inputRange.value); + +var clickedOne = 0; +var clickedTwo = 0; +var isOver = false; +var winningLimit = 0; +// var limit = winningLimit; + +b1.addEventListener("click",function() + { + if(!isOver) + { + clickedOne++; + if(clickedOne === winningLimit) + { + isOver = true; + h1.classList.add("changeClr"); + } + h1.textContent = clickedOne; + } + }); + +b2.addEventListener("click",function() + { + if(!isOver) + { + clickedTwo++; + if(clickedTwo === winningLimit) + { + isOver = true; + h2.classList.add("changeClr"); + } + h2.textContent = clickedTwo; + } + }); + +reset.addEventListener("click",function() + { + resettt(); + }); + +function resettt() +{ + clickedOne = 0; + clickedTwo = 0; + isOver = false; + // inputRange = 0; + h1.textContent = 0; + h2.textContent = 0; + h1.classList.remove("changeClr"); + h2.classList.remove("changeClr"); +} + +inputRange.addEventListener("change", function() + { + h3.textContent = inputRange.value; + winningLimit = Number(inputRange.value); + resettt(); + }); diff --git a/SOLUTIONS/Search for Pretty Integers.py b/SOLUTIONS/Search for Pretty Integers.py new file mode 100644 index 00000000..2bc43961 --- /dev/null +++ b/SOLUTIONS/Search for Pretty Integers.py @@ -0,0 +1,21 @@ +aa, bb = map(int,raw_input().split()) + +a = map(int,raw_input().split()) +b = map(int,raw_input().split()) + +ma = min(a) + +mu = 1000000 +mb = min(b) + +for i in b: + if i in a and i +using namespace std; +template + +void sel_sort(t arr[],int n ) +{ t temp; + + for(int j=0;j>n; + +string arr[n]; +for(int i=0;i>arr[i]; +sel_sort(arr, n); +cout<<"The sorted array is "; +for( int s=0;s +int STACK[100],x,n,choice,top,i; +void push(void); +void pop(void); +void display(void); +int main() +{ + top=-1; + printf("Enter the size of Stack[MaX_100]\n"); + scanf("%d",&n); + printf("Which operarion do you want to perform \n"); + printf("--------------------------------------\n"); + printf("\n1. PUSH\n 2.POP\n3. DISPLAY\n4.EXIT\n"); + do + { + printf("Enter your choice\n"); + scanf("%d",&choice); + switch(choice) + { + case 1: + { + push(); + break; + } + case 2: + { + pop(); + break; + } + case 3: + { + display(); + break; + } + case 4: + { + printf("\n \tExit Point"); + break; + } + default: + { + printf("Enter valid choice(1/2/3/4)\n"); + } + } + } + while(choice!=4); + return 0; +} +void push() +{ + if(top>=n-1) + { + printf("Overflow occurs\n"); + } + else + { + printf("Enter a value to be pushed\n"); + scanf("%d",&x); + top++; + STACK[top]=x; + } +} +void pop() +{ + if(top<=-1) + { + printf("UnderFlow occurs\n"); + } + else + { + printf("The popped element is %d\n",STACK[top]); + top--; + } +} +void display() +{ + if (top>=0) + { + printf("The element in the stack are: \n"); + for(i=top;i>=0;i--) + { + printf("%d\n",STACK[i]); + //printf("Enter next choice \n"); + } + } + else + { + printf("Your stack is empty \n"); + } +} + + + + + + + + + + diff --git a/SOLUTIONS/StrategyPattern.java b/SOLUTIONS/StrategyPattern.java new file mode 100644 index 00000000..56cb2683 --- /dev/null +++ b/SOLUTIONS/StrategyPattern.java @@ -0,0 +1,85 @@ + +import java.util.ArrayList; +import java.util.List; + +public class StrategyPattern { + + public static void main(final String[] arguments) { + Customer firstCustomer = new Customer(new NormalStrategy()); + + // Normal billing + firstCustomer.add(1.0, 1); + + // Start Happy Hour + firstCustomer.setStrategy(new HappyHourStrategy()); + firstCustomer.add(1.0, 2); + + // New Customer + Customer secondCustomer = new Customer(new HappyHourStrategy()); + secondCustomer.add(0.8, 1); + // The Customer pays + firstCustomer.printBill(); + + // End Happy Hour + secondCustomer.setStrategy(new NormalStrategy()); + secondCustomer.add(1.3, 2); + secondCustomer.add(2.5, 1); + secondCustomer.printBill(); + } +} + + +class Customer { + + private List drinks; + private BillingStrategy strategy; + + public Customer(final BillingStrategy strategy) { + this.drinks = new ArrayList(); + this.strategy = strategy; + } + + public void add(final double price, final int quantity) { + drinks.add(strategy.getActPrice(price*quantity)); + } + + // Payment of bill + public void printBill() { + double sum = 0; + for (Double i : drinks) { + sum += i; + } + System.out.println("Total due: " + sum); + drinks.clear(); + } + + // Set Strategy + public void setStrategy(final BillingStrategy strategy) { + this.strategy = strategy; + } + +} + +interface BillingStrategy { + double getActPrice(final double rawPrice); +} + +// Normal billing strategy (unchanged price) +class NormalStrategy implements BillingStrategy { + + @Override + public double getActPrice(final double rawPrice) { + return rawPrice; + } + +} + +// Strategy for Happy hour (50% discount) +class HappyHourStrategy implements BillingStrategy { + + @Override + public double getActPrice(final double rawPrice) { + return rawPrice*0.5; + } + +} \ No newline at end of file diff --git a/SOLUTIONS/SubSetSumDynamicProgramming b/SOLUTIONS/SubSetSumDynamicProgramming new file mode 100644 index 00000000..e11aeb8b --- /dev/null +++ b/SOLUTIONS/SubSetSumDynamicProgramming @@ -0,0 +1,60 @@ +/* **** Complexity = O(subsetSum*n) where subsetSum is sum of the subset to be searched for *** */ + +#include +#include +using namespace std; +int main() +{ + vector Arr; + int n,temp,subsetSum; + cout<<"\nEnter number of the elements in the set : "; + cin>>n; + cout<<"\nEnter elements of the set : \n"; + for(int i=0;i>temp; + if(temp<0) + { + cout<<"\nEnter Non Negative Integers Only!!"; + i--; + } + else + { + Arr.push_back(temp); + } + } + cout<<"\nEnter sum of subset to be searched for : "; + cin>>subsetSum; + bool subsetTable[n+1][subsetSum+1]; + for (int i = 0; i <= n; i++) + { + subsetTable[i][0] = true; + } + for (int i = 1; i <= subsetSum; i++) + { + subsetTable[0][i] = false; + } + for(int i=1;i<=n;i++) + { + for(int j=1;j<=subsetSum;j++) + { + if(j=Arr[i-1]) + { + subsetTable[i][j] = (subsetTable[i-1][j]) || (subsetTable[i - 1][j-Arr[i-1]]); + } + } + } + if(subsetTable[n][subsetSum]) + { + cout<<"\nYes, there exists a subset whose sum is "< throw new RuntimeException("Error occurred while reading number of test cases: please enter a valid value") + } + } + + def readCases(t: Int, list: List[Int] = List.empty[Int]): List[Int] = { + if (t == list.length) { + return list + } + + val inp = scala.io.StdIn.readLine() + try { + val value2insert = inp.trim.toInt + if (value2insert < 0 && value2insert > 1000) { + throw new RuntimeException("0≤ N ≤ 1000") + } + + readCases(t, list :+ value2insert) + } catch { + case _: Exception => throw new RuntimeException("Error occurred while reading cases: please enter a valid value and/or number that is greater than 0") + } + } + + def factorial(n: Int): Int = { + if (-1 < n && n <= 1) 1 + else n * factorial(n - 1) + } + + def calculateDigitsSum(n: Int): Int = { + val digits: String = n.toString + digits.split("").map(_.toInt).sum + } + + def sumFactorialDigits: List[Int] = { + val t = readT() + + val numbers: List[Int] = if (t < 1 && t > 100) { + throw new RuntimeException("1≤ T ≤ 100") + } else { + readCases(t) + } + + numbers.map(factorial).map(calculateDigitsSum) + } + + sumFactorialDigits.foreach(println) +} diff --git a/SOLUTIONS/UnusualGame.ipynb b/SOLUTIONS/UnusualGame.ipynb new file mode 100644 index 00000000..e5e7d482 --- /dev/null +++ b/SOLUTIONS/UnusualGame.ipynb @@ -0,0 +1,33 @@ +import numpy as np +T=int(input("No.of Test Cases")) +for i in range (1,T+1): + s=input("n and m") + n,m=s.split() + n=int(n) + m=int(m) + k=input("m space seperated integers") + l=np.zeros(m) + for j in range (1, m+1): + p=j + count=1 + win=0 + + x=1 + while (count==1): + a=p+x + if (a<=n): + p=a + x=x+1 + else: + a=p-x + if (a>=1): + p=a + x=x+1 + else: + count=0 + if (x%2==0): + win=1 + else: + win=2 + l[j-1]=win +print(l) diff --git a/SOLUTIONS/VideoPosts.java b/SOLUTIONS/VideoPosts.java new file mode 100644 index 00000000..34bb6b79 --- /dev/null +++ b/SOLUTIONS/VideoPosts.java @@ -0,0 +1,66 @@ +import java.util.*; +import java.io.*; +import java.lang.StringBuilder; + +public class VideoPosts +{ + public static void main(String[] args) + { + Scanner in = new Scanner(new BufferedReader(new InputStreamReader(System.in))); + + int numVideos = in.nextInt(); + int numPosts = in.nextInt(); + + int totalSeconds = 0; + List list = new ArrayList<>(); + + for(int i = 0; i < numVideos; i++) + { + int videoLength = in.nextInt(); + totalSeconds += videoLength; + list.add(videoLength); + } + + if(totalSeconds % numPosts != 0) + { + System.out.println("No"); + } + else + { + boolean solutionExists = true; + int i = 0; + StringBuilder builder = new StringBuilder(); + int durationPerPost = totalSeconds / numPosts; + int numVideoPerPost = 0; + while(solutionExists && i < list.size()) + { + durationPerPost -= list.get(i); + numVideoPerPost++; + + if(durationPerPost == 0) + { + builder.append(numVideoPerPost).append(" "); + durationPerPost = totalSeconds / numPosts; + numVideoPerPost = 0; + } + + if(durationPerPost < 0) + { + solutionExists = false; + } + i++; + } + + if(solutionExists) + { + builder.insert(0, "Yes "); + String output = builder.toString(); + System.out.println(output.substring(0, output.length()-1)); + } + else + { + System.out.println("No"); + } + } + } +} diff --git a/SOLUTIONS/XORAGN.cpp b/SOLUTIONS/XORAGN.cpp new file mode 100644 index 00000000..101dd3d6 --- /dev/null +++ b/SOLUTIONS/XORAGN.cpp @@ -0,0 +1,26 @@ + +// Solution to XORAGN question of codechef +#include +#include +#include +using namespace std; +int main(){ +long long int test, n; +long int temp,k=0; +cin>>test; +vector ans(test); +for (int i=0;i>n; + vector arr(n); + temp=0; + for(int j=0;j>arr[j]; + temp=temp^arr[j]; + } + ans[k]=(temp<<1); + k++; +} +for(int i=0;i; +$t = $n; +$sum=0; + +while($n!=0) +{ +$rem = $n %10; +$sum = $sum + $rem*$rem*$rem; +$n=$n/10; +} + +if($t==$sum) +{ +print "yes"; +} +else +{ +print "no"; +} diff --git a/SOLUTIONS/ankit b/SOLUTIONS/ankit new file mode 100644 index 00000000..1c0528c2 --- /dev/null +++ b/SOLUTIONS/ankit @@ -0,0 +1,4 @@ +include +{ +cout<"hello"; +} diff --git a/SOLUTIONS/ascii1product.py b/SOLUTIONS/ascii1product.py new file mode 100644 index 00000000..d3eb406a --- /dev/null +++ b/SOLUTIONS/ascii1product.py @@ -0,0 +1,11 @@ +def productAscii(str): + prod = 1 + for i in range(0, len(str)): + prod = prod * ord(str[i]) + + return prod + +if __name__=='__main__': + + str = "Sweta" + print(productAscii(str)) diff --git a/SOLUTIONS/asciiProd.class b/SOLUTIONS/asciiProd.class new file mode 100644 index 00000000..d1b8a9c5 Binary files /dev/null and b/SOLUTIONS/asciiProd.class differ diff --git a/SOLUTIONS/asciiProd.java b/SOLUTIONS/asciiProd.java new file mode 100644 index 00000000..5e9abeaa --- /dev/null +++ b/SOLUTIONS/asciiProd.java @@ -0,0 +1,22 @@ +import java.util.Scanner; +public class asciiProd { + +public static long productAscii(String str) { + long prod = 1; + + for (int i = 0; i < str.length(); i++) { + prod *= str.charAt(i); + } + + + return prod; +} + + +public static void main(String[] args) { + // String str = "BiD"; + Scanner scanner = new Scanner(System.in); + String str = scanner.nextLine(); + System.out.println(productAscii(str)); +} +} \ No newline at end of file diff --git a/SOLUTIONS/asciipro.py b/SOLUTIONS/asciipro.py new file mode 100644 index 00000000..4b81c80d --- /dev/null +++ b/SOLUTIONS/asciipro.py @@ -0,0 +1,6 @@ +#code written by rk301999 +n=input() +pro=1 +for i in n: + pro*=ord(i) +print("given ascii of %s is = %d"%(n,pro)) diff --git a/SOLUTIONS/atm_machine.py b/SOLUTIONS/atm_machine.py new file mode 100644 index 00000000..2e875ed8 --- /dev/null +++ b/SOLUTIONS/atm_machine.py @@ -0,0 +1,14 @@ +n=int(input()) +for i in range(0,n): + k,n=map(int,input().split()) + l=list(map(int,input().split())) + l1=[] + for j in l: + p=n-j + if(p>=0): + l1.append("1") + n=p + else: + l1.append("0") + print("".join(l1)) + diff --git a/SOLUTIONS/atmprob.c b/SOLUTIONS/atmprob.c new file mode 100644 index 00000000..45806ef1 --- /dev/null +++ b/SOLUTIONS/atmprob.c @@ -0,0 +1,25 @@ +#include +int main(void) +{ + int i,j,n,t,k,a[100]; + scanf("%d",&t); + for(i=0;i +#include + +int main(int argc, char const *argv[]) { + int number_of_cases = 0, number_of_elements = 0, values = 0; + + scanf("%i", &number_of_cases); + + int vet_result_cases[number_of_cases]; + + for (int i = 0; i < number_of_cases; ++i) { + vet_result_cases[i] = 0; + } + + for (int i = 0; i < number_of_cases; ++i) { + scanf("%i", &number_of_elements); + for (int j = 0; j < number_of_elements; ++j) { + scanf("%i", &values); + if (values % 2 == 0) { + vet_result_cases[i] += 1; + } + } + } + + for (int i = 0; i < number_of_cases; ++i) { + printf("%i\n", vet_result_cases[i]); + } + + return 0; +} \ No newline at end of file diff --git a/SOLUTIONS/beginer2.0.cpp b/SOLUTIONS/beginer2.0.cpp new file mode 100644 index 00000000..824d4321 --- /dev/null +++ b/SOLUTIONS/beginer2.0.cpp @@ -0,0 +1,21 @@ +#include +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]; + for(int i=0;i +int even(int n1); +int main(){ + int n; + scanf("%d",&n); + for(int i=0;i +using namespace std; + + + +int main() { + int t; + cin>>t; + while(t--) { + int n; + cin>>n; + int cnt = 0; + for(int i = 0; i>a;b + if(!(a & 1) ) cnt++; + } + + cout< +using namespace std; +vector v[20010]; +int dis[10010]; +int i,j,k,n,m,q; +int main() { + ios_base::sync_with_stdio(false); + cin.tie(NULL); + cin>>q>>n; + for(i=0;i>j>>k>>m; + v[i].push_back(j); + v[i].push_back(k); + v[i].push_back(m); + } + dis[0]=0; + for(i=0;i=0): + l1.append("1") + n=p + else: + l1.append("0") + print("".join(l1)) + diff --git a/SOLUTIONS/binary_multiple_of_3 b/SOLUTIONS/binary_multiple_of_3 new file mode 100644 index 00000000..c62bf258 --- /dev/null +++ b/SOLUTIONS/binary_multiple_of_3 @@ -0,0 +1,19 @@ +//c program for binary multiple of 3 +#include +#include +#include +void main() +{ + char A[100]; + int i=0,sum=0; + i=0; + while(A[i]!='/0') + {scanf("%s",A[i]) + i++; + } + int sum =0; + while(i>=0) + { sum += atoi(A[i]) + pow(2,i); + i--; + } + } diff --git a/SOLUTIONS/binary_multiple_of_3.js b/SOLUTIONS/binary_multiple_of_3.js new file mode 100644 index 00000000..d084c143 --- /dev/null +++ b/SOLUTIONS/binary_multiple_of_3.js @@ -0,0 +1,53 @@ +// run it with node.js +'use strict'; +let readline = require('readline'); + +// solution to the problem +function isBinaryDivisibleBy3 (bNumber) { + let value = parseInt(bNumber,2) + return value % 3 === 0 && value >=3 ? 1 : 0 +} + +// from here is input hanling / validation +const ri = readline.createInterface({ + input: process.stdin, + output: process.stdout +}); + + +const params = { + T: null, + inputs: [] +} + +function processInput (line) { + let question = 'How many test [1-100] (CTRL+C to exit)?' + if (typeof params.T !== 'number') { + const n = parseInt(line,10); + if (n !== NaN && n >= 1 && n <= 100) { + params.T = n; + question = "Enter Binary Number #" + (params.inputs.length + 1); + } + } else { + + // binary input + let isBinary = line.match('^[01]{1,100}$'); + if (isBinary) { + console.log( line, ' => ', isBinaryDivisibleBy3(line)) + params.inputs.push(line); + } + question = "Enter Binary Number #" + (params.inputs.length + 1); + } + return question; +} + +ri.on('line', function (line) { + let question = processInput(line); + if (typeof params.T === 'number' && params.T === params.inputs.length) { + process.exit() + } + console.log(question); + ri.prompt(); +}) +ri.write('\n') +ri.prompt() diff --git a/SOLUTIONS/birthday prob.cpp b/SOLUTIONS/birthday prob.cpp new file mode 100644 index 00000000..f0c64e12 --- /dev/null +++ b/SOLUTIONS/birthday prob.cpp @@ -0,0 +1,49 @@ +#include +using namespace std; +int main() +{ +int t,n; +char c[100000]; +cin>>t; + +for(int i=0;i>n; + + for(int i=0;i>c[i]; + cout< +using namespace std; +#define FOR(i,n) for (int i = 0; i < (int)(n); ++i) +#define mod 1000000007 +#define bigger(a,b) (a>b?a:b) +#define smaller(a,b) (a::max(); +bool visited[1005]; +vectorgraph[1005]; +void init() +{ + for(int i=0;i<1005;i++) + { + visited[i] = false; + } +} +int query,cnt = 0; +void dfs(int check, int depth) +{ + visited[check] = true; + for(int i=0;i&x, const pair&y) +{ + if(x.first!=y.first) + { + return x.first>n; +int u,v; +for(int i=0;i>u>>v; + graph[u].push_back(v); + graph[v].push_back(u); +} +int q; + +cin>>q; +vector>answer; +for(int i=0;i>query; + init(); + dfs(1,0); +// cout< x[j+1] + swap!(x, j, j+1) + end + end + end + + return x +end + +x = [10,2,5,1,3,0] + +println(bubblesort!(x)) \ No newline at end of file diff --git a/SOLUTIONS/chetan gaur b/SOLUTIONS/chetan gaur new file mode 100644 index 00000000..8ed63e97 --- /dev/null +++ b/SOLUTIONS/chetan gaur @@ -0,0 +1,7 @@ +#include +#include +void main() +{ clrscr(); + printf("hello world"); + getch(); + } diff --git a/SOLUTIONS/circular_primes.rb b/SOLUTIONS/circular_primes.rb new file mode 100644 index 00000000..a059e327 --- /dev/null +++ b/SOLUTIONS/circular_primes.rb @@ -0,0 +1,66 @@ +# The number,197 , is called a circular prime because +# all rotations of the digits: 197,971 and 719 are themselves prime. +# There are thirteen such primes below 100: 2,3,5,7,11,13,17,31,37,71,73,79 and 97. +# Sum of which is 446. +# Find the sum of circular primes that are below N? +# Rotations can exceed N +# #### Input Format +# Input contains an integer N. +# #### Output Format +# Print the required answer. +# #### CONSTRAINTS +# 10≤ N ≤ 10^6 +# #### Sample Input +# ``` +# 100 +# ``` +# #### Sample Output +# ``` +# 446 +# ``` + +require 'prime' + +def find_circular_primes + puts 'Enter an integer number between 10 and 1000000' + input_string = gets + number = input_string.chomp.to_i + if number < 10 || number > 10**6 + puts 'The number exceeds the range. Exiting!' + else + list_circular_primes(number) + end +end + +def list_circular_primes(max_number) + circular_primes = [] + (1...max_number).each do |number| + next unless prime?(number) + circular_primes << number if circular_prime?(number) + end + puts "Circular primes below #{max_number}" + puts circular_primes.join(', ') + puts "Count: #{circular_primes.count}" + puts "Sum: #{circular_primes.sum}" +end + +def prime?(number) + Prime.prime?(number) +end + +def circular_prime?(number) + circular_numbers = unique_circular_numbers(number) + circular_numbers.all? { |num| prime?(num) } +end + +def unique_circular_numbers(number) + splitted_numbers = number.digits + splitted_numbers + .permutation(splitted_numbers.size) + .uniq + .map(&:join) + .map(&:to_i) +end + +# running the program +find_circular_primes diff --git a/SOLUTIONS/circularprimes.py b/SOLUTIONS/circularprimes.py new file mode 100644 index 00000000..cc0c947d --- /dev/null +++ b/SOLUTIONS/circularprimes.py @@ -0,0 +1,45 @@ +user_input = int(input()) + + +def calculate_n(x): # I still think its the faster to compute sieve for a one digit higher then to do it other way + return int("1"+("0"* len(str(x)))) + + +n = calculate_n(user_input) + + +def sieve_for_primes_to(n): + size = n//2 + sieve = [1]*size + limit = int(n**0.5) + for i in range(1,limit): + if sieve[i]: + val = 2*i+1 + tmp = ((size-1) - i)//val + sieve[i+val::val] = [0]*tmp + return sieve + + +arr = ([2] + [i*2+1 for i, v in enumerate(sieve_for_primes_to(n+1)) if v and i>0]) +# This array is now a sieve of primes up to the len(user_input) + one more digit case 400 its 1000 + +ansarr = [] +for v in arr: + if v > user_input: # We are looping up to the user_input limit higher values in arr allow us to check whether + # they are prime num by just checking the array instead of expensive computation + break + if v <= 11: + ansarr.append(v) + else: + try: + reversed = int(str(v)[::-1]) # we calculate reversed number by doing string slice + if arr.index(reversed) and ansarr.count(v) == 0: # we check for the reversed num being part of prime nums + ansarr.append(v) # then we append v + if ansarr.count(reversed) == 0: # if reversed is not already appended we append + ansarr.append(reversed) + except (ValueError, IndexError): # in case of reversed not being a prime num we get + # ValueError from search operation so we just catch + # and continue + continue +# print(ansarr) # Added for debugging manually if needed +print(sum(ansarr)) # we just sum appended nums and print the sum \ No newline at end of file diff --git a/SOLUTIONS/convert.py b/SOLUTIONS/convert.py new file mode 100644 index 00000000..81573160 --- /dev/null +++ b/SOLUTIONS/convert.py @@ -0,0 +1,8 @@ +n = input() +sec, rest = n[:-2].split(":") , n[-2:] +if rest == "PM" and sec[0] != "12": + sec[0] = str(int(sec[0]) + 12) +elif rest == "AM" and sec[0] == "12": + sec[0] = str(int(sec[0]) - 12) + +print(":".join(sec)) diff --git a/SOLUTIONS/decimal_octal_conversion.rb b/SOLUTIONS/decimal_octal_conversion.rb new file mode 100644 index 00000000..4991b369 --- /dev/null +++ b/SOLUTIONS/decimal_octal_conversion.rb @@ -0,0 +1,31 @@ +# octal to decimal and decimal to octal conversion + +def octal_decimal(int) + num = int.to_i.digits + if (num & [8, 9]).present? + puts "Can't be a octal number please check" + return + end + decimal_number = 0 + num.each_with_index do |val, index| + decimal_number += (val * (8 ** index)) + end + puts "Octal #{int} is Decimal #{decimal_number}" +end + +def decimal_octal(int) + quotient = int.to_i + octal_num = '' + while quotient != 0 + remainder = quotient % 8 + quotient /= 8 + octal_num = remainder.to_s + octal_num + end + puts "Decimal #{int} is Octal #{octal_num}" +end + +# To convert decimal to octal +decimal_octal 1792 + +# To convert octal to decimal +octal_decimal 3400 diff --git a/SOLUTIONS/decimaltobainary.md b/SOLUTIONS/decimaltobainary.md new file mode 100644 index 00000000..d8171b33 --- /dev/null +++ b/SOLUTIONS/decimaltobainary.md @@ -0,0 +1,6 @@ +How to convert decimal to binary +Conversion steps: +Divide the number by 2. +Get the integer quotient for the next iteration. +Get the remainder for the binary digit. +Repeat the steps until the quotient is equal to 0. diff --git a/SOLUTIONS/fib.pl b/SOLUTIONS/fib.pl new file mode 100644 index 00000000..a29cc9bd --- /dev/null +++ b/SOLUTIONS/fib.pl @@ -0,0 +1,18 @@ +print "enter a no:"; +$num = ; +$i = 0; + +$c = 0; +$a = 0; +$b = 1; + +while($i < $num) +{ + +print $a." "; +$c = $a+$b; +$a = $b; +$b = $c; +$i++; + +} \ No newline at end of file diff --git a/SOLUTIONS/fibonacci.cpp b/SOLUTIONS/fibonacci.cpp new file mode 100644 index 00000000..16339dc6 --- /dev/null +++ b/SOLUTIONS/fibonacci.cpp @@ -0,0 +1,18 @@ +#include +void main() +{ + int a=0,b=1,n,d=0; + cout<<"how many terms of fibonacci series to display"; + cin>>n; + for(int i=1;i<=n;i++) + { + if(i==1) + cout< +#include +void main() +{ +char a[200]; +gets(a); +printf("Hello world"); +} diff --git a/SOLUTIONS/halfPyramid.c b/SOLUTIONS/halfPyramid.c new file mode 100644 index 00000000..7d2fa6e0 --- /dev/null +++ b/SOLUTIONS/halfPyramid.c @@ -0,0 +1,19 @@ +#include +int main() +{ + int rows, i, j; + + printf("Enter number of rows: "); + scanf("%d",&rows); + + for(i=1; i <= rows; i++) + { + for(j=1; j <= i; ++j) + { + printf("*"); + } + + printf("\n"); + } + return 0; +} \ No newline at end of file diff --git a/SOLUTIONS/hc.c b/SOLUTIONS/hc.c new file mode 100644 index 00000000..830d0386 --- /dev/null +++ b/SOLUTIONS/hc.c @@ -0,0 +1,54 @@ + +// CPP program to reverse a string +#include + +/* function prototype for utility function to + reverse a string from begin to end */ +void reverse(char* begin, char* end); + +/*Function to reverse words*/ +void reverseWords(char* s) +{ + char* word_begin = s; + char* temp = s; /* temp is for word boundry */ + + /*STEP 1 of the above algorithm */ + while (*temp) { + temp++; + if (*temp == '\0') { + reverse(word_begin, temp - 1); + } + else if (*temp == ' ') { + reverse(word_begin, temp - 1); + word_begin = temp + 1; + } + } /* End of while */ + + /*STEP 2 of the above algorithm */ + reverse(s, temp - 1); +} + +/* UTILITY FUNCTIONS */ +/*Function to reverse any sequence starting with pointer + begin and ending with pointer end */ +void reverse(char* begin, char* end) +{ + char temp; + while (begin < end) { + temp = *begin; + *begin++ = *end; + *end-- = temp; + } +} + +/* Driver function to test above functions */ +int main() +{ + char s[100]; + gets(s); + char* temp = s; + reverseWords(s); + printf("%s", s); + getchar(); + return 0; +} diff --git a/SOLUTIONS/hello world.cpp b/SOLUTIONS/hello world.cpp new file mode 100644 index 00000000..c1c7ac5e --- /dev/null +++ b/SOLUTIONS/hello world.cpp @@ -0,0 +1,5 @@ +#include +void main() +{ +cout<<"Hello world"; +} \ No newline at end of file diff --git a/SOLUTIONS/hello-world b/SOLUTIONS/hello-world new file mode 100644 index 00000000..547f402e --- /dev/null +++ b/SOLUTIONS/hello-world @@ -0,0 +1,51 @@ +def altera(nome, nota_antiga, nota_nova): + medias = open("Medias.txt", "r") + medias2 = open("medias2.txt", "w") + for texto in medias: + nome_no_arquivo = "" + for char in texto: + if char.isalpha(): + nome_no_arquivo += char + if nome_no_arquivo == nome: + medias2.write(substitui(texto, str(nota_antiga), str(nota_nova)) + "\n") + else: + medias2.write(texto) + + + +def substitui(f, a, n): + posicao = len(f) + f2 = "" + for i in range(-len(a), -len(f)-1, -1): + p = "" + aux = i + for j in range(aux, aux+len(a), 1): + p += f[j] + aux -= 1 + if p == a: + posicao += i + break + cont = 0 + while cont < len(f): + if cont == posicao: + for i in range(0, len(n), 1): + f2 += n[i] + cont += len(a)-1 + else: + f2 += f[cont] + cont += 1 + if f == f2: + return f + else: + return f2 + + +def imprimir(): + medias = open("Medias.txt", "r") + for texto in medias: + print(texto) + +n = input("Informe o nome do aluno: ") +nota_a = input("Informe a nota antiga: ") +nota_n = input("Informe a nota nova: ") +altera(n, nota_a, nota_n) diff --git a/SOLUTIONS/hello-world-2.py b/SOLUTIONS/hello-world-2.py new file mode 100644 index 00000000..44159b39 --- /dev/null +++ b/SOLUTIONS/hello-world-2.py @@ -0,0 +1 @@ +print("Hello world") diff --git a/SOLUTIONS/hello-world.java b/SOLUTIONS/hello-world.java index 6b13581e..790a989a 100644 --- a/SOLUTIONS/hello-world.java +++ b/SOLUTIONS/hello-world.java @@ -1,3 +1,10 @@ +import java.util.Scanner; public class helloWorld { + public static void main(String args[]){ + Scanner in =new Scanner(System.in); + System.out.println("Enter to display the same!"); + String sentence=in.next(); + System.out.println(sentence); + } -} \ No newline at end of file +} diff --git a/SOLUTIONS/hello.c b/SOLUTIONS/hello.c new file mode 100644 index 00000000..f381f047 --- /dev/null +++ b/SOLUTIONS/hello.c @@ -0,0 +1,5 @@ +#include +void main() +{ +printf("hello world!"); +} diff --git a/SOLUTIONS/hello.js b/SOLUTIONS/hello.js index b179ee95..f6160902 100644 --- a/SOLUTIONS/hello.js +++ b/SOLUTIONS/hello.js @@ -1 +1,6 @@ -console.log("Hello world"); +var x = function HelloWorld(Name) { + var hellow = "Hello World "; + // Name ? hellow+=` ${Name}`:"" + console.log(hellow); +}; +console.log(x()); diff --git a/SOLUTIONS/hello_world.c b/SOLUTIONS/hello_world.c new file mode 100644 index 00000000..476c6b61 --- /dev/null +++ b/SOLUTIONS/hello_world.c @@ -0,0 +1,22 @@ +#include + +void ft_putchar(char c) +{ + write(1, &c, 1); +} + +void ft_putstr(char *str) +{ + int count = 0; + while (str[count]) + { + ft_putchar(str[count]); + count++; + } +} + +int main(void) +{ + ft_putstr("Hello World!\n"); + return 0; +} diff --git a/SOLUTIONS/hello_world.class b/SOLUTIONS/hello_world.class new file mode 100644 index 00000000..8a67ab5f Binary files /dev/null and b/SOLUTIONS/hello_world.class differ diff --git a/SOLUTIONS/hello_world1.c b/SOLUTIONS/hello_world1.c new file mode 100644 index 00000000..626162b2 --- /dev/null +++ b/SOLUTIONS/hello_world1.c @@ -0,0 +1,8 @@ +#include + +int main() +{ + printf("hello world"); + + return 0; +} diff --git a/SOLUTIONS/helloworld.cpp b/SOLUTIONS/helloworld.cpp new file mode 100644 index 00000000..afa1e5da --- /dev/null +++ b/SOLUTIONS/helloworld.cpp @@ -0,0 +1,7 @@ +#include + +int main() +{ +cout<<"Hello World"<int(num2)) & (count[num1]>count[num2]): + return 1 + elif (int(num2)>int(num1)) & (count[num2]>count[num1]): + return 1 + elif int(num1)==int(num2): + return 1 + else: + return 0 + +N = int(input("")) +arr = list(input("").split()) +allSubSeq = [arr[i:i+j] for i in range(0,N) for j in range(1,N - i+1)] +sortedSubSeq = sorted(allSubSeq,key=len,reverse=True) +for subSeq in sortedSubSeq: + count = Counter(subSeq) + flags = [compareFreq(subSeq[i],subSeq[j],count) for i in range(0,len(subSeq)) for j in range(i+1,len(subSeq))] + if len(subSeq)<=1: + print(len(subSeq)) + break + elif sum(flags)/len(flags)==1: + print(len(subSeq)) + break diff --git a/SOLUTIONS/hh b/SOLUTIONS/hh new file mode 100644 index 00000000..5015e319 --- /dev/null +++ b/SOLUTIONS/hh @@ -0,0 +1,5 @@ +#include +void main() +{ +printf("virat 107"); +} diff --git a/SOLUTIONS/invertedPyramid.c b/SOLUTIONS/invertedPyramid.c new file mode 100644 index 00000000..16035fb9 --- /dev/null +++ b/SOLUTIONS/invertedPyramid.c @@ -0,0 +1,24 @@ +#include +int main() +{ + int rows, i, j, k; + + printf("Enter number of rows: "); + scanf("%d",&rows); + + for(i=rows; i >=1; i--) + { + for(j=i; j T that denotes the number of test cases. This is followed by T lines, each containing an integer,N . + + +# #### Output Format + +# Print the required answer for each test case. + +# #### CONSTRAINTS +# 1≤ T ≤ 100 + +# 101101≤ N ≤ 1000000 + +# #### Sample Input +# ``` +# 2 +# 101110 +# 800000 +# ``` + +# #### Sample Output +# ``` +# 101101 +# 793397 +# ``` + +def main + # read the test cases + puts "Enter number of Test Cases (1-100)" + test_cases = gets.to_i + return "Number of test cases exceeds the range" if test_cases < 1 || test_cases > 100 + + # read the numbers + numbers = [] + puts "Enter numbers in the range of 101101 - 999999 " + test_cases.times do |n| + puts "Enter number #{n} : " + number = gets.to_i + return "Number out of range" if number < 101101 || number > 999999 + numbers << number + end + puts "********* OUTPUT ***********" + palindromes = [] + numbers.each do |num| + palindromes << largest_palindrome(num) + end + puts palindromes +end + +def largest_palindrome(number) + (101_101..number).to_a.reverse.each do |num| + next unless palindrome?(num) + return num if three_digit_product?(num) + end + 101_101 +end + +def three_digit_product?(number) + max_num = 999 + first_num = max_num + second_num = 101 # 999 * 101 gives the first 6 digit number + while first_num > second_num + product = first_num * second_num + return true if product == number + if product > number + first_num -= 1 + else + second_num += 1 + end + end + false +end + +def palindrome?(number) + digits = number.digits + digits == digits.reverse +end + + +# running the program +main diff --git a/SOLUTIONS/lcm.cpp b/SOLUTIONS/lcm.cpp new file mode 100644 index 00000000..ae609340 --- /dev/null +++ b/SOLUTIONS/lcm.cpp @@ -0,0 +1,21 @@ +#include +using namespace std; +int main() +{ + int a, b, x, y, temp, hcf, lcm; + cout<<"\n Enter Two Numbers : \n"; + cin>>x>>y; + a=x; + b=y; + while(b!=0) + { + temp=b; + b=a%b; + a=temp; + } + hcf=a; + lcm=(x*y)/hcf; + cout<<"\n HCF : "< new Promise(resolve => rl.question(text, resolve)); +const stop = exitText => { + rl.close(); + console.log('Stopping:', exitText); + process.exit(1); + }; +const operationList = { + '+': { noun: 'Sum', oper: (a, b) => a + b }, + '-': { noun: 'Difference', oper: (a, b) => a - b }, + '*': { noun: 'Product', oper: (a, b) => a * b }, + '/': { noun: 'Quotient', oper: (a, b) => b === 0 ? undefined : a / b } + }; +Object.assign(operationList, Object.entries({ + '+': [ 'add', 'addition', 'sum' ], + '-': [ 'sub', 'subtract', 'difference', 'diff' ], + '*': [ 'mult', 'multiply', 'multiplication', 'product', 'x' ], + '/': [ 'div', 'divide', 'division', 'quotient', '\\' ] +}).reduce((p, [ key, aliases ]) => { + aliases.forEach(a => p[a] = operationList[key]); + return p; + }, {})); +const maxRetries = 3; +const getElements = (m, n) => async (name, array) => { + console.log(`\nEnter the ${m * n} elements of ${name} ${m}x${n} matrix:`); + for(let c = 0; c < m; c++) { + let retries = maxRetries; + for(let d = 0; d < n; d++) { + array[c][d] = parseFloat(await question(`(${c}, ${d}): `)); + if(array[c][d] !== array[c][d]) { + if(retries) { + console.log(`Value could not be parsed as a valid number, try again. ${retries}/${maxRetries}`); + d--; + retries--; + } + else { + return stop(`Value could not be parsed as a valid number.`); + } + } + else { + retries = maxRetries; + } + } + } + }; + +(async () => { + const counts = await question('Enter the number of rows and columns of matrix\nType "86" for 8x6 matrices or "4" for 4x4.\n'); + let { 0: m, 1: n, length } = counts; + if(length !== 2 && length !== 1) { + return stop(length ? 'Too many arguments.' : 'Not enough arguments.'); + } + else if(length === 1) { + n = m; + } + m = parseInt(m); + n = parseInt(n); + if(m !== m || n !== n) { + return stop('Values could not be parsed as valid integers.'); + } + else if(!m || !n) { + return stop('Values cannot be 0.'); + } + let operation; + for(let i = maxRetries; i >= 0; i--) { + const operationInput = await question('Choose an operation: + - * /\n'); + operation = operationList[operationInput]; + if(operation) { + break; + } + if(i) { + console.log(`Not a valid operation, try again. ${i}/${maxRetries}`); + } + } + if(!operation) { + return stop('Could not pick a valid operation.'); + } + const { noun, oper } = operation; + const [ + first, second, sum + ] = Array(3).fill().map(_ => Array(m).fill().map(_ => Array(n).fill(0))); + const getData = getElements(m, n); + await getData('first', first); + await getData('second', second); + console.log('\nFirst matrix:'); + console.table(first); + console.log('\nSecond matrix:'); + console.table(second); + rl.close(); + console.log(`\n${noun} of entered matrices:`); + for(let c = 0; c < m; c++) { + for(let d = 0; d < n; d++) { + sum[c][d] = oper(first[c][d], second[c][d]); + } + } + console.table(sum); +})(); diff --git a/SOLUTIONS/myACIIIProduct.py b/SOLUTIONS/myACIIIProduct.py new file mode 100644 index 00000000..ccd863d7 --- /dev/null +++ b/SOLUTIONS/myACIIIProduct.py @@ -0,0 +1,9 @@ +from __future__ import print_function +# author: Harshil +string = raw_input() +product = 1 + +for e in string: + product *= ord(e) + +print(product) diff --git a/SOLUTIONS/myBinaryMultipleOf3.cpp b/SOLUTIONS/myBinaryMultipleOf3.cpp new file mode 100644 index 00000000..5b485fe4 --- /dev/null +++ b/SOLUTIONS/myBinaryMultipleOf3.cpp @@ -0,0 +1,34 @@ +#include +#include +#include + +using namespace std; + +int main() { + + int qtd, count = 0, len, exponent; + cin >> qtd; + + for(int i = 0; i < qtd; i++) { + char binary[100]; + cin >> binary; + + len = strlen(binary); + for (int i = len; i >= 0; i--) { + if(binary[i-1] == '1') { + exponent = len - i; + count += pow(2, exponent); + } + } + + if (count % 3 == 0){ + cout << "1" << endl; + } else { + cout << "0" << endl; + } + + count = 0; + } + + return 0; +} diff --git a/SOLUTIONS/myatm.cpp b/SOLUTIONS/myatm.cpp new file mode 100644 index 00000000..280d174f --- /dev/null +++ b/SOLUTIONS/myatm.cpp @@ -0,0 +1,24 @@ +#include + +using namespace std; + +int main() +{ + int T; + cin >> T; + while(T--){ + int n,k,p; + cin >> n >> k; + while(n--){ + cin >> p; + if(k >= p){ + k -= p; + cout << "1"; + } + else + cout << "0"; + } + cout << endl; + } + return 0; +} diff --git a/SOLUTIONS/palindrome-gauthamlal.js b/SOLUTIONS/palindrome-gauthamlal.js new file mode 100644 index 00000000..739164b6 --- /dev/null +++ b/SOLUTIONS/palindrome-gauthamlal.js @@ -0,0 +1,16 @@ +let palindrome = word => { + for (let i = 0, j = word.length - 1; i <=j; i++, j--) { + if(word[i] !== word[j]) { + return false; + } + } + return true; +} + +let word = 'malayalam'; + +if (palindrome(word.toLowerCase())) { + console.log(`${word} is a palindrome`); +} else { + console.log(`${word} is not a palindrome`); +} diff --git a/SOLUTIONS/palindrome.c b/SOLUTIONS/palindrome.c new file mode 100644 index 00000000..0cc24979 --- /dev/null +++ b/SOLUTIONS/palindrome.c @@ -0,0 +1,14 @@ +#include + +void check_palindrom( char string[]) { + + int len = strlen(string) - 1 ; + int i = 0 ; + + while (i < len ) { + if( string[i++] != string[len--] ) { + return true ; + } + } + return false ; +} diff --git a/SOLUTIONS/palindrome.js b/SOLUTIONS/palindrome.js new file mode 100644 index 00000000..42956530 --- /dev/null +++ b/SOLUTIONS/palindrome.js @@ -0,0 +1,15 @@ +function reverse(word){ + let splitWord = word.split('') + let reversed = []; + for (let i = splitWord.length-1; i>=0; i--){ + reversed.unshift(splitWord[i]) + } + + if ( reversed.join('') === word ) { + console.log(true, `"${ word }" is a palindrome`) + }else{ + console.log(false, `"${ word }" is not a palindrome`) + } + console.log(reversed.join(''));// Eve damned Eden, mad Eve +} +reverse('madam') \ No newline at end of file diff --git a/SOLUTIONS/pallindromeofstring.cpp b/SOLUTIONS/pallindromeofstring.cpp new file mode 100644 index 00000000..d54c9a70 --- /dev/null +++ b/SOLUTIONS/pallindromeofstring.cpp @@ -0,0 +1,20 @@ +//to check whether string is pallindrome or not +#include +#include +using namespace std; +int main() +{string str,str2; +cout<<"Enter the string :"; +getline(cin,str); +int l,i; +l=str.size(); +for(i=l-1;i>=0;i--) +{ str2=str2+str[i]; +} +cout< +using namespace std; +int main() +{ + int t; + cin>>t; + while(t--) + { + int n,count=0; + cin>>n; + int a[n]; + for(int i=0;i>a[i]; + if(a[i]%2==0) + count++; + } + cout< +int main() +{ + int rows, i, j,k, number= 1; + + printf("Enter number of rows: "); + scanf("%d",&rows); + + for(i=1; i <= rows; i++) + { + for(k=rows;k>i;k--) + { + printf(" "); + } + for(j=1; j <= 2*i-1; ++j) + { + printf("*"); + } + + printf("\n"); + } + return 0; +} \ No newline at end of file diff --git a/SOLUTIONS/questionforpractice.c b/SOLUTIONS/questionforpractice.c new file mode 100644 index 00000000..c8041f72 --- /dev/null +++ b/SOLUTIONS/questionforpractice.c @@ -0,0 +1,23 @@ +#include + +void main() +{ + char str[80]; + printf("Enter the string : "); + scanf("%s",str); + int i; + for(i=0;str[i]!=NULL;i++); + int flag=0,len=i; + for(i=0;i +#include + +using namespace std; + +int main(int argc, char const *argv[]) +{ + if (argc != 2) + { + cout << "How to use: \n $ ./rf [file]"; + return -1; + } + string filename = argv[1]; + ifstream file(filename); + string line; + while (file.eof() == 0) + { + getline(file, line); + cout << line << endl; + } + return 0; +} diff --git a/SOLUTIONS/readline.c b/SOLUTIONS/readline.c new file mode 100644 index 00000000..8fd038b5 --- /dev/null +++ b/SOLUTIONS/readline.c @@ -0,0 +1,10 @@ +#include +#define MAX 100 +int main() +{ + char buf[MAX]; + fgets(buf, MAX, stdin); + printf("string is: %s\n", buf); + + return 0; +} diff --git a/SOLUTIONS/reduction game b/SOLUTIONS/reduction game new file mode 100644 index 00000000..9781281c --- /dev/null +++ b/SOLUTIONS/reduction game @@ -0,0 +1,61 @@ +#include +#include + +int compare (const void * a, const void * b) +{ + if(*(long long int*)b - *(long long int*)a < 0) + return 1; + if(*(long long int*)b - *(long long int*)a == 0) + return 0; + if(*(long long int*)b - *(long long int*)a > 0) + return -1; +} + +int main(){ + long long t, n, k, a[50], i, j, l, sum, temp; + scanf("%lld",&t); + while(t--){ + scanf("%lld%lld",&n,&k); + sum = 0; + for (i=0;ii&&a[l]==a[l-1];l--); + temp = a[l]; + a[l] = a[j]; + a[j] = temp; + } + } + } + if (a[i] > k && n>=3){ + a[j] -= a[i] - k; + sum += k; + } + else if (n>=3){ + sum += a[i]; + } + if (a[j] > k){ + sum += k + a[n-1] - a[j] + k; + } + else { + sum += a[j] + a[n-1]; + } + printf("%lld\n",sum); + } +} diff --git a/SOLUTIONS/reduction.dev b/SOLUTIONS/reduction.dev new file mode 100644 index 00000000..50ad86d9 --- /dev/null +++ b/SOLUTIONS/reduction.dev @@ -0,0 +1,37 @@ +#include +using namespace std; + +int main() +{ + int t,i,n,j,k; + long s; + scanf("%d",&t); + for(i=0;i { + let wordArray = word.split(''); + let reverseWord = ""; + for (var i = wordArray.length - 1; i >= 0; i--) reverseWord+= wordArray[i] + return reverseWord; +} + +console.log(reverseWord('I love JS!')); diff --git a/SOLUTIONS/reverse-word b/SOLUTIONS/reverse-word new file mode 100644 index 00000000..3dcee9d5 --- /dev/null +++ b/SOLUTIONS/reverse-word @@ -0,0 +1,37 @@ +Write a program (using functions!) that asks the user for a long string containing multiple words. Print back to the user the same string, except with the words in backwards order. For example, say I type the string: + +My name is Michele + +Then I would see the string: + +Michele is name My + +shown back to me. + +#include +#include + +using namespace std; + +string s; + +int main() +{ + getline( cin, s ); + string st = ""; + int i = s.length() - 1; + while (i >= 0) + { + if (s[i] != ' ') + { + st = s[i] + st; + } + else + { + cout << st << ' '; + st = ""; + } + -- i; + } + cout << st; +} diff --git a/SOLUTIONS/reverse-word-in-sentence.js b/SOLUTIONS/reverse-word-in-sentence.js new file mode 100644 index 00000000..96a82bf4 --- /dev/null +++ b/SOLUTIONS/reverse-word-in-sentence.js @@ -0,0 +1,14 @@ +let reversedWord = function reverse(word){ + let splitWord = word.split(' ') + let reversed = []; + for (let i = 0; i<=splitWord.length; i++){ + reversed.unshift(splitWord[i]); + } + console.log(reversed.join(' ')) +} +reversedWord('My name is Michele') // Michelle is name My + + + + + diff --git a/SOLUTIONS/reverse-word-molcay.py b/SOLUTIONS/reverse-word-molcay.py new file mode 100644 index 00000000..b61962be --- /dev/null +++ b/SOLUTIONS/reverse-word-molcay.py @@ -0,0 +1,6 @@ +def reverse_word(): + sentence = input("Enter a sentence to reverse words order: ") + words = sentence.split(" ") + return " ".join(words[::-1]) + +print(reverse_word()) diff --git a/SOLUTIONS/reverse-word.py b/SOLUTIONS/reverse-word.py new file mode 100644 index 00000000..6e63b249 --- /dev/null +++ b/SOLUTIONS/reverse-word.py @@ -0,0 +1,8 @@ +def reverse_word(): + s = input("Enter a sentence containing multiple words: ").strip() + s = s.split()[::-1] + print(s) + s = " ".join(s) + return s + +print(reverse_word()) diff --git a/SOLUTIONS/reverse-word.scala b/SOLUTIONS/reverse-word.scala new file mode 100644 index 00000000..14acd2cb --- /dev/null +++ b/SOLUTIONS/reverse-word.scala @@ -0,0 +1,12 @@ +object ReverseWord extends App { + def reverseWord(): String = { + print("Enter a sentence to reverse words order: ") + val sentence = scala.io.StdIn.readLine() + println() + val words = sentence.split(" ") + val reversed_words = words.reverse + reversed_words.mkString(" ") + } + + println(reverseWord()) +} diff --git a/SOLUTIONS/reverse-word7.js b/SOLUTIONS/reverse-word7.js new file mode 100644 index 00000000..575ce57e --- /dev/null +++ b/SOLUTIONS/reverse-word7.js @@ -0,0 +1,9 @@ +REF: href="https://github.com/hackerearthclub/CODE2RACE/blob/master/ASSIGNMENTS/reverse-word.md">reverse-word.md + +function reverseWord(word) { + let arr = word.split(' '); + let reversed = arr.reverse(); + return reversed.join(' '); +} + +console.log(reverseWord("My name is Michele")); diff --git a/SOLUTIONS/reverseWord.py b/SOLUTIONS/reverseWord.py new file mode 100644 index 00000000..0c7fe4de --- /dev/null +++ b/SOLUTIONS/reverseWord.py @@ -0,0 +1,10 @@ +from __future__ import print_function +word = raw_input("Insert a long string: ").split() +output = '' + +for x in xrange(len(word)-1,0,-1): + output += word[x] + " " + +output += word[0] +print(output) + diff --git a/SOLUTIONS/reverse_string.py b/SOLUTIONS/reverse_string.py new file mode 100644 index 00000000..96df95be --- /dev/null +++ b/SOLUTIONS/reverse_string.py @@ -0,0 +1,7 @@ + +a = input() +a = a.split() +n = len(a) +for i in range(n-1,-1,-1): + print(a[i], end=" ") + diff --git a/SOLUTIONS/reverse_word.c b/SOLUTIONS/reverse_word.c new file mode 100644 index 00000000..aace8a02 --- /dev/null +++ b/SOLUTIONS/reverse_word.c @@ -0,0 +1,120 @@ +#include +#include + + +int ft_countword(char *str) +{ + int index; + int total; + + index = 0; + total = 0; + while (str[index]) + { + if (str[index] != '\t' && str[index] != ' ' && str[index] != '\n' + && (str[index + 1] == ' ' || str[index + 1] == '\t' + || str[index + 1] == '\0' || str[index + 1] == '\n')) + { + total++; + } + index++; + } + return (total); +} + +char **ft_malloctab(char *str, char **tab) +{ + int index; + int index_tab; + int count; + + index = 0; + index_tab = 0; + while (str[index]) + { + while (str[index] == ' ' || str[index] == '\t' || str[index] == '\n') + { + index++; + } + if (str[index] != '\0') + { + count = 0; + while (str[index] != ' ' && str[index] != '\t' + && str[index] != '\0' && str[index] != '\n') + { + count++; + index++; + } + tab[index_tab] = (char*)malloc(count + 1); + index_tab++; + } + } + return (tab); +} + +char **ft_filltab(char *str, char **tab) +{ + int index; + int index_tab; + int index_word; + + index = 0; + index_tab = 0; + while (str[index]) + { + while (str[index] == ' ' || str[index] == '\t' || str[index] == '\n') + { + index++; + } + if (str[index] != '\0') + { + index_word = 0; + while (str[index] != ' ' && str[index] != '\t' + && str[index] != '\0' && str[index] != '\n') + { + tab[index_tab][index_word] = str[index]; + index_word++; + index++; + } + tab[index_tab][index_word] = '\0'; + index_tab++; + } + } + tab[index_tab] = NULL; + return (tab); +} + +char **ft_split(char *str) +{ + int nb_words; + char **tab; + + nb_words = ft_countword(str); + tab = (char**)malloc(sizeof(char*) * (nb_words + 1)); + tab = ft_malloctab(str, tab); + tab = ft_filltab(str, tab); + return (tab); +} + +int main(void) +{ + char msg[1024]; + printf("Enter a sentence : "); + gets(msg); + char **tab = ft_split(msg); + int count = ft_countword(msg) - 1; + if (count >= 0) + { + while (count > 0) + { + printf("%s ", tab[count]); + count--; + } + printf("%s\n", tab[0]); + } + else + { + printf("Sentence error\n"); + } + return 0; +} diff --git a/SOLUTIONS/reverse_word.go b/SOLUTIONS/reverse_word.go new file mode 100644 index 00000000..65f30463 --- /dev/null +++ b/SOLUTIONS/reverse_word.go @@ -0,0 +1,24 @@ +package main + +import ( + "bufio" + "fmt" + "os" + "strings" +) + +func main() { + fmt.Println("Enter your text: ") + reader := bufio.NewReader(os.Stdin) + inputText, _ := reader.ReadString('\n') + reverseString := ReverseStringSlice(strings.Split(strings.TrimRight(inputText, "\n"), " ")) + fmt.Print("You reversed text is: ", strings.Join(reverseString, " ")) +} + +func ReverseStringSlice(inputString []string) []string { + lastWord := len(inputString) - 1 + for i := 0; i < len(inputString)/2; i++ { + inputString[i], inputString[lastWord-i] = inputString[lastWord-i], inputString[i] + } + return append(inputString, "\n") +} diff --git a/SOLUTIONS/reverse_word_.py b/SOLUTIONS/reverse_word_.py new file mode 100644 index 00000000..a4830009 --- /dev/null +++ b/SOLUTIONS/reverse_word_.py @@ -0,0 +1,5 @@ +def reverse_sentence(sentence): + return " ".join(sentence.split()[::-1]) + + +print(reverse_sentence("Once upon a time")) diff --git a/SOLUTIONS/robo.cpp b/SOLUTIONS/robo.cpp new file mode 100644 index 00000000..442e2154 --- /dev/null +++ b/SOLUTIONS/robo.cpp @@ -0,0 +1,65 @@ +#include +#include +using namespace std; +int main() +{ + long tc; + int i, j, dot, num, len, flag,l, k; + string s; + cin>>tc; + while(tc--) + { + k = 0; + dot = 0; + num = 0; + flag = 0; + cin>>s; + len = s.length(); + int d[100], index[100]; + for(i = 0; i < len; i++) + { + if(s[i] == '.') + dot++; + else + { + num++; + } + } + if(dot == len) + cout<<"safe"< + +using namespace std; + +int main() +{ + int search(int [],int,int); + int n,i,a[100],e,res; + cout<<"How Many Elements:"; + cin>>n; + cout<<"\nEnter Elements of Array in Ascending order\n"; + + for(i=0;i>a[i]; + } + + cout<<"\nEnter element to search:"; + cin>>e; + + res=search(a,n,e); + + if(res!=-1) + cout<<"\nElement found at position "<a[m]) + f=m+1; + else + l=m-1; + } + + return -1; +} diff --git a/SOLUTIONS/sens numbers b/SOLUTIONS/sens numbers new file mode 100644 index 00000000..099cd394 --- /dev/null +++ b/SOLUTIONS/sens numbers @@ -0,0 +1,6 @@ +a = int(input("num: ")) +count=0 +for i in range(a): + if(i%2==0): + count=count+1 +print count diff --git a/SOLUTIONS/sol b/SOLUTIONS/sol new file mode 100644 index 00000000..530ba249 --- /dev/null +++ b/SOLUTIONS/sol @@ -0,0 +1,59 @@ +#include +using namespace std; +vectorv[1005]; +queuequ; +int girls[1005]; +int bfs() +{ + int mi=10005; + while(!qu.empty()) + { + int t=qu.front(); + for(int i=0;i>n; + // vectorv[n]; + int x,y; + for(int i=0;i>x>>y; + v[x].push_back(y); + v[y].push_back(x); + } + int q; + cin>>q; + // bool girls[n+5]={false}; + int k; + while(q) + { + cin>>k; + girls[k]=true; + q--; + } + + qu.push(1); + cout<s; + +} diff --git a/SOLUTIONS/solution_hw.py b/SOLUTIONS/solution_hw.py new file mode 100644 index 00000000..1e0c3c61 --- /dev/null +++ b/SOLUTIONS/solution_hw.py @@ -0,0 +1,2 @@ +#for python 3.x + +print("Hello World") diff --git a/SOLUTIONS/stringReverse.py b/SOLUTIONS/stringReverse.py new file mode 100644 index 00000000..efb7880a --- /dev/null +++ b/SOLUTIONS/stringReverse.py @@ -0,0 +1,6 @@ +# issue no 615 + +def reverse(word): + return(word[::-1]) + +print(reverse(input("Enter a string to reverse "))) diff --git a/SOLUTIONS/sum--factorial digit.py b/SOLUTIONS/sum--factorial digit.py new file mode 100644 index 00000000..05910755 --- /dev/null +++ b/SOLUTIONS/sum--factorial digit.py @@ -0,0 +1,11 @@ +import math +t=int(input()) +while t>0: + x=int(input()) + number=math.factorial(x) + s=sum(int(digit) for digit in str(number)) + print(s) + t=t-1 + + + diff --git a/SOLUTIONS/sum_sq_diff.py b/SOLUTIONS/sum_sq_diff.py new file mode 100644 index 00000000..cb161d21 --- /dev/null +++ b/SOLUTIONS/sum_sq_diff.py @@ -0,0 +1,21 @@ +def sum_square_diff(N): + sum1 = 0 + sum2 = 0 + for num in range(1, N+1): + sum1 += num ** 2 + + for num in range(1, N+1): + sum2 += num + + sum2 = sum2 ** 2 + return abs(sum1-sum2) + +N_list = [] +T = int(input()) + +for _ in range(T): + N = int(input()) + N_list.append(N) + +for N in N_list: +print(sum_square_diff(N), end="\n") diff --git a/SOLUTIONS/sum_square_difference.cpp b/SOLUTIONS/sum_square_difference.cpp new file mode 100644 index 00000000..a0a51ff0 --- /dev/null +++ b/SOLUTIONS/sum_square_difference.cpp @@ -0,0 +1,16 @@ +#include +void main() +{ + int a,b,t,n; + cin>>t>>n; + while(t>0) + { + a=(n*(n+1))/2; + b=(n*(n+1)*(2*n+1))/6; + if(a>b) + cout<