diff --git a/.github/workflows/label.yml b/.github/workflows/labeler.yml similarity index 100% rename from .github/workflows/label.yml rename to .github/workflows/labeler.yml diff --git a/30 Days of Code/D0-Hello-World.py b/30 Days of Code (Python)/D0-Hello-World.py similarity index 100% rename from 30 Days of Code/D0-Hello-World.py rename to 30 Days of Code (Python)/D0-Hello-World.py diff --git a/30 Days of Code/D1-Data-Types.py b/30 Days of Code (Python)/D1-Data-Types.py similarity index 100% rename from 30 Days of Code/D1-Data-Types.py rename to 30 Days of Code (Python)/D1-Data-Types.py diff --git a/30 Days of Code/D10-Binary-Numbers.py b/30 Days of Code (Python)/D10-Binary-Numbers.py similarity index 100% rename from 30 Days of Code/D10-Binary-Numbers.py rename to 30 Days of Code (Python)/D10-Binary-Numbers.py diff --git a/30 Days of Code/D11-2D-Arrays.py b/30 Days of Code (Python)/D11-2D-Arrays.py similarity index 100% rename from 30 Days of Code/D11-2D-Arrays.py rename to 30 Days of Code (Python)/D11-2D-Arrays.py diff --git a/30 Days of Code/D12-Inheritance.py b/30 Days of Code (Python)/D12-Inheritance.py similarity index 100% rename from 30 Days of Code/D12-Inheritance.py rename to 30 Days of Code (Python)/D12-Inheritance.py diff --git a/30 Days of Code/D13-Abstract-Class.py b/30 Days of Code (Python)/D13-Abstract-Class.py similarity index 100% rename from 30 Days of Code/D13-Abstract-Class.py rename to 30 Days of Code (Python)/D13-Abstract-Class.py diff --git a/30 Days of Code/D14-Scope.py b/30 Days of Code (Python)/D14-Scope.py similarity index 100% rename from 30 Days of Code/D14-Scope.py rename to 30 Days of Code (Python)/D14-Scope.py diff --git a/30 Days of Code/D15-Linked-List.py b/30 Days of Code (Python)/D15-Linked-List.py similarity index 100% rename from 30 Days of Code/D15-Linked-List.py rename to 30 Days of Code (Python)/D15-Linked-List.py diff --git a/30 Days of Code/D16-Exceptions.py b/30 Days of Code (Python)/D16-Exceptions.py similarity index 100% rename from 30 Days of Code/D16-Exceptions.py rename to 30 Days of Code (Python)/D16-Exceptions.py diff --git a/30 Days of Code/D17-More-Exceptions.py b/30 Days of Code (Python)/D17-More-Exceptions.py similarity index 100% rename from 30 Days of Code/D17-More-Exceptions.py rename to 30 Days of Code (Python)/D17-More-Exceptions.py diff --git a/30 Days of Code/D18-Queues-and-Stacks.py b/30 Days of Code (Python)/D18-Queues-and-Stacks.py similarity index 100% rename from 30 Days of Code/D18-Queues-and-Stacks.py rename to 30 Days of Code (Python)/D18-Queues-and-Stacks.py diff --git a/30 Days of Code/D19-Interfaces.py b/30 Days of Code (Python)/D19-Interfaces.py similarity index 100% rename from 30 Days of Code/D19-Interfaces.py rename to 30 Days of Code (Python)/D19-Interfaces.py diff --git a/30 Days of Code/D2-Operators.py b/30 Days of Code (Python)/D2-Operators.py similarity index 100% rename from 30 Days of Code/D2-Operators.py rename to 30 Days of Code (Python)/D2-Operators.py diff --git a/30 Days of Code/D20-Sorting.py b/30 Days of Code (Python)/D20-Sorting.py similarity index 100% rename from 30 Days of Code/D20-Sorting.py rename to 30 Days of Code (Python)/D20-Sorting.py diff --git a/30 Days of Code/D21-Generics.java b/30 Days of Code (Python)/D21-Generics.java similarity index 100% rename from 30 Days of Code/D21-Generics.java rename to 30 Days of Code (Python)/D21-Generics.java diff --git a/30 Days of Code/D22-Binary-Search-Trees.py b/30 Days of Code (Python)/D22-Binary-Search-Trees.py similarity index 100% rename from 30 Days of Code/D22-Binary-Search-Trees.py rename to 30 Days of Code (Python)/D22-Binary-Search-Trees.py diff --git a/30 Days of Code/D23-BST-Level-Order-Traversal.py b/30 Days of Code (Python)/D23-BST-Level-Order-Traversal.py similarity index 100% rename from 30 Days of Code/D23-BST-Level-Order-Traversal.py rename to 30 Days of Code (Python)/D23-BST-Level-Order-Traversal.py diff --git a/30 Days of Code/D24-More-Linked-Lists.py b/30 Days of Code (Python)/D24-More-Linked-Lists.py similarity index 100% rename from 30 Days of Code/D24-More-Linked-Lists.py rename to 30 Days of Code (Python)/D24-More-Linked-Lists.py diff --git a/30 Days of Code/D25-Running-Time-and-Complexity.py b/30 Days of Code (Python)/D25-Running-Time-and-Complexity.py similarity index 100% rename from 30 Days of Code/D25-Running-Time-and-Complexity.py rename to 30 Days of Code (Python)/D25-Running-Time-and-Complexity.py diff --git a/30 Days of Code/D26-Nested-Logic.py b/30 Days of Code (Python)/D26-Nested-Logic.py similarity index 100% rename from 30 Days of Code/D26-Nested-Logic.py rename to 30 Days of Code (Python)/D26-Nested-Logic.py diff --git a/30 Days of Code/D27-Testing.py b/30 Days of Code (Python)/D27-Testing.py similarity index 100% rename from 30 Days of Code/D27-Testing.py rename to 30 Days of Code (Python)/D27-Testing.py diff --git a/30 Days of Code/D28-RegEx,-Patterns,-and-Intro-to-Databases.py b/30 Days of Code (Python)/D28-RegEx,-Patterns,-and-Intro-to-Databases.py similarity index 100% rename from 30 Days of Code/D28-RegEx,-Patterns,-and-Intro-to-Databases.py rename to 30 Days of Code (Python)/D28-RegEx,-Patterns,-and-Intro-to-Databases.py diff --git a/30 Days of Code/D29-Bitwise-AND.py b/30 Days of Code (Python)/D29-Bitwise-AND.py similarity index 100% rename from 30 Days of Code/D29-Bitwise-AND.py rename to 30 Days of Code (Python)/D29-Bitwise-AND.py diff --git a/30 Days of Code/D3-Intro-to-Conditional-Statements.py b/30 Days of Code (Python)/D3-Intro-to-Conditional-Statements.py similarity index 100% rename from 30 Days of Code/D3-Intro-to-Conditional-Statements.py rename to 30 Days of Code (Python)/D3-Intro-to-Conditional-Statements.py diff --git a/30 Days of Code/D4-Class-vs-Instance.py b/30 Days of Code (Python)/D4-Class-vs-Instance.py similarity index 100% rename from 30 Days of Code/D4-Class-vs-Instance.py rename to 30 Days of Code (Python)/D4-Class-vs-Instance.py diff --git a/30 Days of Code/D5-Loops.py b/30 Days of Code (Python)/D5-Loops.py similarity index 100% rename from 30 Days of Code/D5-Loops.py rename to 30 Days of Code (Python)/D5-Loops.py diff --git a/30 Days of Code/D6-Let's-Review.py b/30 Days of Code (Python)/D6-Let's-Review.py similarity index 100% rename from 30 Days of Code/D6-Let's-Review.py rename to 30 Days of Code (Python)/D6-Let's-Review.py diff --git a/30 Days of Code/D7-Arrays.py b/30 Days of Code (Python)/D7-Arrays.py similarity index 100% rename from 30 Days of Code/D7-Arrays.py rename to 30 Days of Code (Python)/D7-Arrays.py diff --git a/30 Days of Code/D8-Dictionaries-and-Maps.py b/30 Days of Code (Python)/D8-Dictionaries-and-Maps.py similarity index 100% rename from 30 Days of Code/D8-Dictionaries-and-Maps.py rename to 30 Days of Code (Python)/D8-Dictionaries-and-Maps.py diff --git a/30 Days of Code/D9-Recursion-3.py b/30 Days of Code (Python)/D9-Recursion-3.py similarity index 100% rename from 30 Days of Code/D9-Recursion-3.py rename to 30 Days of Code (Python)/D9-Recursion-3.py diff --git a/Algorithms/CountSort1.cpp b/Algorithms/CountSort1.cpp new file mode 100644 index 00000000..66675c9e --- /dev/null +++ b/Algorithms/CountSort1.cpp @@ -0,0 +1,134 @@ +/* +Comparison Sorting +Quicksort usually has a running time of , but is there an algorithm that can sort even faster? In general, this is not possible. Most sorting algorithms are comparison sorts, i.e. they sort a list just by comparing the elements to one another. A comparison sort algorithm cannot beat (worst-case) running time, since represents the minimum number of comparisons needed to know where to place each element. For more details, you can see these notes (PDF). + +Alternative Sorting +Another sorting method, the counting sort, does not require comparison. Instead, you create an integer array whose index range covers the entire range of values in your array to sort. Each time a value occurs in the original array, you increment the counter at that index. At the end, run through your counting array, printing the value of each non-zero valued index that number of times. + +For example, consider an array . All of the values are in the range , so create an array of zeroes, . The results of each iteration follow: + +i arr[i] result +0 1 [0, 1, 0, 0] +1 1 [0, 2, 0, 0] +2 3 [0, 2, 0, 1] +3 2 [0, 2, 1, 1] +4 1 [0, 3, 1, 1] +Now we can print the list of occurrences, or determine the sorted array: . + +Challenge +Given a list of integers, count and output the number of times each value appears as a list of space-separated integers. + +Function Description + +Complete the countingSort function in the editor below. It should return an array of integers where each value is the number of occurrences of the element's index value in the original array. + +countingSort has the following parameter(s): + +arr: an array of integers +Input Format + +The first line contains an integer , the number of items in . +Each of the next lines contains an integer where . + +Constraints + + + +Output Format + +Output the number of times every number from through appears in as a list of space-separated integers on one line. + +Sample Input + +100 +63 25 73 1 98 73 56 84 86 57 16 83 8 25 81 56 9 53 98 67 99 12 83 89 80 91 39 86 76 85 74 39 25 90 59 10 94 32 44 3 89 30 27 79 46 96 27 32 18 21 92 69 81 40 40 34 68 78 24 87 42 69 23 41 78 22 6 90 99 89 50 30 20 1 43 3 70 95 33 46 44 9 69 48 33 60 65 16 82 67 61 32 21 79 75 75 13 87 70 33 +Sample Output + +0 2 0 2 0 0 1 0 1 2 1 0 1 1 0 0 2 0 1 0 1 2 1 1 1 3 0 2 0 0 2 0 3 3 1 0 0 0 0 2 2 1 1 1 2 0 2 0 1 0 1 0 0 1 0 0 2 1 0 1 1 1 0 1 0 1 0 2 1 3 2 0 0 2 1 2 1 0 2 2 1 2 1 2 1 1 2 2 0 3 2 1 1 0 1 1 1 0 2 2 +Explanation + +Each of the resulting values represents the number of times appeared in . +*/ +#include + +using namespace std; + +vector split_string(string); + +// Complete the countingSort function below. +vector countingSort(vector arr) { + + vectorcount(100,0); + + for(int i:arr) + count[i]++; + + return count; +} + +int main() +{ + ofstream fout(getenv("OUTPUT_PATH")); + + int n; + cin >> n; + cin.ignore(numeric_limits::max(), '\n'); + + string arr_temp_temp; + getline(cin, arr_temp_temp); + + vector arr_temp = split_string(arr_temp_temp); + + vector arr(n); + + for (int i = 0; i < n; i++) { + int arr_item = stoi(arr_temp[i]); + + arr[i] = arr_item; + } + + vector result = countingSort(arr); + + for (int i = 0; i < result.size(); i++) { + fout << result[i]; + + if (i != result.size() - 1) { + fout << " "; + } + } + + fout << "\n"; + + fout.close(); + + return 0; +} + +vector split_string(string input_string) { + string::iterator new_end = unique(input_string.begin(), input_string.end(), [] (const char &x, const char &y) { + return x == y and x == ' '; + }); + + input_string.erase(new_end, input_string.end()); + + while (input_string[input_string.length() - 1] == ' ') { + input_string.pop_back(); + } + + vector splits; + char delimiter = ' '; + + size_t i = 0; + size_t pos = input_string.find(delimiter); + + while (pos != string::npos) { + splits.push_back(input_string.substr(i, pos - i)); + + i = pos + 1; + pos = input_string.find(delimiter, i); + } + + splits.push_back(input_string.substr(i, min(pos, input_string.length()) - i + 1)); + + return splits; +} diff --git a/Algorithms/Intro to Tutorial Challenges.py b/Algorithms/Intro to Tutorial Challenges.py new file mode 100644 index 00000000..b1cc2019 --- /dev/null +++ b/Algorithms/Intro to Tutorial Challenges.py @@ -0,0 +1,86 @@ +'''# Problem: https://www.hackerrank.com/challenges/tutorial-intro/problem +# Score: 30 +About Tutorial Challenges +Many of the challenges on HackerRank are difficult and assume that you already know the relevant algorithms. These tutorial challenges are different. They break down algorithmic concepts into smaller challenges so that you can learn the algorithm by solving them. They are intended for those who already know some programming, however. You could be a student majoring in computer science, a self-taught programmer, or an experienced developer who wants an active algorithms review. Here's a great place to learn by doing! + +The first series of challenges covers sorting. They are listed below: + +Tutorial Challenges - Sorting + +Insertion Sort challenges + +Insertion Sort 1 - Inserting +Insertion Sort 2 - Sorting +Correctness and loop invariant +Running Time of Algorithms +Quicksort challenges + +Quicksort 1 - Partition +Quicksort 2 - Sorting +Quicksort In-place (advanced) +Running time of Quicksort +Counting sort challenges + +Counting Sort 1 - Counting +Counting Sort 2 - Simple sort +Counting Sort 3 - Preparing +Full Counting Sort (advanced) +There will also be some challenges where you'll get to apply what you've learned using the completed algorithms. + +About the Challenges +Each challenge will describe a scenario and you will code a solution. As you progress through the challenges, you will learn some important concepts in algorithms. In each challenge, you will receive input on STDIN and you will need to print the correct output to STDOUT. + +There may be time limits that will force you to make your code efficient. If you receive a "Terminated due to time out" message when you submit your solution, you'll need to reconsider your method. If you want to test your code locally, each test case can be downloaded, inputs and expected results, using hackos. You earn hackos as you solve challenges, and you can spend them on these tests. + +For many challenges, helper methods (like an array) will be provided for you to process the input into a useful format. You can use these methods to get started with your program, or you can write your own input methods if you want. Your code just needs to print the right output to each test case. + +Sample Challenge +This is a simple challenge to get things started. Given a sorted array () and a number (), can you print the index location of in the array? + +For example, if and , you would print for a zero-based index array. + +If you are going to use the provided code for I/O, this next section is for you. + +Function Description + +Complete the introTutorial function in the editor below. It must return an integer representing the zero-based index of . + +introTutorial has the following parameter(s): + +arr: a sorted array of integers +V: an integer to search for +The next section describes the input format. You can often skip it, if you are using included methods or code stubs. + +Input Format + +The first line contains an integer, , a value to search for. +The next line contains an integer, , the size of . The last line contains space-separated integers, each a value of where . + +Output Format +Output the index of in the array. + +The next section describes the constraints and ranges of the input. You should check this section to know the range of the input. + +Constraints + +It is guaranteed that will occur in exactly once. +This "sample" shows the first input test case. It is often useful to go through the sample to understand a challenge. + +Sample Input 0 + +4 +6 +1 4 5 7 9 12 +Sample Output 0 + +1 +Explanation 0 +. The value is the element in the array, but its index is since in this case, array indices start from (see array definition under Input Format). +''' +v = int(input()) +n = int(input()) +arr = list(map(int, input().split())) +i = 0 +while arr[i] != v: + i += 1 +print(i) diff --git a/Algorithms/Marc's Cakewalk.py b/Algorithms/Marc's Cakewalk.py new file mode 100644 index 00000000..de86f306 --- /dev/null +++ b/Algorithms/Marc's Cakewalk.py @@ -0,0 +1,58 @@ +'''# Problem: https://www.hackerrank.com/challenges/marcs-cakewalk/problem +# Score: 15 +Marc loves cupcakes, but he also likes to stay fit. Each cupcake has a calorie count, and Marc can walk a distance to expend those calories. If Marc has eaten cupcakes so far, after eating a cupcake with calories he must walk at least miles to maintain his weight. + +For example, if he eats cupcakes with calorie counts in the following order: , the miles he will need to walk are . This is not the minimum, though, so we need to test other orders of consumption. In this case, our minimum miles is calculated as . + +Given the individual calorie counts for each of the cupcakes, determine the minimum number of miles Marc must walk to maintain his weight. Note that he can eat the cupcakes in any order. + +Function Description + +Complete the marcsCakewalk function in the editor below. It should return a long integer that represents the minimum miles necessary. + +marcsCakewalk has the following parameter(s): + +calorie: an integer array that represents calorie count for each cupcake +Input Format + +The first line contains an integer , the number of cupcakes in . +The second line contains space-separated integers . + +Constraints + +Output Format + +Print a long integer denoting the minimum number of miles Marc must walk to maintain his weight. + +Sample Input 0 + +3 +1 3 2 +Sample Output 0 + +11 +Explanation 0 + +Let's say the number of miles Marc must walk to maintain his weight is . He can minimize by eating the cupcakes in the following order: + +Eat the cupcake with calories, so . +Eat the cupcake with calories, so . +Eat the cupcake with calories, so . +We then print the final value of , which is , as our answer. + +Sample Input 1 + +4 +7 4 9 6 +Sample Output 1 + +79 +''' + +_ = input() +calories = list(map(int, input().split())) +calories = sorted(calories, reverse=True) +ans = 0 +for index, cupcake in enumerate(calories): + ans += 2**index*cupcake +print(ans) diff --git a/Algorithms/Minimum Absolute Difference in an Array.py b/Algorithms/Minimum Absolute Difference in an Array.py new file mode 100644 index 00000000..9a031686 --- /dev/null +++ b/Algorithms/Minimum Absolute Difference in an Array.py @@ -0,0 +1,66 @@ +'''# Problem: https://www.hackerrank.com/challenges/minimum-absolute-difference-in-an-array/problem +# Score: 15 +Consider an array of integers, . We define the absolute difference between two elements, and (where ), to be the absolute value of . + +Given an array of integers, find and print the minimum absolute difference between any two elements in the array. For example, given the array we can create pairs of numbers: and . The absolute differences for these pairs are , and . The minimum absolute difference is . + +Function Description + +Complete the minimumAbsoluteDifference function in the editor below. It should return an integer that represents the minimum absolute difference between any pair of elements. + +minimumAbsoluteDifference has the following parameter(s): + +n: an integer that represents the length of arr +arr: an array of integers +Input Format + +The first line contains a single integer , the size of . +The second line contains space-separated integers . + +Constraints + +Output Format + +Print the minimum absolute difference between any two elements in the array. + +Sample Input 0 + +3 +3 -7 0 +Sample Output 0 + +3 +Explanation 0 + +With integers in our array, we have three possible pairs: , , and . The absolute values of the differences between these pairs are as follows: + +Notice that if we were to switch the order of the numbers in these pairs, the resulting absolute values would still be the same. The smallest of these possible absolute differences is . + +Sample Input 1 + +10 +-59 -36 -13 1 -53 -92 -2 -96 -54 75 +Sample Output 1 + +1 +Explanation 1 + +The smallest absolute difference is . + +Sample Input 2 + +5 +1 -3 71 68 17 +Sample Output 2 + +3 +Explanation 2 + +The minimum absolute difference is ''' + +_ = input() +arr = sorted(map(int, input().split())) +diff = 2*10**9 +for i in range(1, len(arr)): + diff = min(diff, arr[i] - arr[i-1]) +print(diff) diff --git a/Algorithms/Permuting Two Arrays.py b/Algorithms/Permuting Two Arrays.py new file mode 100644 index 00000000..46e6c723 --- /dev/null +++ b/Algorithms/Permuting Two Arrays.py @@ -0,0 +1,62 @@ +'''# Problem: https://www.hackerrank.com/challenges/two-arrays/problem +# Score: 40 +Consider two -element arrays of integers, and . You want to permute them into some and such that the relation holds for all where . For example, if , , and , a valid satisfying our relation would be and , and . + +You are given queries consisting of , , and . For each query, print YES on a new line if some permutation , satisfying the relation above exists. Otherwise, print NO. + +Function Description + +Complete the twoArrays function in the editor below. It should return a string, either YES or NO. + +twoArrays has the following parameter(s): + +k: an integer +A: an array of integers +B: an array of integers +Input Format + +The first line contains an integer , the number of queries. + +The next sets of lines are as follows: + +The first line contains two space-separated integers and , the size of both arrays and , and the relation variable. +The second line contains space-separated integers . +The third line contains space-separated integers . +Constraints + +Output Format + +For each query, print YES on a new line if valid permutations exist. Otherwise, print NO. + +Sample Input + +2 +3 10 +2 1 3 +7 8 9 +4 5 +1 2 2 1 +3 3 3 4 +Sample Output + +YES +NO +Explanation + +We perform the following two queries: + +, , and . We permute these into and so that the following statements are true: + +Thus, we print YES on a new line. + +, , and . To permute and into a valid and , we would need at least three numbers in to be greater than ; as this is not the case, we print NO on a new line.''' + +n = int(input()) +for _ in range(n): + __, k = map(int, input().split()) + a = sorted(list(map(int, input().split()))) + b = sorted(list(map(int, input().split())), reverse=True) + if all([a[i] + b[i] >= k for i in range(len(a))]): + print('YES') + else: + print('NO') diff --git a/Algorithms/README.md b/Algorithms/README.md index bc033014..153f9ca6 100644 --- a/Algorithms/README.md +++ b/Algorithms/README.md @@ -1 +1 @@ -# Algorithms \ No newline at end of file +# Algorithms diff --git a/C/README.md b/C/README.md index 325fc601..57b88955 100644 --- a/C/README.md +++ b/C/README.md @@ -1 +1 @@ -# C \ No newline at end of file +# C diff --git a/CPP/ColoringBallsProblem.cpp b/CPP/ColoringBallsProblem.cpp new file mode 100644 index 00000000..1a3b687d --- /dev/null +++ b/CPP/ColoringBallsProblem.cpp @@ -0,0 +1,94 @@ +/* QUESTION */ +/* Boboniu gives you + +r red balls, +g green balls, +b blue balls, +w white balls. +He allows you to do the following operation as many times as you want: + +Pick a red ball, a green ball, and a blue ball and then change their color to white. +You should answer if it's possible to arrange all the balls into a palindrome after +several (possibly zero) number of described operations. + +Input +The first line contains one integer T (1≤T≤100) denoting the number of test cases. + +For each of the next T cases, the first line contains four integers r, g, b and w (0≤r,g,b,w≤109). + +Output +For each test case, print "Yes" if it's possible to arrange all the balls into a palindrome after doing s +everal (possibly zero) number of described operations. Otherwise, print "No".*/ + +/* ANSWER */ + +#include +#define MOD 998244353 +#define IO ios_base::sync_with_stdio(false);cin.tie(NULL); +#define fo(i,a,b) for(i=a;i vi; +typedef std::vector > vv; +#define print(vec,a,b) for(ll i=a;i>vec[i]; +using namespace std; +const int N = 1e6+5; +void solve(){ + ll n,g,r,b,w; + cin>>g>>r>>b>>w; + ll ev=0,odd=0,e=0,o=0,zero = 0; + //ev= odd=o=e =0; + if(!g||!b||!r) + zero = 1; + if(g%2) + ev++; + else + odd++; + if(r%2) + ev++; + else + odd++; + if(b%2) + ev++; + else + odd++; + if(w%2) + e++; + else + o++; + //cout<>t; + + + while(t--) + { + + solve(); + } + return 0; +} \ No newline at end of file diff --git a/CPP/Largest_Bitonic_Subarray.cpp b/CPP/Largest_Bitonic_Subarray.cpp new file mode 100644 index 00000000..ee389ee5 --- /dev/null +++ b/CPP/Largest_Bitonic_Subarray.cpp @@ -0,0 +1,80 @@ +/* You are given an array of positive integers as input. Write a code to return the length of the largest such subsequence in which the values are arranged first in strictly ascending order and then in strictly descending order. +Such a subsequence is known as bitonic subsequence. A purely increasing or purely decreasing subsequence will also be considered as a bitonic sequence with the other part empty. +Note that the elements in bitonic subsequence need not be consecutive in the given array but the order should remain same. +Input Format: +Line 1 : A positive Integer N, i.e., the size of array +Line 2 : N space-separated integers as elements of the array +Output Format: +Length of Largest Bitonic subsequence +Input Constraints: +1<= N <= 100000 +Sample Input 1: +6 +15 20 20 6 4 2 +Sample Output 1: +5 +Sample Output 1 Explanation: +Here, longest Bitonic subsequence is {15, 20, 6, 4, 2} which has length = 5. +Sample Input 2: +2 +1 5 +Sample Output 2: +2 +Sample Input 3: +2 +5 1 +Sample Output 3: +2 */ + + + +#include +#include +using namespace std; +int* lis(int* input, int n) +{ + int* output = new int[n]; + output[0] = 1; + for (int i = 1; i < n; i++) + { + int current_maximum = 0; + for (int j = 0; j < i; j++) + { + if (input[i] > input[j]) + { + current_maximum = max(current_maximum, output[j]); + } + } + output[i] = current_maximum + 1; + } + return output; +} +int* lis_back(int* input, int n) +{ + int* output = new int[n]; + output[n - 1] = 1; + for (int i = n - 2; i >= 0; i--) + { + int current_maximum = 0; + for (int j = i + 1; j < n; j++) + { + if (input[i] > input[j]) + { + current_maximum = max(current_maximum, output[j]); + } + } + output[i] = current_maximum + 1; + } + return output; +} +int longestBitonicSubarray(int* input, int n) +{ + int* longest_increasing_subsequence = lis(input, n); + int* longest_increasing_subsequence_from_back = lis_back(input, n); + int maximum = 2; + for (int i = 0; i < n; i++) + { + maximum = max(maximum, longest_increasing_subsequence_from_back[i] + longest_increasing_subsequence[i] - 1); + } + return maximum; +} diff --git a/CPP/Multi-Level-Inheritance.cpp b/CPP/Multi-Level-Inheritance.cpp new file mode 100644 index 00000000..c0d9eba0 --- /dev/null +++ b/CPP/Multi-Level-Inheritance.cpp @@ -0,0 +1,65 @@ +/* +This challenge is an extension of a previous challenge named Inheritance-Introduction. We highly recommend solving Inheritance-Introduction before solving this problem. + +In the previous problem, we learned about inheritance and how can a derived class object use the member functions of the base class. + +In this challenge, we explore multi-level inheritance. Suppose, we have a class A which is the base class and we have a class B which is derived from class A and we have a class C which is derived from class B, we can access the functions of both class A and class B by creating an object for class C. Hence, this mechanism is called multi-level inheritance. (B inherits A and C inherits B.) + +Create a class called Equilateral which inherits from Isosceles and should have a function such that the output is as given below. + +Sample Output + +I am an equilateral triangle +I am an isosceles triangle +I am a triangle +*/ + + +#include +#include +#include +#include +#include +using namespace std; + +class Triangle +{ +public: +void triangle() +{ +cout<<"I am a triangle\n"; +} +}; + +class Isosceles : public Triangle +{ +public: +void isosceles() +{ +cout<<"I am an isosceles triangle\n"; +} +}; + +class Equilateral:public Isosceles +{ +public: +void equilateral() +{ +cout<<"I am an equilateral triangle\n"; +} +}; + +int main() +{ + +Equilateral eqr; + +eqr.equilateral(); + +eqr.isosceles(); + +eqr.triangle(); + +return 0; + +} diff --git a/CPP/README.md b/CPP/README.md index 6a1f50cf..7ba12416 100644 --- a/CPP/README.md +++ b/CPP/README.md @@ -1 +1,6 @@ -# CPP (C++) \ No newline at end of file +# CPP Codes for HackerRank +![GitHub contributors](https://img.shields.io/github/contributors/swapnanildutta/Hackerrank-Codes?style=plastic) +## Problems solved in C++ +* [RecursiveDigitSum](https://www.hackerrank.com/challenges/recursive-digit-sum/problem) +* [TheCoinChangeProblem](https://www.hackerrank.com/challenges/coin-change/problem) +* [TheMaximumSubarray](https://www.hackerrank.com/challenges/maxsubarray/problem) diff --git a/Data Structures/Arrays/LeftRotation.py b/Data Structures/Arrays/LeftRotation.py new file mode 100644 index 00000000..a423df3a --- /dev/null +++ b/Data Structures/Arrays/LeftRotation.py @@ -0,0 +1,57 @@ +""" +Left Rotation + +A left rotation operation on an array of size shifts each of the array's elements unit to the left. Given an integer, , rotate the array that many steps left and return the result. + +Example + + +After rotations, . + +Function Description + +Complete the rotateLeft function in the editor below. + +rotateLeft has the following parameters: + +int d: the amount to rotate by +int arr[n]: the array to rotate +Returns + +int[n]: the rotated array +Input Format + +The first line contains two space-separated integers that denote , the number of integers, and , the number of left rotations to perform. +The second line contains space-separated integers that describe . + +Constraints + +Sample Input + +5 4 +1 2 3 4 5 +Sample Output + +5 1 2 3 4 +Explanation + +To perform left rotations, the array undergoes the following sequence of changes: + [1,2,3,4,5] -> [2,3,4,5,1] -> [3,4,5,1,2] -> [4,5,1,2,3] -> [5,1,2,3,4] + +""" +if __name__ == '__main__': + nd = input().split() + + n = int(nd[0]) + + d = int(nd[1]) + + a = list(map(int, input().rstrip().split())) + + d = d%len(a) + + l2 = a[:d] + l1 = a[d:] + l1 = l1+l2 + + print(*l1) diff --git a/Java/Java_Comparator/Solution.java b/Java/Java_Comparator/Solution.java new file mode 100644 index 00000000..5d441f87 --- /dev/null +++ b/Java/Java_Comparator/Solution.java @@ -0,0 +1,88 @@ +/* +Java Comparator Hackerrank Problem: +https://www.hackerrank.com/challenges/java-comparator/problem + +Comparators are used to compare two objects. In this challenge, you'll create a comparator and use it to sort an array. + +The Player class is provided for you in your editor. It has fields: a String and a integer. + +Given an array of Player objects, write a comparator that sorts them in order of decreasing score; if or more players have the same score, sort those players alphabetically by name. To do this, you must create a Checker class that implements the Comparator interface, then write an int compare(Player a, Player b) method implementing the Comparator.compare(T o1, T o2) method. + +Input Format + +Input from stdin is handled by the locked stub code in the Solution class. + +The first line contains an integer, , denoting the number of players. +Each of the subsequent lines contains a player's and , respectively. + +Constraints + +0 <= score <= 1000 +2 players can have the same name. +Player names consist of lowercase English letters. + +Output Format + +You are not responsible for printing any output to stdout. The locked stub code in Solution will create a Checker object, use it to sort the Player array, and print each sorted element. + +Sample Input + +5 +amy 100 +david 100 +heraldo 50 +aakansha 75 +aleksa 150 + +Sample Output + +aleksa 150 +amy 100 +david 100 +aakansha 75 +heraldo 50 + +*/ + +import java.util.*; + +// Write your Checker class here + +class Checker implements Comparator { + public int compare(Player a, Player b) { + return a.score == b.score ? a.name.compareTo(b.name) : Integer.compare(b.score, a.score); + } +} + +// (Starter code below) + +class Player { + String name; + int score; + + Player(String name, int score) { + this.name = name; + this.score = score; + } +} + +class Solution { + + public static void main(String[] args) { + Scanner scan = new Scanner(System.in); + int n = scan.nextInt(); + + Player[] player = new Player[n]; + Checker checker = new Checker(); + + for (int i = 0; i < n; i++) { + player[i] = new Player(scan.next(), scan.nextInt()); + } + scan.close(); + + Arrays.sort(player, checker); + for (int i = 0; i < player.length; i++) { + System.out.printf("%s %s\n", player[i].name, player[i].score); + } + } +} \ No newline at end of file diff --git a/Java/README.md b/Java/README.md index 526e9b11..ab1cf631 100644 --- a/Java/README.md +++ b/Java/README.md @@ -1 +1,2 @@ -# Java \ No newline at end of file +# Java +- [Java Comparator](https://www.hackerrank.com/challenges/java-comparator/problem) diff --git a/Java/Welcome to java.java b/Java/Welcome to java.java new file mode 100644 index 00000000..f475d8aa --- /dev/null +++ b/Java/Welcome to java.java @@ -0,0 +1,26 @@ +/* Welcome to the world of Java! In this challenge, we practice printing to stdout. +The code stubs in your editor declare a Solution class and a main method. Complete the main method by copying the two lines of code below and pasting them inside the body of your main method. + System.out.println("Hello, World."); + System.out.println("Hello, Java."); + +Input Format + +There is no input for this challenge. + +Output Format + +You must print two lines of output: + Print Hello, World. on the first line. + Print Hello, Java. on the second line. + +Sample Output + +Hello, World. +Hello, Java. */ + +public class Solution { + public static void main(String[] args) { + System.out.println("Hello, World."); + System.out.println("Hello, Java."); + } +} diff --git a/Java/WelcomeToJava.java b/Java/WelcomeToJava.java new file mode 100644 index 00000000..cac77706 --- /dev/null +++ b/Java/WelcomeToJava.java @@ -0,0 +1,27 @@ +/* +Welcome to the world of Java! In this challenge, we practice printing to stdout. + +The code stubs in your editor declare a Solution class and a main method. Complete the main method by copying the two lines of code below and pasting them inside the body of your main method. + +System.out.println("Hello, World."); +System.out.println("Hello, Java."); +Input Format + +There is no input for this challenge. + +Output Format + +You must print two lines of output: + +Print Hello, World. on the first line. +Print Hello, Java. on the second line. +Sample Output + +Hello, World. +Hello, Java. +*/ + +public static void main(String[] args) { + System.out.println("Hello, World."); + System.out.println("Hello, Java."); +} \ No newline at end of file diff --git a/LeftRotation.py b/LeftRotation.py new file mode 100644 index 00000000..03204572 --- /dev/null +++ b/LeftRotation.py @@ -0,0 +1,43 @@ +# -*- coding: utf-8 -*- +""" +Created on Sun Oct 4 15:15:37 2020 + +@author: Tanmoyee +""" + +''' A left rotation operation on an array of size n shifts each of the array's elements 1 unit to the left. Given an integer, d, rotate the array that many steps left and return the result. + +Example + +d=2 +arr=[1,2,3,4,5] +after 2 rotations, arr'=[3,4,5,1,2] +''' + + + + + + +#!/bin/python3 + +import math +import os +import random +import re +import sys + +def left_rotate(a,d): + l=a[d:] + a[:d] + print(" ".join(list(map(str,l)))) + +if __name__ == '__main__': + nd = input().split() + + n = int(nd[0]) + + d = int(nd[1]) + + a = list(map(int, input().rstrip().split())) + result=left_rotate(a,d) + diff --git a/Problem Solving/AppleAndOranges.c b/Problem Solving/AppleAndOranges.c new file mode 100644 index 00000000..d92d21ab --- /dev/null +++ b/Problem Solving/AppleAndOranges.c @@ -0,0 +1,113 @@ +// Question +// Apple and Orange + +// Sam's house has an apple tree and an orange tree that yield an abundance of fruit. Using the information given below, determine the number of apples and oranges that land on Sam's house. + +// In the diagram below: + +// The red region denotes the house, where + +// is the start point, and +// is the endpoint. The apple tree is to the left of the house, and the orange tree is to its right. +// Assume the trees are located on a single point, where the apple tree is at point +// , and the orange tree is at point +// . +// When a fruit falls from its tree, it lands +// units of distance from its tree of origin along the -axis. *A negative value of means the fruit fell units to the tree's left, and a positive value of means it falls units to the tree's right. * + +// Giveethe value of d for m apples and n oranges, determine how many apples and oranges will fall on Sam's house(i.e in the inclusive range[s,t])? +// For example, Sam's House is between s = 7 and t = 10. The apple tree is located at a = 4 and the orange at b = 12. There are m=3 apples and n=3 oranges. Apples are thrown apples=[2,3,-4] unit distance from a +// and oranges = [3,-2,-4] units distance. Adding each apples distance to the position of the tree, they land at [4+2,4+3,4+-4] = [6,7,0]. Oranges land at [12+3,12+-2,12+-4] = [15,10,8]. One apple and two oranges +// land in the inclusive range 7-10 so we print + +// 1 +// 2 + + +// Function Description + +// Complete the countApplesAndOranges function in the editor below. It should print the number of apples and oranges that land on Sam's house, each on a separate line. + +// countApplesAndOranges has the following parameter(s): + +// s: integer, starting point of Sam's house location. +// t: integer, ending location of Sam's house location. +// a: integer, location of the Apple tree. +// b: integer, location of the Orange tree. +// apples: integer array, distances at which each apple falls from the tree. +// oranges: integer array, distances at which each orange falls from the tree. + + + +// Input Format + +// The first line contains two space-separated integers denoting the respective values of s +// and t. +// The second line contains two space-separated integers denoting the respective values of a and b. +// The third line contains two space-separated integers denoting the respective values of m and n. +// The fourth line contains m space-separated integers denoting the respective distances that each apple falls from point a. +// The fifth line contains n space-separated integers denoting the respective distances that each orange falls from point b. + +// Constraints +// 1 <=s,t,a,b,m,n <= 10^5 +// -10^5 <= d <= 10^5 +// a < s < t < b + +// Sample Input 0 + +// 7 11 +// 5 15 +// 3 2 +// -2 2 1 +// 5 -6 + +// Sample Output 0 + +// 1 +// 1 + + + + + +// Solution + + +#include +#include +#include + +int main() +{ + int s,t,a,b,m,n,acount=0,ocount=0,i; + int apple[100002],orange[100002]; + scanf("%d %d",&s,&t); + scanf("%d %d",&a,&b); + scanf("%d %d",&m,&n); + for (i = 0; i < m; ++i) + { + scanf("%d",&apple[i]); + apple[i] = apple[i] + a; + } + for (i = 0; i < n; ++i) + { + scanf("%d",&orange[i]); + orange[i] = orange[i] + b; + } + for (i = 0; i < m ; i++) + { + if (apple[i] >= s && apple[i] <= t ) + { + acount = acount + 1; + } + } + for (i = 0; i < n; i++) + { + if (orange[i] >= s && orange[i] <= t ) + { + ocount = ocount + 1; + } + } + printf("%d\n",acount); + printf("%d",ocount); +} \ No newline at end of file diff --git a/Problem Solving/Fair_Rations.cpp b/Problem Solving/Fair_Rations.cpp new file mode 100644 index 00000000..f00f2c7c --- /dev/null +++ b/Problem Solving/Fair_Rations.cpp @@ -0,0 +1,107 @@ +/* problem-statement +You are the benevolent ruler of Rankhacker Castle, and today you're distributing bread. Your subjects are in a line, and some of them already have some loaves. +Times are hard and your castle's food stocks are dwindling, so you must distribute as few loaves as possible according to the following rules: +Every time you give a loaf of bread to some person,i, you must also give a loaf of bread to the person immediately in front of or behind them in the line (i.e., persons(i+1) or (i-1) +After all the bread is distributed, each person must have an even number of loaves. +Given the number of loaves already held by each citizen, find and print the minimum number of loaves you must distribute to satisfy the two rules above. If this is not possible, print NO. + +For example, the people in line have loaves, B=[4,5,6,7]. We can first give a loaf to i=3 and i=4 so B=[4,5,7,8] . +Next we give a loaf to i=2 and i=3 and have B=[4,6,8,8] which satisfies our conditions. We had to distribute 4 loaves. + +Function Description +Complete the fairRations function in the editor below. It should return an integer that represents the minimum number of loaves required. +fairRations has the following parameter(s): + B: an array of integers that represent the number of loaves each persons starts with . + +Input Format + +The first line contains an integer,N, the number of subjects in the bread line. +The second line contains N space-separated integers B[i] . + +Output Format +Print a single integer taht denotes the minimum number of loaves that must be distributed so that every person has an even number of loaves. If it's not possible to do this, print NO. + +Sample Input 0 +5 +2 3 4 5 6 +Sample Output 0 +4 +Explanation 0 +The initial distribution is(2,3,4,5,6). The requirements can be met as follows: +Given 1 loaf of bread each to the second and third people so that the distribution becomes (2,4,5,5,6). +Give 1 loaf of bread each to the third and fourth people so that the distribution becomes (2,4,6,6,6) +Each of the N subjects has an even number of loaves after 4 loaves were distributed. */ + +#include +using namespace std; +vector split_string(string); +// Complete the fairRations function below. +int fairRations(vector b) { +int count=0; +for(int i=0;i> N; + cin.ignore(numeric_limits::max(), '\n'); + string B_temp_temp; + getline(cin, B_temp_temp); + vector B_temp = split_string(B_temp_temp); + vector B(N); + for (int i = 0; i < N; i++) { + int B_item = stoi(B_temp[i]); + B[i] = B_item; + } +int result = fairRations(B); + if(result==-1) + fout<<"NO"<<"\n"; + else + fout< split_string(string input_string) { + string::iterator new_end = unique(input_string.begin(), input_string.end(), [] (const char &x, const char &y) { + return x == y and x == ' '; + }); + input_string.erase(new_end, input_string.end()); + while (input_string[input_string.length() - 1] == ' ') { + input_string.pop_back(); + } + vector splits; + char delimiter = ' '; + size_t i = 0; + size_t pos = input_string.find(delimiter); + while (pos != string::npos) { + splits.push_back(input_string.substr(i, pos - i)); + i = pos + 1; + pos = input_string.find(delimiter, i); + } + splits.push_back(input_string.substr(i, min(pos, input_string.length()) - i + 1)); + return splits; +} + diff --git a/Problem Solving/FraudulentActivityNotification.py b/Problem Solving/FraudulentActivityNotification.py new file mode 100644 index 00000000..f9f2f9f0 --- /dev/null +++ b/Problem Solving/FraudulentActivityNotification.py @@ -0,0 +1,117 @@ +''' +HackerLand National Bank has a simple policy for warning clients about possible fraudulent account activity. If the amount spent by a client on a particular day is greater than or equal to the client's median spending for a trailing number of days, they send the client a notification about potential fraud. The bank doesn't send the client any notifications until they have at least that trailing number of prior days' transaction data. + +Given the number of trailing days and a client's total daily expenditures for a period of days, find and print the number of times the client will receive a notification over all days. + +For example, and . On the first three days, they just collect spending data. At day , we have trailing expenditures of . The median is and the day's expenditure is . Because , there will be a notice. The next day, our trailing expenditures are and the expenditures are . This is less than so no notice will be sent. Over the period, there was one notice sent. + +Note: The median of a list of numbers can be found by arranging all the numbers from smallest to greatest. If there is an odd number of numbers, the middle one is picked. If there is an even number of numbers, median is then defined to be the average of the two middle values. (Wikipedia) + +Function Description + +Complete the function activityNotifications in the editor below. It must return an integer representing the number of client notifications. + +activityNotifications has the following parameter(s): + +expenditure: an array of integers representing daily expenditures +d: an integer, the lookback days for median spending +Input Format + +The first line contains two space-separated integers and , the number of days of transaction data, and the number of trailing days' data used to calculate median spending. +The second line contains space-separated non-negative integers where each integer denotes . + +Constraints + +Output Format + +Print an integer denoting the total number of times the client receives a notification over a period of days. + +Sample Input 0 + +9 5 +2 3 4 2 3 6 8 4 5 +Sample Output 0 + +2 +Explanation 0 + +We must determine the total number of the client receives over a period of days. For the first five days, the customer receives no notifications because the bank has insufficient transaction data: . + +On the sixth day, the bank has days of prior transaction data, , and dollars. The client spends dollars, which triggers a notification because : . + +On the seventh day, the bank has days of prior transaction data, , and dollars. The client spends dollars, which triggers a notification because : . + +On the eighth day, the bank has days of prior transaction data, , and dollars. The client spends dollars, which does not trigger a notification because : . + +On the ninth day, the bank has days of prior transaction data, , and a transaction median of dollars. The client spends dollars, which does not trigger a notification because : . + +Sample Input 1 + +5 4 +1 2 3 4 4 +Sample Output 1 + +0 +There are days of data required so the first day a notice might go out is day . Our trailing expenditures are with a median of The client spends which is less than so no notification is sent. +''' + +# --------Solution------- + +#!/bin/python3 + +import math +import os +import random +import re +import sys +from collections import deque +def median(v, d): + count = 0 + if d%2==0: + m1 = None + m2 = None + for i in range(len(v)): + count += v[i] + if count >= d/2 and m1 is None: + m1 = i + if count >= d/2 + 1: + m2 = i + break + return (m1 + m2)/2 + else: + for i in range(len(v)): + count += v[i] + if count > d/2: + return i + return -1 + +def activityNotifications(expenditure, d): + dq = deque(expenditure[: d]) + v = [0]*201 + for n in dq: + v[n] += 1 + count = 0 + for current in expenditure[d:]: + if current >= median(v, d)*2: + count += 1 + v[current] += 1 + dq.append(current) + v[dq.popleft()] -= 1 + return count + +if __name__ == '__main__': + fptr = open(os.environ['OUTPUT_PATH'], 'w') + + nd = input().split() + + n = int(nd[0]) + + d = int(nd[1]) + + expenditure = list(map(int, input().rstrip().split())) + + result = activityNotifications(expenditure, d) + + fptr.write(str(result) + '\n') + + fptr.close() diff --git a/Problem Solving/Pairs.cpp b/Problem Solving/Pairs.cpp new file mode 100644 index 00000000..cf899d01 --- /dev/null +++ b/Problem Solving/Pairs.cpp @@ -0,0 +1,54 @@ +/* +Pairs +You will be given an array of integers and a target value. Determine the number of pairs of array elements +that have a difference equal to a target value. +For example, given an array of [1, 2, 3, 4] and a target value of 1, we have three values meeting the +condition: , , and . +Function Description +Complete the pairs function below. It must return an integer representing the number of element pairs +having the required difference. +pairs has the following parameter(s): +k: an integer, the target difference +arr: an array of integers +Input Format +The first line contains two space-separated integers and , the size of and the target value. +The second line contains space-separated integers of the array arr. +Constraints +each integer will be unique +Output Format +An integer representing the number of pairs of integers whose difference is . +Sample Input +5 2 +1 5 3 4 2 +Sample Output +3 +Explanation +There are 3 pairs of integers in the set with a difference of 2: [5,3], [4,2] and [3,1] . +*/ + +#include +using namespace std; +#define ll unsigned long long int +#define mp make_pair +#define pb push_back +typedef vector vll; +typedef pair pll; +typedef vector vpll; +typedef map mpll; +typedef map mll; +int main() +{ + ll n,k; + cin>>n>>k; + vll a(n); + mll hash; + mpll pairHash; + vpll result; + for(auto &i:a)cin>>i,hash[i]=1; + for(auto &i:a){ + if(hash.find(k+i)!=hash.end()){ + result.pb(mp(k+i,i)); + } + } + cout< +#include +#include +using namespace std; + +vector split_string(string); + +// Complete the flatlandSpaceStations function . +int flatlandSpaceStations(int n, vector c) { +vector arr; +int t,p=0; +for(int i=0;i nm = split_string(nm_temp); + + int n = stoi(nm[0]); + + int m = stoi(nm[1]); + + string c_temp_temp; + getline(cin, c_temp_temp); + + vector c_temp = split_string(c_temp_temp); + + vector c(m); + + for (int i = 0; i < m; i++) { + int c_item = stoi(c_temp[i]); + + c[i] = c_item; + } + + int result = flatlandSpaceStations(n, c); + + fout << result << "\n"; + + fout.close(); + + return 0; +} + +vector split_string(string input_string) { + string::iterator new_end = unique(input_string.begin(), input_string.end(), [] (const char &x, const char &y) { + return x == y and x == ' '; + }); + + input_string.erase(new_end, input_string.end()); + + while (input_string[input_string.length() - 1] == ' ') { + input_string.pop_back(); + } + + vector splits; + char delimiter = ' '; + + size_t i = 0; + size_t pos = input_string.find(delimiter); + + while (pos != string::npos) { + splits.push_back(input_string.substr(i, pos - i)); + + i = pos + 1; + pos = input_string.find(delimiter, i); + } + + splits.push_back(input_string.substr(i, min(pos, input_string.length()) - i + 1)); + + return splits; +} diff --git a/Python/Else-If.py b/Python/Else-If.py index 6f038597..133798e3 100644 --- a/Python/Else-If.py +++ b/Python/Else-If.py @@ -1,11 +1,8 @@ ''' Task Given an integer, - , perform the following conditional actions: - If - is odd, print Weird If is even and in the inclusive range of to @@ -15,45 +12,24 @@ , print Weird If is even and greater than - , print Not Weird - Input Format - A single line containing a positive integer, - . - Constraints - Output Format - Print Weird if the number is weird; otherwise, print Not Weird. - Sample Input 0 - 3 - Sample Output 0 - Weird - Explanation 0 - - is odd and odd numbers are weird, so we print Weird. - Sample Input 1 - 24 - Sample Output 1 - Not Weird - Explanation 1 - - and is even, so it isn't weird. Thus, we print Not Weird. ''' @@ -63,17 +39,16 @@ import re import sys -n=0 -if __name__ == '__main__': - n = int(input().strip()) -if n%2!=0: - print('Weird') -else: - if n in range(2,5): - print('Not Weird') - elif n in range(6,20+1): - print('Weird') +if __name__ == '__main__': + n = int(raw_input().strip()) + if n%2==0 and n<=5: + print("Not Weird") + elif n%2!=0: + print("Weird") + elif n%2==0 and n<=20: + print("Weird") else: - print('Not Weird') \ No newline at end of file + print("Not Weird") + diff --git a/Python/No Idea! - Find your Happiness.py b/Python/No Idea! - Find your Happiness.py new file mode 100644 index 00000000..1cb42d81 --- /dev/null +++ b/Python/No Idea! - Find your Happiness.py @@ -0,0 +1,53 @@ +''' +There is an array of n integers. There are also 2 disjoint sets, A and B, each containing m integers. You like all the integers in set A and dislike all the integers in set B. Your initial happiness is 0. For each i integer in the array, if i ∈ A, you add 1 to your happiness. If i ∈ B, you add -1 to your happiness. Otherwise, your happiness does not change. Output your final happiness at the end. + +Note: Since A and B are sets, they have no repeated elements. However, the array might contain duplicate elements. + +Constraints + +1 <= n <= 10^5 +1 <= n <= 10^5 +1 <= Any integer in the inputs <= 10^9 + +Input Format + +The first line contains integers n and m separated by a space. +The second line contains n integers, the elements of the array. +The third and fourth lines contain m integers, A and B, respectively. + +Output Format + +Output a single integer, your total happiness. + +Sample Input + +3 2 +1 5 3 +3 1 +5 7 + +Sample Output + +1 + +Explanation + +You gain 1 unit of happiness for elements 3 and 1 in set A. You lose 1 unit for 5 in set B. The element 7 in set B does not exist in the array so it is not included in the calculation. +Hence, the total happiness is 2 - 1 = 1. +''' + +if __name__ == '__main__': + n,m=[int(i) for i in input().split(" ")] + + n1=[int(i) for i in input().split(" ")] + + a=set([int(i) for i in input().split(" ")]) + + b=set([int(i) for i in input().split(" ")]) + happiness=0 + for j in n1: + if j in a: + happiness+=1 + if j in b: + happiness-=1 +print(happiness) diff --git a/Python/README.md b/Python/README.md index 92106a82..29868ea9 100644 --- a/Python/README.md +++ b/Python/README.md @@ -1 +1,34 @@ -# Python \ No newline at end of file +# Python Hackerrank Codes + +**Following Codes are Present** + + +* [Capitalize](https://github.com/swapnanildutta/Hackerrank-Codes/blob/master/Python/Capitalize!.py) +* [Collections Counter](https://github.com/swapnanildutta/Hackerrank-Codes/blob/master/Python/CollectionsCounter.py) +* [Collections Namedtuple](https://github.com/swapnanildutta/Hackerrank-Codes/blob/master/Python/CollectionsNamedtuple.py) +* [Collections OrderedDict](https://github.com/swapnanildutta/Hackerrank-Codes/blob/master/Python/CollectionsOrderedDict.py) +* [Compress the String](https://github.com/swapnanildutta/Hackerrank-Codes/blob/master/Python/Compress%20the%20String.py) +* [Else-If](https://github.com/swapnanildutta/Hackerrank-Codes/blob/master/Python/Else-If.py) +* [Find a string](https://github.com/swapnanildutta/Hackerrank-Codes/blob/master/Python/Find%20a%20string.py) +* [Finding The Percentage](https://github.com/swapnanildutta/Hackerrank-Codes/blob/master/Python/FindingThePercentage.py) +* [Find Second RunnerUp](https://github.com/swapnanildutta/Hackerrank-Codes/blob/master/Python/FindSecondRunnerUp.py) +* [Iterables and Iterators](https://github.com/swapnanildutta/Hackerrank-Codes/blob/master/Python/Iterables%20and%20Iterators.py) +* [Itertools Combinations](https://github.com/swapnanildutta/Hackerrank-Codes/blob/master/Python/ItertoolsCombinations.py) +* [Itertools Combinations with Replacecment](https://github.com/swapnanildutta/Hackerrank-Codes/blob/master/Python/ItertoolsCombinations_with_replacement.py) +* [Itertools Permutation](https://github.com/swapnanildutta/Hackerrank-Codes/blob/master/Python/ItertoolsPermutations.py) +* [Itertools Product](https://github.com/swapnanildutta/Hackerrank-Codes/blob/master/Python/ItertoolsProduct.py) +* [Leap Year](https://github.com/swapnanildutta/Hackerrank-Codes/blob/master/Python/LeapYear.py) +* [List Comprehension](https://github.com/swapnanildutta/Hackerrank-Codes/blob/master/Python/ListComprehensions.py) +* [Mutations]https://github.com/swapnanildutta/Hackerrank-Codes/blob/master/Python/Mutations.py() +* [NestedLists](https://github.com/swapnanildutta/Hackerrank-Codes/blob/master/Python/NestedLists.py) +* [Mod Power](https://github.com/swapnanildutta/Hackerrank-Codes/blob/master/Python/Power%20-%20Mod%20Power.py) +* [Set discard remove and copy](https://github.com/swapnanildutta/Hackerrank-Codes/blob/master/Python/Set%20.discard()%2C%20.remove()%20%26%20.pop().py) +* [String Validators](https://github.com/swapnanildutta/Hackerrank-Codes/blob/master/Python/String%20Validators.py) +* [swapcase](https://github.com/swapnanildutta/Hackerrank-Codes/blob/master/Python/sWAPcASE.py) +* [Symmetric Difference](https://github.com/swapnanildutta/Hackerrank-Codes/blob/master/Python/SymmetricDifference.py) +* [Text Alignment](https://github.com/swapnanildutta/Hackerrank-Codes/blob/master/Python/Text%20Alignment.py) +* [Text Wrap](https://github.com/swapnanildutta/Hackerrank-Codes/blob/master/Python/Text%20Wrap.pyv) +* [Tuples](https://github.com/swapnanildutta/Hackerrank-Codes/blob/master/Python/Tuples.py) +* [What's your name](https://github.com/swapnanildutta/Hackerrank-Codes/blob/master/Python/What's%20Your%20Name.py) +* [Word Order](https://github.com/swapnanildutta/Hackerrank-Codes/blob/master/Python/Word%20Order.py) + diff --git a/Python/Sales by Match.py b/Python/Sales by Match.py new file mode 100644 index 00000000..755a4a0e --- /dev/null +++ b/Python/Sales by Match.py @@ -0,0 +1,53 @@ +#problem hackerrank.com/challenges/sock-merchant/problem +#points 10 +'''Alex works at a clothing store. There is a large pile of socks that must be paired by color for sale. Given an array of integers representing the color of each sock, determine how many pairs of socks with matching colors there are. + +For example, there are socks with colors . There is one pair of color and one of color . There are three odd socks left, one of each color. The number of pairs is . + +Function Description + +Complete the sockMerchant function in the editor below. It must return an integer representing the number of matching pairs of socks that are available. + +sockMerchant has the following parameter(s): + +n: the number of socks in the pile +ar: the colors of each sock +Input Format + +The first line contains an integer , the number of socks represented in . +The second line contains space-separated integers describing the colors of the socks in the pile. + +Constraints +Output Format + +Return the total number of matching pairs of socks that Alex can sell. + +Sample Input + +9 +10 20 20 10 10 30 50 10 20 +Sample Output + +3 +Explanation + +sock.png + +Alex can match three pairs of socks''' + +#solution +def sockMerchant(n, ar): + return sum([ar.count(i)//2 for i in set(ar)]) + +if __name__ == '__main__': + fptr = open(os.environ['OUTPUT_PATH'], 'w') + + n = int(input()) + + ar = list(map(int, input().rstrip().split())) + + result = sockMerchant(n, ar) + + fptr.write(str(result) + '\n') + + fptr.close() diff --git a/Python/Set.add().py b/Python/Set.add().py new file mode 100644 index 00000000..37bd6ad5 --- /dev/null +++ b/Python/Set.add().py @@ -0,0 +1,59 @@ +""" +Task + +Apply your knowledge of the .add() operation to help your friend Rupal. + +Rupal has a huge collection of country stamps. +She decided to count the total number of distinct country stamps in her collection. +She asked for your help. You pick the stamps one by one from a stack of +n country stamps + +Input Format + +The first line contains an integer n, the total number of country stamps. +The next n lines contains the name of the country where the stamp is from. + +Input Format + +The first line contains an integer , the total number of country stamps. +The next lines contains the name of the country where the stamp is from. + +Constraints +0>> a = "this is a string" +>>> a = a.split(" ") # a is converted to a list of strings. +>>> print a +['this', 'is', 'a', 'string'] + +Joining a string is simple: + +>>> a = "-".join(a) +>>> print a +this-is-a-string + +Task +You are given a string. Split the string on a " " (space) delimiter and join using a - hyphen. + +Input Format +The first line contains a string consisting of space separated words. + +Output Format +Print the formatted string as explained above. + +Sample Input + +this is a string + +Sample Output + +this-is-a-string + +""" + +def split_and_join(line): + return "-".join(line.split(" ")) + +if __name__ == '__main__': + line = raw_input() + result = split_and_join(line) + print(result) diff --git a/Python/StringsplitandJoin.py b/Python/StringsplitandJoin.py new file mode 100644 index 00000000..5c582046 --- /dev/null +++ b/Python/StringsplitandJoin.py @@ -0,0 +1,28 @@ +#Answer to the challenge "String split and Join" in Python3 + +#In Python, a string can be split on a delimeter. Example +#>>> a = "this is a string" +#>>> a = a.split(" ") # a is converted to a list of strings. +#>>> print a +#['this', 'is', 'a', 'string'] + +#joining a string is simple : + +#>>> a = "-".join(a) +#>>> print a +#this-is-a-string + +#Task :- You are given a string. Split the string on a " "(space)delimeter and join using a - hyphen + +#input Format :- The first line contains a string consisting of space separated words. + +#output Format:- Print the formatted string as explained above + +#Sample input :- this is a string. + +#sample output:- this-is-a-string + +#the code to be written directly in a compiler. + +print('-'.join(input().split())) + diff --git a/Python/TheMinionGame.py b/Python/TheMinionGame.py new file mode 100644 index 00000000..874452f8 --- /dev/null +++ b/Python/TheMinionGame.py @@ -0,0 +1,109 @@ +#Type 1 +#Kevin and Stuart want to play 'The Minion Game' + +#Game Rules + +#1) Both players are given the same string, S +#2) Both players have to make substrings using the letters of the string . +#3) Stuart has to make words starting with consonants. +#4) Kevin has to make words starting with vowels. +#5) The game ends when both players have made all possible substrings. + +#Scoring :- A player gets +1 points for each occurance of the substring in the string S + +#For Example :- String S = BANANA +#Kevin's vowel beginning word = ANA +#Here's ANA occurs twice in BANANA. Hence, Kevin will get 2 points. + +#Input Format :- A single line of input containing the string S. Also, The string S will contain only uppercase letters [A-Z] + +#Constratints :- 0 < len(S) < 10 to the power 6 + +#Output :- Print one line: the name of the winner and their score separated by a space. If the game is a draw, print Draw. + +#Sample Input :- BANANA +#Sample Output :- Stuart 12 + +def minion_game(string): + vowel =['A','E','I','O','U'] + S=0 + K=0 + for i in range(len(string)): + if string[i] in vowel: + K+= len(string)-i + else: + S+=len(string)-i + if S>K: + print("Stuart"+" "+ "%d" % S) + elif K>S: + print("Kevin"+" "+'%d' % K) + else: + print("Draw") + +#Note :- The Answer is to put directly in the compiler (Any Python compiler) +======= +#Type 2 +''' + Kevin and Stuart want to play the 'The Minion Game'. + +Game Rules + +Both players are given the same string, S. +Both players have to make substrings using the letters of the string S. +Stuart has to make words starting with consonants. +Kevin has to make words starting with vowels. +The game ends when both players have made all possible substrings. + +Scoring +A player gets +1 point for each occurrence of the substring in the string S. + +For Example: +String S = BANANA +Kevin's vowel beginning word = ANA +Here, ANA occurs twice in BANANA. Hence, Kevin will get 2 Points. + +Your task is to determine the winner of the game and their score. + +Input Format + +A single line of input containing the string S. +Note: The string will contain only uppercase letters: [A - Z]. + +Constraints + 0 < len(S) < 10^6 + +Output Format + +Print one line: the name of the winner and their score separated by a space. + +If the game is a draw, print Draw. + +Sample Input +BANANA + +Sample Output +Stuart 12 + +Note : +Vowels are only defined as AEIOU. In this problem,Y is not considered a vowel. +''' + +def minion_game(string): + vowels = {'A', 'E', 'I', 'O', 'U'} + kevin = 0 # vowels + stuart = 0 # consonants + for i in range(len(string)): + if string[i] in vowels: + kevin += len(string) - i + else: + stuart += len(string) - i + if kevin > stuart: + print('Kevin', kevin) + elif stuart > kevin: + print('Stuart', stuart) + else: + print('Draw') +if __name__ == '__main__': + s = input() + minion_game(s) + diff --git a/Python/TriangleQuest.py b/Python/TriangleQuest.py new file mode 100644 index 00000000..4cb88741 --- /dev/null +++ b/Python/TriangleQuest.py @@ -0,0 +1,36 @@ +''' +You are given a positive integer . Print a numerical triangle of height like the one below: + +1 +22 +333 +4444 +55555 +...... +Can you do it using only arithmetic operations, a single for loop and print statement? + +Use no more than two lines. The first line (the for statement) is already written for you. You have to complete the print statement. + +Note: Using anything related to strings will give a score of . + +Input Format +A single line containing integer, . + +Constraints + +Output Format +Print lines as explained above. + +Sample Input + +5 +Sample Output + +1 +22 +333 +4444 +''' + +for i in range(1,int(input())): + print((10**(i)//9)*i) diff --git a/Python/Write_a_function.py b/Python/Write_a_function.py new file mode 100644 index 00000000..c9723509 --- /dev/null +++ b/Python/Write_a_function.py @@ -0,0 +1,36 @@ +#problem https://www.hackerrank.com/challenges/write-a-function/problem +#points 10 +''' +Write a function - Hacker Rank Solution +We add a Leap Day on February 29, almost every four years. The leap day is an extra, or intercalary, day and we add it to the shortest month of the year, February. + +In the Gregorian calendar three criteria must be taken into account to identify leap years: +The year can be evenly divided by 4; +If the year can be evenly divided by 100, it is NOT a leap year, unless; +The year is also evenly divisible by 400. Then it is a leap year. +This means that in the Gregorian calendar, the years 2000 and 2400 are leap years, while 1800, 1900, 2100, 2200, 2300 and 2500 are NOT leap years.Source +Task +You are given the year, and you have to write a function to check if the year is leap or not. + + +Note that you have to complete the function and remaining code is given as template. +Input Format +Read y, the year that needs to be checked. +Constraints +Output Format +Output is taken care of by the template. Your function must return a boolean value (True/False) +Sample Input +1990 +Sample Output +False +Explanation +1990 is not a multiple of 4 hence it's not a leap year.''' + +def is_leap(year): + leapyear = False + if (((year%4==0 and year%100!=0) or year%400==0) and year>=1900): + leapyear=True + return leapyear + +year = int(input()) +print(is_leap(year)) \ No newline at end of file diff --git a/Python/sWAPcASE.py b/Python/sWAPcASE.py index c5260573..f25d3c46 100644 --- a/Python/sWAPcASE.py +++ b/Python/sWAPcASE.py @@ -31,17 +31,10 @@ ''' def swap_case(s): - result='' - for i in s: - if i.isalpha() and i.isupper(): - result+=i.lower() - elif i.isalpha() and i.islower(): - result+=i.upper() - else: - result+=i - return result + s=s.swapcase() + return s if __name__ == '__main__': s = input() result = swap_case(s) - print(result) \ No newline at end of file + print(result) diff --git a/README.md b/README.md index 43f3ae04..297f220d 100644 --- a/README.md +++ b/README.md @@ -1,5 +1,9 @@ [![HitCount](http://hits.dwyl.com/swapnanildutta/Hackerrank-Codes.svg)](http://hits.dwyl.com/swapnanildutta/Hackerrank-Codes) [![PRs Welcome](https://img.shields.io/badge/PRs-welcome-brightgreen.svg?style=flat-square)](http://makeapullrequest.com) +[![GitHub forks](https://img.shields.io/github/forks/swapnanildutta/Hackerrank-Codes?style=flat-square)](https://github.com/swapnanildutta/Hackerrank-Codes/network) +[![GitHub issues](https://img.shields.io/github/issues/swapnanildutta/Hackerrank-Codes?style=flat-square)](https://github.com/swapnanildutta/Hackerrank-Codes/issues) +[![GitHub stars](https://img.shields.io/github/stars/swapnanildutta/Hackerrank-Codes?style=flat-square)](https://github.com/swapnanildutta/Hackerrank-Codes/stargazers) +![GitHub Hacktoberfest combined status](https://img.shields.io/github/hacktoberfest/2020/swapnanildutta/Hackerrank-Codes?color=%23072541&label=hacktoberfest%202020&style=flat-square) # Hackerrank-Codes Here are some of the HackerRank Codes. Please try them by yourself and then check them out. These are just to help you understand better. @@ -12,4 +16,7 @@ For contributing, please follow the following instructions : - Create a pull request with the name of the file you want to add or change, specifying the changes you made. - Add working codes. Please ! - Raise an issue whenever you find something incorrect. -- Always update the README when you upload a new file. \ No newline at end of file +- Always update the README when you upload a new file. +- Check the other PRs for changes required, else approve them. +- Wait till the PR is checked and merged. +- Be kind. diff --git a/Regex/README.md b/Regex/README.md index f84685fc..9ed6c786 100644 --- a/Regex/README.md +++ b/Regex/README.md @@ -1 +1,116 @@ -# Regex \ No newline at end of file +# Regex + +# Definition: +A regex is a string of text that allows you to create patterns that help match, locate, and manage text. + +# Use Of Regex: +Pattern matching + +# How To Write Regex: + +### Repeaters : * , + and { } : +These symbols act as repeaters and tell the computer that the preceding character is to be used for more than just one time. + +### The asterisk symbol ( * ): +It tells the computer to match the preceding character (or set of characters) for 0 or more times (upto infinite). +Example : The regular expression ab*c will give ac, abc, abbc, +abbbc….ans so on + +### The Plus symbol ( + ): +It tells the computer to repeat the preceding character (or set of characters) for atleast one or more times(upto infinite). +Example : The regular expression ab+c will give abc, abbc, +abbc, … and so on. + +### The curly braces {…}: +It tells the computer to repeat the preceding character (or set of characters) for as many times as the value inside this bracket. +Example : {2} means that the preceding character is to be repeated 2 +times, {min,} means the preceding character is matches min or more +times. {min,max} means that the preceding character is repeated at +least min & at most max times. + +### Wildcard – ( . ) +The dot symbol can take place of any other symbol, that is why it +is called the wildcard character. +Example : +The Regular expression .* will tell the computer that any character +can be used any number of times. + +### Optional character – ( ? ) +This symbol tells the computer that the preceding character may +or may not be present in the string to be matched. +Example : +We may write the format for document file as – “docx?” +The ‘?’ tells the computer that x may or may not be +present in the name of file format. + +### The caret ( ^ ) symbol: Setting position for match :tells the computer that the match must start at the beginning of the string or line. +Example : ^\d{3} will match with patterns like "901" in "901-333-". + +### The dollar ( $ ) symbol +It tells the computer that the match must occur at the end of the string or before \n at the end of the line or string. +Example : -\d{3}$ will match with patterns like "-333" in "-901-333". + +### Character Classes +A character class matches any one of a set of characters. It is used to match the most basic element of a language like a letter, a digit, space, a symbol etc. +/s : matches any whitespace characters such as space and tab +/S : matches any non-whitespace characters +/d : matches any digit character +/D : matches any non-digit characters +/w : matches any word character (basically alpha-numeric) +/W : matches any non-word character +/b : matches any word boundary (this would include spaces, dashes, commas, semi-colons, etc) + +### [set_of_characters]: +Matches any single character in set_of_characters. By default, the match is case-sensitive. + +Example : [abc] will match characters a,b and c in any string. + +### [^set_of_characters] – Negation: +Matches any single character that is not in set_of_characters. By default, the match is case sensitive. + +Example : [^abc] will match any character except a,b,c . +[first-last] – Character range: Matches any single character in the range from first to last. + +Example : [a-zA-z] will match any character from a to z or A to Z. + +### The Escape Symbol : \ +If you want to match for the actual ‘+’, ‘.’ etc characters, add a backslash( \ ) before that character. This will tell the computer to treat the following character as a search character and consider it for matching pattern. + +Example : \d+[\+-x\*]\d+ will match patterns like "2+2" +and "3*9" in "(2+2) * 3*9". + +### Grouping Characters ( ) +A set of different symbols of a regular expression can be grouped together to act as a single unit and behave as a block, for this, you need to wrap the regular expression in the parenthesis( ). + +Example : ([A-Z]\w+) contains two different elements of the regular +expression combined together. This expression will match any pattern +containing uppercase letter followed by any character. + +### Vertical Bar ( | ) : +Matches any one element separated by the vertical bar (|) character. + +Example : th(e|is|at) will match words - the, this and that. +\number : + +### Backreference: +allows a previously matched sub-expression(expression captured or enclosed within circular brackets ) to be identified subsequently in the same regular expression. \n means that group enclosed within the n-th bracket will be repeated at current position. +Example : ([a-z])\1 will match “ee” in Geek because the character +at second position is same as character at position 1 of the match. + +### Comment : (?# comment) – +Inline comment: The comment ends at the first closing parenthesis. +Example : \bA(?#This is an inline comment)\w+\ + +# Some Common Regex: + +### Regex For Email: +^([a-zA-Z0-9_\-\.]+)@([a-zA-Z0-9_\-\.]+)\.([a-zA-Z]{2,5})$ + +### Regex for Date in the format 08 Aug 2020, 06 Jun 2020 +^((31(?!\ (Feb?|Apr?|Jun?|(Sep(?=\b)t?|Nov)(ember)?)))|((30|29)(?!\ Feb?))|(29(?=\ Feb?\ (((1[6-9]|[2-9]\d)(0[48]|[2468][048]|[13579][26])|((16|[2468][048]|[3579][26])00)))))|(0?[1-9])|1\d|2[0-8])[.\-\/\s](Jan?|Feb?|Ma(r(ch)?|y)|Apr?|Ju((ly?)|(ne?))|Aug?|Oct?|(Sep(?=\b)t?|Nov|Dec)?)[.\-\/\s]((1[6-9]|[2-9]\d)\d{2})$ + +### Regex for Date in the format 08 August 2020, 16 June 2020 +^((31(?!\ (Feb(ruary)?|Apr(il)?|June?|(Sep(?=\b)t?|Nov)(ember)?)))|((30|29)(?!\ Feb(ruary)?))|(29(?=\ Feb(ruary)?\ (((1[6-9]|[2-9]\d)(0[48]|[2468][048]|[13579][26])|((16|[2468][048]|[3579][26])00)))))|(0?[1-9])|1\d|2[0-8])[.\-\/\s](Jan(uary)?|Feb(ruary)?|Ma(r(ch)?|y)|Apr(il)?|Ju((ly?)|(ne?))|Aug(ust)?|Oct(ober)?|(Sep(?=\b)t?|Nov|Dec)(ember)?)[.\-\/\s]((1[6-9]|[2-9]\d)\d{2})$ + +### Regex for Date which do not takes 8 Aug 2020 but 08 Aug 2020 +^((31(?!\ (Feb?|Apr?|Jun?|(Sep(?=\b)t?|Nov)(ember)?)))|((30|29)(?!\ Feb?))|(29(?=\ Feb?\ (((1[6-9]|[2-9]\d)(0[48]|[2468][048]|[13579][26])|((16|[2468][048]|[3579][26])00)))))|(0[1-9])|1\d|2[0-8])[.\-\/\s](Jan?|Feb?|Ma(r(ch)?|y)|Apr?|Ju((ly?)|(ne?))|Aug?|Oct?|(Sep(?=\b)t?|Nov|Dec)?)[.\-\/\s]((1[6-9]|[2-9]\d)\d{2})$ diff --git a/julia/README.md b/julia/README.md new file mode 100644 index 00000000..8d7f6e75 --- /dev/null +++ b/julia/README.md @@ -0,0 +1,3 @@ +### Solved problems in Julia + +- [Staircase problem](https://www.hackerrank.com/challenges/staircase/problem) \ No newline at end of file diff --git a/julia/staircase.jl b/julia/staircase.jl new file mode 100644 index 00000000..6355a5bf --- /dev/null +++ b/julia/staircase.jl @@ -0,0 +1,37 @@ +""" +Given an integer n = 4, the output should be + + # + ## + ### +#### + +ref: https://www.hackerrank.com/challenges/staircase/problem +""" + +function staircase(size = nothing,builder = nothing, pad_char = nothing) + """ + The method takes the size, builder and padding character of a staircase + and prints the result to console + if size is not provided, size is defaulted to 6 + if builder is not provided, defaulted to # + if pad_char is not provided, defaulted to ' ', white space + """ + + # check if values are not provided and assign appropriate defaults + size = (size === nothing) ? 6 : size + builder = (builder === nothing) ? "#" : builder + pad_char = (pad_char === nothing) ? " " : pad_char + + # Julia is 1-index based, this means from 1 to size + # for example, for size = 6, we get 1,2,3,4,5,6 + for loop in 1:size + # print line to console, pad white spaces and then builder + println(join([pad_char for lp in 1:(size-loop)]),join([builder for rl in 1:loop])) + end +end + +# printing an empty line +println() # printing an empty line at the end, to look nice +staircase(9) +println() # printing an empty line at the end, to look nice \ No newline at end of file