diff --git a/Algorithms/Bit Manipulation/FlippingBits.m b/Algorithms/Bit Manipulation/FlippingBits.m new file mode 100644 index 0000000..523b3fd --- /dev/null +++ b/Algorithms/Bit Manipulation/FlippingBits.m @@ -0,0 +1,33 @@ +/* Flipping Bits + +You will be given a list of 32 bits unsigned integers. You are required to output the list of the unsigned integers you get by flipping bits in its binary representation (i.e. unset bits must be set, and set bits must be unset). + +Input Format + +The first line of the input contains the list size T, which is followed by T lines, each line having an integer from the list. + +Constraints + +1≤T≤100 +0≤integer<2^32 +Output Format + +Output one line per element from the list with the requested result. +*/ + +#import + + +int main (int argc, const char * argv[]) { + NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; + int numInput; + scanf("%d", &numInput); + for(int i=0;i alStr = new ArrayList(Arrays.asList(sc.nextLine().split(" "))); + String answer=""; + int pos = 0; + while(alStr.size()>1){ + answer = alStr.get(0); + alStr.remove(0); + if(!alStr.contains(answer)){ + break; + }else{ + alStr.remove(answer); + } + pos++; + + } + System.out.println(alStr.size()!=1?answer:alStr.get(0)); + } +} \ No newline at end of file diff --git a/Algorithms/Bit Manipulation/MaximizingXOR.m b/Algorithms/Bit Manipulation/MaximizingXOR.m new file mode 100644 index 0000000..2061b6d --- /dev/null +++ b/Algorithms/Bit Manipulation/MaximizingXOR.m @@ -0,0 +1,41 @@ +/* Maximizing XOR +Given two integers, L and R, find the maximal value of A xor B, where A and B satisfy the following condition: + +L≤A≤B≤R +Input Format + +The input contains two lines; L is present in the first line and R in the second line. + +Constraints +1≤L≤R≤10^3 + +Output Format + +The maximal value as mentioned in the problem statement. +*/ + +//Enter your code here. Read input from STDIN. Print output to STDOUT +#import + +int calculateMaximizingOR(int L,int R) +{ + int maxVal = 0; + for(int i=L;i<=R;i++){ + for(int j=i;j<=R;j++){ + if((i^j)>maxVal){ + maxVal=i^j; + } + } + } + return maxVal; +} + +int main (int argc, const char * argv[]) { + NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; + int L,R; + scanf("%d %d", &L,&R); + printf("%d\n",calculateMaximizingOR(L,R)); + + [pool drain]; + return 0; +} \ No newline at end of file diff --git a/Algorithms/Greedy/Flowers.java b/Algorithms/Greedy/Flowers.java new file mode 100644 index 0000000..50400b5 --- /dev/null +++ b/Algorithms/Greedy/Flowers.java @@ -0,0 +1,46 @@ +/* Flowers +You and your K-1 friends want to buy N flowers. Flower number i has cost ci. Unfortunately the seller does not want just one customer to buy a lot of flowers, so he tries to change the price of flowers for customers who have already bought some flowers. More precisely, if a customer has already bought x flowers, he should pay (x+1)*ci dollars to buy flower number i. +You and your K-1 friends want to buy all N flowers in such a way that you spend the least amount of money. You can buy the flowers in any order. + +Input: + +The first line of input contains two integers N and K (K <= N). The next line contains N space separated positive integers c1,c2,...,cN. + +Output: + +Print the minimum amount of money you (and your friends) have to pay in order to buy all N flowers. +*/ + + +import java.io.*; +import java.util.*; + +public class Flowers { + + public static void main(String[] args) { + /* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */ + Scanner sc = new Scanner(System.in); + ArrayList flowerPriceList = new ArrayList(); + int numFlowers = sc.nextInt(); + int numFriends = sc.nextInt(); + for(int i = 0; icurrentToy+4){ + count++; + currentToy=numArray[i]; + } + } + System.out.println(count); + } +} \ No newline at end of file diff --git a/Algorithms/Greedy/TwoArrays.java b/Algorithms/Greedy/TwoArrays.java new file mode 100644 index 0000000..4acf2d7 --- /dev/null +++ b/Algorithms/Greedy/TwoArrays.java @@ -0,0 +1,83 @@ +/* +Two Arrays + +You are given two integer arrays, A and B, each containing N integers. The size of the array is +less than or equal to 1000. You are free to permute the order of the elements in the arrays. + +Now here's the real question: Is there an permutation A', B' possible of A and B, such that, A'i+B'i ≥ K +for all i, where A'i denotes the ith element in the array A' and B'i denotes ith element in the array B'. + + +Input Format +The first line contains an integer, T, the number of test-cases. T test cases follow. Each test case has the following format: + +The first line contains two integers, N and K. The second line contains N space separated integers, d +enoting array A. The third line describes array B in a same format. + +Output Format +For each test case, if such an arrangement exists, output "YES", otherwise "NO" (without quotes). + + +Constraints +1 <= T <= 10 +1 <= N <= 1000 +1 <= K <= 109 +0 <= Ai, Bi ≤ 109 + + +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 +*/ + +import java.io.*; +import java.util.*; +import java.text.*; +import java.math.*; +import java.util.regex.*; + +public class TwoArrays { + + public static void main(String[] args) { + + Scanner sc = new Scanner(System.in); + int numTestCases = Integer.parseInt(sc.nextLine()); + for(int i = 0;i0) +indicate the student arrived ai minutes late. + +Output Format + +For each test case, print the word YES if the class is canceled or NO if it is not. + +Constraints + +1≤T≤10 +1≤N≤1000 +1≤K≤N +−100≤ai≤100,where i∈[1,N] +Note +If a student arrives exactly on time (ai=0), the student is considered to have entered before the class started. + +Sample Input + +2 +4 3 +-1 -3 4 2 +4 2 +0 -1 2 1 + +Sample Output + +YES +NO +*/ + +import java.io.*; +import java.util.*; +import java.text.*; +import java.math.*; +import java.util.regex.*; + +public class AngryProfessor { + + public static void main(String[] args) { + + Scanner sc = new Scanner(System.in); + int numCases=Integer.parseInt(sc.nextLine()); + for(int i = 0;i=atLeastNumStudents?"NO":"YES"); + } + } +} \ No newline at end of file diff --git a/Algorithms/Implementation/AppleAndOrange.java b/Algorithms/Implementation/AppleAndOrange.java new file mode 100644 index 0000000..b7e3d69 --- /dev/null +++ b/Algorithms/Implementation/AppleAndOrange.java @@ -0,0 +1,51 @@ +/* + +Apple and Orange +https://www.hackerrank.com/challenges/apple-and-orange + +*/ + + +import java.io.*; +import java.util.*; +import java.text.*; +import java.math.*; +import java.util.regex.*; + +public class Solution { + + public static boolean didHitHouse(int s, int t, int treePos, int d) + { + int fallenFruitPos = treePos + d; + return s <= fallenFruitPos && fallenFruitPos <= t; + } + + public static void main(String[] args) { + Scanner in = new Scanner(System.in); + int s = in.nextInt(); + int t = in.nextInt(); + int a = in.nextInt(); + int b = in.nextInt(); + int m = in.nextInt(); + int n = in.nextInt(); + + int hitCount = 0; + for(int apple_i=0; apple_i < m; apple_i++){ + int distance = in.nextInt(); + if (distance > 0) { + if (didHitHouse(s, t, a, distance)) hitCount++; + } + } + System.out.println(hitCount); + + hitCount = 0; + for(int orange_i=0; orange_i < n; orange_i++){ + int distance = in.nextInt(); + if (distance < 0) { + if (didHitHouse(s, t, b, distance)) hitCount++; + } + } + System.out.println(hitCount); + + } +} \ No newline at end of file diff --git a/Algorithms/Implementation/BeautifulDaysAtTheMovies.java b/Algorithms/Implementation/BeautifulDaysAtTheMovies.java new file mode 100644 index 0000000..e89b228 --- /dev/null +++ b/Algorithms/Implementation/BeautifulDaysAtTheMovies.java @@ -0,0 +1,44 @@ +/* Beautiful Days at the Movies + +https://www.hackerrank.com/challenges/beautiful-days-at-the-movies + +*/ + +import java.io.*; +import java.util.*; +import java.text.*; +import java.math.*; +import java.util.regex.*; + +public class BeautifulDaysAtTheMovies { + + public static int reverseNum(int num) + { + String numStr = "" + num; + String reverseNumStr = ""; + + for(int i = numStr.length() - 1;i >= 0;i--){ + reverseNumStr = reverseNumStr + numStr.charAt(i); + } + + return Integer.parseInt(reverseNumStr); + } + + public static boolean isNumBeautiful(int num, int k) + { + return Math.abs(num - reverseNum(num)) % k == 0; + } + + public static void main(String[] args) + { + Scanner sc = new Scanner(System.in); + int numOne = sc.nextInt(); + int numTwo = sc.nextInt(); + int k = sc.nextInt(); + int total = 0; + for(int i = numOne; i <= numTwo; i++){ + if(isNumBeautiful(i,k)) total++; + } + System.out.println(total); + } +} \ No newline at end of file diff --git a/Algorithms/Implementation/BonAppetit.java b/Algorithms/Implementation/BonAppetit.java new file mode 100644 index 0000000..77e18ee --- /dev/null +++ b/Algorithms/Implementation/BonAppetit.java @@ -0,0 +1,41 @@ +/* +Bon Appétit +https://www.hackerrank.com/challenges/bon-appetit +*/ +import java.io.*; +import java.util.*; +import java.text.*; +import java.math.*; +import java.util.regex.*; + +public class BonAppetit { + + public static void main(String[] args) { + + Scanner sc = new Scanner(System.in); + int numItems = sc.nextInt(); + int nthItem = sc.nextInt(); + int totalSum = 0; + int[] items = new int[numItems]; + + for(int i = 0;i < numItems;i++){ + items[i] = sc.nextInt(); + totalSum += items[i]; + } + + int annasCharge = sc.nextInt(); + if(nthItem == 0){ + if(totalSum == annasCharge){ + System.out.println("Bon Appetit"); + } else { + System.out.println("" + (annasCharge - totalSum)); + } + } else { + if(annasCharge == (totalSum - items[nthItem]) /2 ){ + System.out.println("Bon Appetit"); + }else{ + System.out.println("" + (annasCharge - (totalSum - items[nthItem])/2)); + } + } + } +} \ No newline at end of file diff --git a/Algorithms/Implementation/CavityMap.java b/Algorithms/Implementation/CavityMap.java new file mode 100644 index 0000000..74e4830 --- /dev/null +++ b/Algorithms/Implementation/CavityMap.java @@ -0,0 +1,53 @@ +/* Cavity Map +You are given a square map of size n×n. Each cell of the map has a value denoting its depth. We will call a cell of the map a cavity if and only if this cell is not on the border of the map and each cell adjacent to it has strictly smaller depth. Two cells are adjacent if they have a common side (edge). + +You need to find all the cavities on the map and depict them with the uppercase character X. + +Input Format + +The first line contains an integer, n, denoting the size of the map. Each of the following n lines contains n positive digits without spaces. Each digit (1-9) denotes the depth of the appropriate area. + +Constraints +1≤n≤100 +Output Format + +Output n lines, denoting the resulting map. Each cavity should be replaced with character X. +*/ + +import java.io.*; +import java.util.*; +import java.text.*; +import java.math.*; +import java.util.regex.*; + +public class CavityMap { + + public static void printMapWithCavities(char[][]map, int mapSize) + { + + for(int row = 1;row < mapSize-1;row++){ + for(int column = 1; column < mapSize-1;column++){ + int cellDepth = map[row][column]; + if(cellDepth>map[row][column+1] && cellDepth>map[row][column-1] && cellDepth>map[row-1][column] && cellDepth>map[row+1][column]){ + map[row][column] = 'X'; + } + } + } + for(int row = 0;row0); + return candyAte; + } +} + diff --git a/Algorithms/Implementation/CutTheSticks.java b/Algorithms/Implementation/CutTheSticks.java new file mode 100644 index 0000000..bec9e00 --- /dev/null +++ b/Algorithms/Implementation/CutTheSticks.java @@ -0,0 +1,90 @@ +/* Cut The Sticks + +You are given N sticks, where the length of each stick is a positive integer. A cut operation is performed on the sticks such that all of them are reduced by the length of the smallest stick. + +Suppose we have six sticks of the following lengths: + +5 4 4 2 2 8 +Then, in one cut operation we make a cut of length 2 from each of the six sticks. For the next cut +operation four sticks are left (of non-zero length), whose lengths are the following: + +3 2 2 6 +The above step is repeated until no sticks are left. + +Given the length of N sticks, print the number of sticks that are left before each subsequent cut operations. + +Note: For each cut operation, you have to recalcuate the length of smallest sticks (excluding zero-length sticks). + +Input Format +The first line contains a single integer N. +The next line contains N integers: a0, a1,...aN-1 separated by space, where ai represents the length of ith stick. + +Output Format +For each operation, print the number of sticks that are cut, on separate lines. + +Constraints +1 ≤ N ≤ 1000 +1 ≤ ai ≤ 1000 + +Sample Input #00 + +6 +5 4 4 2 2 8 +Sample Output #00 + +6 +4 +2 +1 +Sample Input #01 + +8 +1 2 3 4 3 3 2 1 + +Sample Output #01 + +8 +6 +4 +1 +*/ + +import java.io.*; +import java.util.*; +import java.text.*; +import java.math.*; +import java.util.regex.*; + +public class Solution { + + public static void main(String[] args) { + + Scanner sc = new Scanner(System.in); + ArrayList sticks = new ArrayList(); + int numSticks = Integer.parseInt(sc.nextLine()); + for(int i = 0;i0){ + Collections.sort(sticks); + int shortestStick = sticks.get(0); + + int pos = 0; + System.out.println(sticks.size()); + while(pos0){ + sticks.set(pos,num); + pos++; + }else{ + sticks.remove(pos); + + } + + } + + + } + } +} \ No newline at end of file diff --git a/Algorithms/Implementation/DivisibleSumPairs.java b/Algorithms/Implementation/DivisibleSumPairs.java new file mode 100644 index 0000000..b35f39f --- /dev/null +++ b/Algorithms/Implementation/DivisibleSumPairs.java @@ -0,0 +1,50 @@ +//https://www.hackerrank.com/challenges/divisible-sum-pairs + +/* + You are given an array of n integers, a0,a1,....,a(n-1), and a positive integer, k. Find and print the number of (i,j) pairs where i < j and a(i) + a(j) is evenly divisible by k. + + Input Format + + The first line contains 2 space-separated integers, n and k, respectively. + The second line contains n space-separated integers describing the respective values of a0, a1,...,a(n-1). + + Constraints + - 2 <= n <= 100 + - 1 <= k <= 100 + - 1 <= ai <= 100 + Output Format + + Print the number of (i,j) pairs where i < j and ai + aj is evenly divisible by k. + + Sample Input + + 6 3 + 1 3 2 6 1 2 + + Sample Output + + 5 + + */ + +import java.util.Scanner; + +class DivisibleSumPairs { + public static void main(String args[]) { + Scanner sc = new Scanner(System.in); + int n = sc.nextInt(); + int k = sc.nextInt(); + int a[] = new int[n]; + for (int i = 0; i < n; i++) { + a[i] = sc.nextInt(); + } + int cnt = 0; + for (int i = 0; i < n - 1; i++) { + for (int j = i + 1; j < n; j++) { + if ((a[i] + a[j]) % k == 0) + cnt++; + } + } + System.out.println(cnt); + } +} diff --git a/Algorithms/Implementation/Encryption.java b/Algorithms/Implementation/Encryption.java new file mode 100644 index 0000000..6f1ed87 --- /dev/null +++ b/Algorithms/Implementation/Encryption.java @@ -0,0 +1,40 @@ +import java.io.*; +import java.util.*; +import java.text.*; +import java.math.*; +import java.util.regex.*; + +public class Encryption { + + public static void main(String[] args) { + Scanner in = new Scanner(System.in); + String s = in.nextLine(); + + int rows = (int) Math.floor(Math.sqrt(s.length())); + int columns = (int) Math.ceil(Math.sqrt(s.length())); + if(rows*columns < s.length())rows ++; + String[][] encryptArray = new String[rows][columns]; + + int r = 0; + int c = 0; + for(int i = 0; i < s.length();i++){ + encryptArray[r][c] = ""+s.charAt(i); + if(c == columns - 1){ + c = -1; + r++; + } + c++; + } + + String encryptedString = ""; + for(int k = 0;k < columns;k++){ + for(int i = 0;i < rows;i++){ + encryptedString = encryptedString + (encryptArray[i][k] != null?encryptArray[i][k]:""); + } + encryptedString +=" "; + } + + System.out.println(encryptedString); + } +} + diff --git a/Algorithms/Implementation/EqualizeTheArray.playground/Contents.swift b/Algorithms/Implementation/EqualizeTheArray.playground/Contents.swift new file mode 100644 index 0000000..93ed7a5 --- /dev/null +++ b/Algorithms/Implementation/EqualizeTheArray.playground/Contents.swift @@ -0,0 +1,51 @@ +/* + +Equalize the Array + +https://www.hackerrank.com/challenges/equality-in-a-array + + */ +import Foundation + +public func getLine() -> String { + var buf = String() + var ch = getchar() + // 10 is ascii code for newline + while ch != EOF && ch != 10 { + buf = buf + "\(ch)" + ch = getchar() + } + return buf +} + +public func readLn() -> [String] { + return getLine().components(separatedBy: CharacterSet.whitespaces) +} + +public func readLine() -> [Int] { + let words: [String] = readLn() + return words.map { Int($0)! } +} + +let numIntegers: [Int] = readLine() +let input: [Int] = readLine() + +var numDictionary = [Int : Int]() + +var maxNumOccurrences = 1 + +var pos = 0 + +for num in input { + if let numPos = numDictionary[num] { + numDictionary[num]! += 1 + if numDictionary[num]! > maxNumOccurrences { + maxNumOccurrences = numDictionary[num]! + } + } else { + numDictionary[num] = 1 + } + pos+=1 +} + +print("\(input.count - maxNumOccurrences)") \ No newline at end of file diff --git a/Algorithms/Implementation/EqualizeTheArray.playground/contents.xcplayground b/Algorithms/Implementation/EqualizeTheArray.playground/contents.xcplayground new file mode 100644 index 0000000..63b6dd8 --- /dev/null +++ b/Algorithms/Implementation/EqualizeTheArray.playground/contents.xcplayground @@ -0,0 +1,4 @@ + + + + \ No newline at end of file diff --git a/Algorithms/Implementation/EqualizeTheArray.playground/playground.xcworkspace/contents.xcworkspacedata b/Algorithms/Implementation/EqualizeTheArray.playground/playground.xcworkspace/contents.xcworkspacedata new file mode 100644 index 0000000..919434a --- /dev/null +++ b/Algorithms/Implementation/EqualizeTheArray.playground/playground.xcworkspace/contents.xcworkspacedata @@ -0,0 +1,7 @@ + + + + + diff --git a/Algorithms/Implementation/ExtraLongFactorial.java b/Algorithms/Implementation/ExtraLongFactorial.java new file mode 100644 index 0000000..85d19fd --- /dev/null +++ b/Algorithms/Implementation/ExtraLongFactorial.java @@ -0,0 +1,41 @@ +/* Extra Long Factorials + +You are given an integer N. Print the factorial of this number. + +N!=N×(N−1)×(N−2)×⋯×3×2×1 +Input +Input consists of a single integer N, where 1≤N≤100. + +Output +Print the factorial of N. + +Example +For an input of 25, you would print 15511210043330985984000000. + +Note: Factorials of N>20 can't be stored even in a 64−bit long long variable. +Big integers must be used for such calculations. Languages like Java, Python, Ruby etc. can handle +big integers, but we need to write additional code in C/C++ to handle huge values. + +We recommend solving this challenge using BigIntegers. + + +*/ + +import java.io.*; +import java.util.*; +import java.math.BigInteger; + +public class ExtraLongFactorial { + + public static void main(String[] args) { + + Scanner sc = new Scanner(System.in); + int factorialNum = sc.nextInt(); + BigInteger bigInt = new BigInteger(""+factorialNum); + for(int i = 1;i String { + var buf = String() + var ch = getchar() + // 10 is ascii code for newline + while ch != EOF && ch != 10 { + buf = buf + "\(ch)" + ch = getchar() + } + return buf +} + +public func readLn() -> [String] { + return getLine().components(separatedBy: CharacterSet.whitespaces) +} + +public func readLine() -> [Int] { + let words: [String] = readLn() + return words.map { Int($0)! } +} + +let numSubjects: [Int] = readLine() +var numBreads: [Int] = readLine() + +var sum = 0 +var count = 0 + +numBreads.map {sum+=$0} + +if(sum % 2 != 0) { + print("NO") +} else { + for num in 0.. + + + \ No newline at end of file diff --git a/Algorithms/Implementation/FairRations.playground/playground.xcworkspace/contents.xcworkspacedata b/Algorithms/Implementation/FairRations.playground/playground.xcworkspace/contents.xcworkspacedata new file mode 100644 index 0000000..919434a --- /dev/null +++ b/Algorithms/Implementation/FairRations.playground/playground.xcworkspace/contents.xcworkspacedata @@ -0,0 +1,7 @@ + + + + + diff --git a/Algorithms/Implementation/FindDigits.java b/Algorithms/Implementation/FindDigits.java new file mode 100644 index 0000000..75fe78c --- /dev/null +++ b/Algorithms/Implementation/FindDigits.java @@ -0,0 +1,60 @@ +/* Find Digits +You are given an integer N. Find the digits in this number that exactly divide N (division that leaves 0 as remainder) and display their count. For N=24, there are 2 digits (2 & 4). Both of these digits exactly divide 24. So our answer is 2. + +Note + +If the same number is repeated twice at different positions, it should be counted twice, e.g., For N=122, 2 divides 122 exactly and occurs at ones' and tens' position. So for this case, our answer is 3. +Division by 0 is undefined. +Input Format + +The first line contains T (the number of test cases), followed by T lines (each containing an integer N). + +Constraints +1≤T≤15 +0 String { + var buf = String() + var ch = getchar() + // 10 is ascii code for newline + while ch != EOF && ch != 10 { + buf = buf + "\(ch)" + ch = getchar() + } + return buf +} + +public func readLn() -> [String] { + return getLine().components(separatedBy: CharacterSet.whitespaces) +} + +public func readLine() -> [Int] { + let words: [String] = readLn() + return words.map { Int($0)! } +} + +let info: [Int] = readLine() +var stationLocations: [Int] = readLine() + +var previousStationLocation = -1 + +var maxDistance = 0 + +var pos = 0 + +if info[0] == info[1] { + print(0) +} else { + stationLocations = stationLocations.sorted() + for station in stationLocations { + if previousStationLocation == -1 { + previousStationLocation = station + maxDistance = station + } else { + let distance = (station - previousStationLocation) / 2 + maxDistance = max(distance, maxDistance) + previousStationLocation = station + } + } + + print(max(maxDistance,(info[0] - previousStationLocation - 1))) +} \ No newline at end of file diff --git a/Algorithms/Implementation/FlatlandsSpaceStations.playground/contents.xcplayground b/Algorithms/Implementation/FlatlandsSpaceStations.playground/contents.xcplayground new file mode 100644 index 0000000..63b6dd8 --- /dev/null +++ b/Algorithms/Implementation/FlatlandsSpaceStations.playground/contents.xcplayground @@ -0,0 +1,4 @@ + + + + \ No newline at end of file diff --git a/Algorithms/Implementation/FlatlandsSpaceStations.playground/playground.xcworkspace/contents.xcworkspacedata b/Algorithms/Implementation/FlatlandsSpaceStations.playground/playground.xcworkspace/contents.xcworkspacedata new file mode 100644 index 0000000..919434a --- /dev/null +++ b/Algorithms/Implementation/FlatlandsSpaceStations.playground/playground.xcworkspace/contents.xcworkspacedata @@ -0,0 +1,7 @@ + + + + + diff --git a/Algorithms/Implementation/GradingStudents.java b/Algorithms/Implementation/GradingStudents.java new file mode 100644 index 0000000..fcbbb7d --- /dev/null +++ b/Algorithms/Implementation/GradingStudents.java @@ -0,0 +1,53 @@ +import java.io.*; +import java.math.*; +import java.text.*; +import java.util.*; +import java.util.regex.*; + +public class Solution { + + /* + * Complete the gradingStudents function below. + */ + static int[] gradingStudents(int[] grades) { + for(int i = 0; i < grades.length; i++) { + for(int j = 40; j <= 100; j += 5) { + if(j > grades[i]) { + if(j - grades[i] <= 2) { + grades[i] = j; + } + } + } + } + return grades; + } + + private static final Scanner scan = new Scanner(System.in); + + public static void main(String[] args) throws IOException { + BufferedWriter bw = new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH"))); + + int n = Integer.parseInt(scan.nextLine().trim()); + + int[] grades = new int[n]; + + for (int gradesItr = 0; gradesItr < n; gradesItr++) { + int gradesItem = Integer.parseInt(scan.nextLine().trim()); + grades[gradesItr] = gradesItem; + } + + int[] result = gradingStudents(grades); + + for (int resultItr = 0; resultItr < result.length; resultItr++) { + bw.write(String.valueOf(result[resultItr])); + + if (resultItr != result.length - 1) { + bw.write("\n"); + } + } + + bw.newLine(); + + bw.close(); + } +} diff --git a/Algorithms/Implementation/JumpingOnTheClouds.java b/Algorithms/Implementation/JumpingOnTheClouds.java new file mode 100644 index 0000000..fd0325f --- /dev/null +++ b/Algorithms/Implementation/JumpingOnTheClouds.java @@ -0,0 +1,39 @@ +/* +Jumping on the Clouds +https://www.hackerrank.com/challenges/jumping-on-the-clouds +*/ + +import java.io.*; +import java.util.*; +import java.text.*; +import java.math.*; +import java.util.regex.*; + +public class Solution { + + public static int minJumps(int[] cloudsArray) + { + int currentPos = 0; + int jumpsCount = 0; + + while (currentPos < cloudsArray.length-1){ + if(currentPos + 2 < cloudsArray.length && cloudsArray[currentPos + 2] == 0){ + currentPos+=2; + jumpsCount++; + } else { + currentPos++; + jumpsCount++; + } + } + return jumpsCount; + } + public static void main(String[] args) { + Scanner in = new Scanner(System.in); + int n = in.nextInt(); + int c[] = new int[n]; + for(int c_i=0; c_i < n; c_i++){ + c[c_i] = in.nextInt(); + } + System.out.println(minJumps(c)); + } +} \ No newline at end of file diff --git a/Algorithms/Implementation/JumpingOnTheCloudsRevisited.java b/Algorithms/Implementation/JumpingOnTheCloudsRevisited.java new file mode 100644 index 0000000..0895620 --- /dev/null +++ b/Algorithms/Implementation/JumpingOnTheCloudsRevisited.java @@ -0,0 +1,38 @@ +/* +Jumping On The Clouds Revisited +https://www.hackerrank.com/challenges/jumping-on-the-clouds-revisited +*/ + + +import java.io.*; +import java.util.*; +import java.text.*; +import java.math.*; +import java.util.regex.*; + +public class JumpingOnTheCloudsRevisited { + + public static int energyLeft(int[] cloudsArray, int jumpDistance) + { + int currentPos = 0; + int energyLeft = 100; + + do{ + currentPos = (currentPos + jumpDistance) % cloudsArray.length; + energyLeft--; + if(cloudsArray[currentPos] == 1) energyLeft-=2; + }while (currentPos != 0); + + return energyLeft; + } + public static void main(String[] args) { + Scanner in = new Scanner(System.in); + int n = in.nextInt(); + int k = in.nextInt(); + int c[] = new int[n]; + for(int c_i=0; c_i < n; c_i++){ + c[c_i] = in.nextInt(); + } + System.out.println(energyLeft(c,k)); + } +} \ No newline at end of file diff --git a/Algorithms/Implementation/Kangaroo.java b/Algorithms/Implementation/Kangaroo.java new file mode 100644 index 0000000..d1bca73 --- /dev/null +++ b/Algorithms/Implementation/Kangaroo.java @@ -0,0 +1,44 @@ +/* +Kangaroo +https://www.hackerrank.com/challenges/kangaroo +*/ + + +import java.io.*; +import java.util.*; +import java.text.*; +import java.math.*; +import java.util.regex.*; + +public class Kangaroo { + + public static String willTheyMeat(int firstPos, int firstDistance, int secondPos, int secondDistance) + { + if (firstPos == secondPos) return "YES"; + + while(firstPos < secondPos){ + firstPos+=firstDistance; + secondPos+=secondDistance; + if(firstPos == secondPos) return "YES"; + } + + return "NO"; + } + + public static void main(String[] args) { + Scanner in = new Scanner(System.in); + int x1 = in.nextInt(); + int v1 = in.nextInt(); + int x2 = in.nextInt(); + int v2 = in.nextInt(); + + if(x1 <= x2 && v1 >= v2){ + System.out.println(willTheyMeat(x1,v1,x2,v2)); + } else if (x2 <= x1 && v2 >= v1){ + System.out.println(willTheyMeat(x2,v2,x1,v1)); + } else { + System.out.println("NO"); + } + + } +} \ No newline at end of file diff --git a/Algorithms/Implementation/LibraryFine.java b/Algorithms/Implementation/LibraryFine.java new file mode 100644 index 0000000..27d0689 --- /dev/null +++ b/Algorithms/Implementation/LibraryFine.java @@ -0,0 +1,52 @@ +/* Library Fine + +The Head Librarian at a library wants you to create a program that calculates the fine for returning a +book after the return date. You are given the actual and the expected return dates. Calculate the fine as follows: + +If the book is returned on or before the expected return date, no fine will be charged. In other words, the fine is 0. +If the book is returned in the same calendar month as the expected return date, the fine = 15 Hackos × the number of late days. +If the book is not returned in the same calendar month but in the same calendar year as the expected return date, +the fine = 500 Hackos × the number of late months. +If the book is not returned in the same calendar year, the fine is fixed at 10000 Hackos. +Input +You are given the actual and the expected return dates in D M Y format on two separate lines. The first line contains +the D M Y values for the actual return date and the next line contains the D M Y values for the expected return date. + Here's a sample: + +9 6 2015 +6 6 2015 +Constraints: +1≤D≤31 +1≤M≤12 +1≤Y≤3000 +The given date is a valid date on a Gregorian calendar. + +Output +Print a single value representing the fine. +The sample output for the above input would be 45. +Since the actual return date is 3 days later than expected, the fine is calculated as 15×3=45 Hackos. +*/ + +import java.io.*; +import java.util.*; + +public class LibraryFine { + + public static void main(String[] args) { + + int fine = 0; + Scanner sc = new Scanner(System.in); + String[] returnedDay = sc.nextLine().split(" "); + String[] returnDay = sc.nextLine().split(" "); + if(Integer.parseInt(returnDay[2]) numProblemsCurrentChapter){ + numProblemsInCurrentPage = numProblemsCurrentChapter - ((j-1) * numProblemsPerPage); + }else{ + numProblemsInCurrentPage = numProblemsPerPage; + } + + if(currentNumProblem >= j && (currentNumProblem+numProblemsInCurrentPage) <= j){ + numSpecialProblems++; + } + currentNumProblem+=numProblemsPerPage; + + } + + } + System.out.println(numSpecialProblems); + } +} \ No newline at end of file diff --git a/Algorithms/Implementation/MatrixLayerRotation.java b/Algorithms/Implementation/MatrixLayerRotation.java new file mode 100644 index 0000000..db02dd2 --- /dev/null +++ b/Algorithms/Implementation/MatrixLayerRotation.java @@ -0,0 +1,204 @@ +/* + * You are given a 2D matrix, a, of dimension MxN and a positive integer R. You have to rotate the matrix R times and print the resultant matrix. Rotation should be in anti-clockwise direction. + * Rotation of a 4x5 matrix is represented by the following figure. Note that in one rotation, you have to shift elements + * It is guaranteed that the minimum of M and N will be even. + +Input Format +First line contains three space separated integers, M, N and R, where M is the number of rows, N is number of columns in matrix, and R is the number of times the matrix has to be rotated. +Then M lines follow, where each line contains N space separated positive integers. These M lines represent the matrix. + +Constraints +2 <= M, N <= 300 +1 <= R <= 109 +min(M, N) % 2 == 0 +1 <= aij <= 10^8, where i belongs to [1..M] & j belongs to [1..N] + +Output Format +Print the rotated matrix. + +Sample Input #00 + +4 4 1 +1 2 3 4 +5 6 7 8 +9 10 11 12 +13 14 15 16 + +Sample Output #00 + +2 3 4 8 +1 7 11 12 +5 6 10 16 +9 13 14 15 + +Sample Input #01 + +4 4 2 +1 2 3 4 +5 6 7 8 +9 10 11 12 +13 14 15 16 + +Sample Output #01 + +3 4 8 12 +2 11 10 16 +1 7 6 15 +5 9 13 14 + +Sample Input #02 + +5 4 7 +1 2 3 4 +7 8 9 10 +13 14 15 16 +19 20 21 22 +25 26 27 28 + +Sample Output #02 + +28 27 26 25 +22 9 15 19 +16 8 21 13 +10 14 20 7 +4 3 2 1 + +Sample Input #03 + +2 2 3 +1 1 +1 1 + +Sample Output #03 + +1 1 +1 1 + +Explanation +Sample Case #00: Here is an illustration of what happens when the matrix is rotated once. + + 1 2 3 4 2 3 4 8 + 5 6 7 8 1 7 11 12 + 9 10 11 12 -> 5 6 10 16 +13 14 15 16 9 13 14 15 + +Sample Case #01: Here is what happens when to the matrix after two rotations. + + 1 2 3 4 2 3 4 8 3 4 8 12 + 5 6 7 8 1 7 11 12 2 11 10 16 + 9 10 11 12 -> 5 6 10 16 -> 1 7 6 15 +13 14 15 16 9 13 14 15 5 9 13 14 + +Sample Case #02: Following are the intermediate states. + +1 2 3 4 2 3 4 10 3 4 10 16 4 10 16 22 +7 8 9 10 1 9 15 16 2 15 21 22 3 21 20 28 +13 14 15 16 -> 7 8 21 22 -> 1 9 20 28 -> 2 15 14 27 -> +19 20 21 22 13 14 20 28 7 8 14 27 1 9 8 26 +25 26 27 28 19 25 26 27 13 19 25 26 7 13 19 25 + + + +10 16 22 28 16 22 28 27 22 28 27 26 28 27 26 25 + 4 20 14 27 10 14 8 26 16 8 9 25 22 9 15 19 + 3 21 8 26 -> 4 20 9 25 -> 10 14 15 19 -> 16 8 21 13 + 2 15 9 25 3 21 15 19 4 20 21 13 10 14 20 7 + 1 7 13 19 2 1 7 13 3 2 1 7 4 3 2 1 + +Sample Case #03: As all elements are same, any rotation will reflect the same matrix. + */ + +/* + * Solution explanation: + * Steps to solve the problem: + * -Input the values. + * -Convert layers into queue. + * -Rotate according to input times. + * -Convert queue to layers. + * -Print the matrix. + */ + +import java.io.IOException; +import java.util.LinkedList; +import java.util.Queue; +import java.util.Scanner; + +class MatrixLayerRotation { + + static int[][] matrix; + static int R; + static int layer; + + public static void Rotate(int row, int col) { + Queue queue = new LinkedList(); + //Convert into queue + for (int i = 0 + layer; i < col - 1 - layer; i++) { + queue.add(matrix[0 + layer][i]); + } + for (int i = 0 + layer; i < row - 1 - layer; i++) { + queue.add(matrix[i][col - 1 - layer]); + } + for (int i = col - 1 - layer; i > 0 + layer; i--) { + queue.add(matrix[row - 1 - layer][i]); + } + for (int i = row - 1 - layer; i > 0 + layer; i--) { + queue.add(matrix[i][0 + layer]); + } + int redo = R; + + if ((2 * (row - layer * 2) + 2 * (col - layer * 2) - 4) > 0) { + redo = R % (2 * (row - layer * 2) + 2 * (col - layer * 2) - 4); + } + int t; + for (int i = 0; i < redo; i++) { + t = queue.poll(); + queue.add(t); + } + + // putting black into matrix + for (int i = 0 + layer; i < col - 1 - layer; i++) { + matrix[0 + layer][i] = queue.poll(); + } + for (int i = 0 + layer; i < row - 1 - layer; i++) { + matrix[i][col - 1 - layer] = queue.poll(); + } + for (int i = col - 1 - layer; i > 0 + layer; i--) { + matrix[row - 1 - layer][i] = queue.poll(); + } + for (int i = row - 1 - layer; i > 0 + layer; i--) { + matrix[i][0 + layer] = queue.poll(); + } + if (layer < col / 2 - 1 && layer < row / 2 - 1) { + layer++; + Rotate(row, col); + } + } + + public static void main(String[] args) throws IOException { + Scanner in = new Scanner(System.in); + layer = 0; + int M = in.nextInt(); + int N = in.nextInt(); + R = in.nextInt(); + matrix = new int[M][N]; + + for (int y = 0; y < M; y++) { + for (int x = 0; x < N; x++) { + matrix[y][x] = in.nextInt(); + } + } + + Rotate(M, N); + printMatrix(M, N); + } + + // To print the matrix + public static void printMatrix(int row, int col) { + for (int i = 0; i < row; i++) { + for (int j = 0; j < col; j++) { + System.out.print(matrix[i][j] + " "); + } + System.out.println(); + } + } +} diff --git a/Algorithms/Implementation/MiniMaxSum.java b/Algorithms/Implementation/MiniMaxSum.java new file mode 100644 index 0000000..159936b --- /dev/null +++ b/Algorithms/Implementation/MiniMaxSum.java @@ -0,0 +1,29 @@ +/* Mini-Max Sum + +https://www.hackerrank.com/challenges/mini-max-sum + +*/ + +import java.io.*; +import java.util.*; +import java.text.*; +import java.math.*; +import java.util.regex.*; + +public class MiniMaxSum +{ + + public static void main(String[] args) { + Scanner in = new Scanner(System.in); + long total = 0; + long max = 0; + long min = Long.MAX_VALUE; + while(in.hasNext()) { + long num = in.nextLong(); + min = Math.min(min, num); + max = Math.max(max, num); + total += num; + } + System.out.println(""+ (total - max) + " " + (total - min)); + } +} \ No newline at end of file diff --git a/Algorithms/Implementation/MiniumumDistances.playground/Contents.swift b/Algorithms/Implementation/MiniumumDistances.playground/Contents.swift new file mode 100644 index 0000000..351bd82 --- /dev/null +++ b/Algorithms/Implementation/MiniumumDistances.playground/Contents.swift @@ -0,0 +1,54 @@ +/* + Minimum Distances + https://www.hackerrank.com/challenges/minimum-distances/submissions/code/31473268 + +*/ + +import Foundation + +public func getLine() -> String { + var buf = String() + var ch = getchar() + // 10 is ascii code for newline + while ch != EOF && ch != 10 { + buf = buf + "\(ch)" + ch = getchar() + } + return buf +} + +public func readLn() -> [String] { + return getLine().components(separatedBy: CharacterSet.whitespaces) +} + +public func readLine() -> [Int] { + let words: [String] = readLn() + return words.map { Int($0)! } +} + +let info: [Int] = readLine() +var stationLocations: [Int] = readLine() + +var previousStationLocation = -1 + +var maxDistance = 0 + +var pos = 0 + +if info[0] == info[1] { + print(0) +} else { + stationLocations = stationLocations.sorted() + for station in stationLocations { + if previousStationLocation == -1 { + previousStationLocation = station + maxDistance = station + } else { + let distance = (station - previousStationLocation) / 2 + maxDistance = max(distance, maxDistance) + previousStationLocation = station + } + } + + print(max(maxDistance,(info[0] - previousStationLocation - 1))) +} diff --git a/Algorithms/Implementation/MiniumumDistances.playground/contents.xcplayground b/Algorithms/Implementation/MiniumumDistances.playground/contents.xcplayground new file mode 100644 index 0000000..63b6dd8 --- /dev/null +++ b/Algorithms/Implementation/MiniumumDistances.playground/contents.xcplayground @@ -0,0 +1,4 @@ + + + + \ No newline at end of file diff --git a/Algorithms/Implementation/MiniumumDistances.playground/playground.xcworkspace/contents.xcworkspacedata b/Algorithms/Implementation/MiniumumDistances.playground/playground.xcworkspace/contents.xcworkspacedata new file mode 100644 index 0000000..919434a --- /dev/null +++ b/Algorithms/Implementation/MiniumumDistances.playground/playground.xcworkspace/contents.xcworkspacedata @@ -0,0 +1,7 @@ + + + + + diff --git a/Algorithms/Implementation/ModifiedKaprekarNumbers.java b/Algorithms/Implementation/ModifiedKaprekarNumbers.java new file mode 100644 index 0000000..3715687 --- /dev/null +++ b/Algorithms/Implementation/ModifiedKaprekarNumbers.java @@ -0,0 +1,89 @@ +/* Modified Kaprekar Numbers +https://www.hackerrank.com/challenges/kaprekar-numbers + +A modified Kaprekar number is a positive whole number with digits, such that when we split +its square into two pieces - a right hand piece with digits and a left hand piece that contains the remaining or digits, the sum of the pieces is equal to the original number (i.e. + = ). + +Note: r may have leading zeros. + +Here's an explanation from Wikipedia about the ORIGINAL Kaprekar Number (spot the difference!): +In mathematics, a Kaprekar number for a given base is a non-negative integer, the representation of whose square in that base can be split into two parts that add up to the original number again. For instance, 45 is a Kaprekar number, because 45² = 2025 and 20+25 = 45. + +The Task +You are given the two positive integers and , where is lower than . Write a program to determine +how many Kaprekar numbers are there in the range between and (both inclusive) and display them all. + +Input Format + +There will be two lines of input: , lowest value , highest value + +Constraints: + + +Output Format + +Output each Kaprekar number in the given range, space-separated on a single line. +If no Kaprekar numbers exist in the given range, print INVALID RANGE. + +Sample Input + +1 +100 +Sample Output + +1 9 45 55 99 +*/ + +import java.io.*; +import java.util.*; +import java.text.*; +import java.math.*; +import java.util.regex.*; + +public class ModifiedKaprekarNumbers { + + static boolean isKaprekarNum2(int num) + { + if(num == 1) return true; + String right = ""; + String left = ""; + String strNum = String.valueOf((long)num*num); + if(strNum.length() % 2 == 0){ + right = strNum.substring(strNum.length()/2); + int pos = 0; + while(pos < right.length()-1 && right.charAt(pos) == '0') pos++; + right = right.substring(pos); + if(right.charAt(0) == '0') right = right.substring(1); + left = strNum.substring(0,strNum.length()/2); + }else{ + right = strNum.substring((int)Math.ceil(strNum.length()/2.0)-1); + if(right.length()>0){ + int pos = 0; + while(pos < right.length() && right.charAt(pos) == '0') pos++; + right = right.substring(pos); + } + left = strNum.substring(0,(int)Math.ceil(strNum.length()/2.0)-1); + + + } + if(right.length() < 1 || left.length() < 1 || right.charAt(0) == '0') return false; + + return Integer.parseInt(right)+Integer.parseInt(left) == num; + } + + public static void main(String[] args) { + /* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */ + Scanner sc = new Scanner(System.in); + int firstNum = sc.nextInt(); + int lastNum = sc.nextInt(); + boolean isKaprekarNum = false; + for(int i = firstNum;i <= lastNum;i++){ + if(isKaprekarNum2(i)){ + System.out.print(i+" "); + isKaprekarNum = true; + } + } + System.out.println(isKaprekarNum?"":"INVALID RANGE"); + + } +} \ No newline at end of file diff --git a/Algorithms/Implementation/RepeatedString.java b/Algorithms/Implementation/RepeatedString.java new file mode 100644 index 0000000..265c42a --- /dev/null +++ b/Algorithms/Implementation/RepeatedString.java @@ -0,0 +1,42 @@ +/* +Reapeated Strings +https://www.hackerrank.com/challenges/repeated-string +*/ +import java.io.*; +import java.util.*; +import java.text.*; +import java.math.*; +import java.util.regex.*; + +public class RepeatedString { + + public static long calcNumAInString(String s, long numChar) + { + long count = 0; + + for(int i = 0;i < numChar;i++){ + if(s.charAt(i) == 'a'){ + count++; + } + } + return count; + } + + public static void main(String[] args) { + Scanner in = new Scanner(System.in); + String s = in.next(); + long n = in.nextLong(); + + + + if(s.length() > n){ + System.out.println(calcNumAInString(s,n)); + }else{ + long count = calcNumAInString(s,s.length()) * (n / s.length()); + long numCharLeft = n % s.length(); + count += calcNumAInString(s,numCharLeft); + System.out.println(count); + } + + } +} \ No newline at end of file diff --git a/Algorithms/Implementation/SaveThePrisoner.java b/Algorithms/Implementation/SaveThePrisoner.java new file mode 100644 index 0000000..2390d08 --- /dev/null +++ b/Algorithms/Implementation/SaveThePrisoner.java @@ -0,0 +1,63 @@ +//https://www.hackerrank.com/challenges/save-the-prisoner + +/* + A jail has N prisoners, and each prisoner has a unique id number, S, ranging from 1 to N. There are M sweets that must be distributed to the prisoners. + + The jailer decides the fairest way to do this is by sitting the prisoners down in a circle (ordered by ascending ), and then, starting with some random S, + distribute one candy at a time to each sequentially numbered prisoner until all M candies are distributed. + For example, if the jailer picks prisoner S = 2, then his distribution order would be (2,3,4,5....,n-1,n,1,2,3,4...) until all sweets are distributed. + + But wait—there's a catch—the very last sweet is poisoned! Can you find and print the ID number of the last prisoner to receive a sweet so he can be warned? + + Input Format + + The first line contains an integer, T, denoting the number of test cases. + The T subsequent lines each contain 3 space-separated integers: + N(the number of prisoners), M(the number of sweets), and S(the prisoner ID), respectively. + + Constraints + - 1 <= T <= 100 + - 1 <= N <= 10^9 + - 1 <= M <= 10^9 + - 1 <= S <= 10^9 + + Output Format + + For each test case, print the ID number of the prisoner who receives the poisoned sweet on a new line. + + Sample Input + + 1 + 5 2 1 + + Sample Output + + 2 + + Explanation + + There are N = 5 prisoners and M = 2 sweets. Distribution starts at ID number S = 1, so prisoner 1 gets the first sweet and prisoner 2 gets the second (last) sweet. Thus, we must warn prisoner 2 about the poison, so we print 2 on a new line. + */ +import java.util.Scanner; + +public class SaveThePrisoner { + + public static void main(String[] args) { + Scanner in = new Scanner(System.in); + int t = in.nextInt(); + while (t-- > 0) { + int n = in.nextInt(); + int m = in.nextInt(); + int s = in.nextInt(); + int last = s - 1; + while (m != 0) { + last++; + m--; + if (last > n) { + last = 1; + } + } + System.out.println(last); + } + } +} diff --git a/Algorithms/Implementation/ServiceLane.java b/Algorithms/Implementation/ServiceLane.java new file mode 100644 index 0000000..a355e75 --- /dev/null +++ b/Algorithms/Implementation/ServiceLane.java @@ -0,0 +1,69 @@ +/* Service Lane +Calvin is driving his favorite vehicle on the 101 freeway. He notices that the check engine light of his vehicle is on, and he wants to service it immediately to avoid any risks. Luckily, a service lane runs parallel to the highway. The length of the service lane is N units. The service lane consists of N segments of equal length and different width. + +Calvin can enter to and exit from any segment. Let's call the entry segment as index i and the exit segment as index j. Assume that the exit segment lies after the entry segment (i≤j) and 0≤i. Calvin has to pass through all segments from index i to index j (both inclusive). + +Paradise Highway + +Calvin has three types of vehicles - bike, car, and truck - represented by 1, 2 and 3, respectively. These numbers also denote the width of the vehicle. + +You are given an array width of length N, where width[k] represents the width of the kth segment of the service lane. It is guaranteed that while servicing he can pass through at most 1000 segments, including the entry and exit segments. + +If width[k]=1, only the bike can pass through the kth segment. +If width[k]=2, the bike and the car can pass through the kth segment. +If width[k]=3, all three vehicles can pass through the kth segment. +Given the entry and exit point of Calvin's vehicle in the service lane, output the type of the largest vehicle which can pass through the service lane (including the entry and exit segments). + +Input Format + +The first line of input contains two integers, N and T, where N denotes the length of the freeway and T the number of test cases. The next line has N space-separated integers which represent the width array. + +T test cases follow. Each test case contains two integers, i and j, where i is the index of the segment through which Calvin enters the service lane and j is the index of the lane segment through which he exits. + +Constraints +2≤N≤100000 +1≤T≤1000 +0≤i= 0; i--){ + if((i)%3 == 0 && (((n-i))%5) == 0){ + num = createDescentNumber(i,n-i); + break; + }else if ((i)%5 == 0 && (((n-i))%3) == 0){ + num = createDescentNumber(i,n-i); + } + } + return num; + } + public static void main(String[] args) { + + Scanner sc = new Scanner(System.in); + int numTestCases = Integer.parseInt(sc.nextLine()); + + for(int i = 0;i < numTestCases; i++){ + int n = sc.nextInt(); + System.out.println(descentNumber(n)); + } + } +} \ No newline at end of file diff --git a/Algorithms/Implementation/SockMerchant.playground/Contents.swift b/Algorithms/Implementation/SockMerchant.playground/Contents.swift new file mode 100644 index 0000000..93c0e46 --- /dev/null +++ b/Algorithms/Implementation/SockMerchant.playground/Contents.swift @@ -0,0 +1,29 @@ +/* +Sock Merchant +https://www.hackerrank.com/challenges/sock-merchant +*/ + +import Cocoa +import Foundation + +var socksDict = [String:Int]() + +if var input = readLine(stripNewline: true) { + let numOfSocks = Int(input) + if let socksInput = readLine(stripNewline: true){ + let socksArray = socksInput.characters.split(" ").map(String.init) + for var color in socksArray { + if socksDict[color] != nil { + socksDict[color]! += 1 + } else { + socksDict[color] = 1 + } + } + } + + var countPairs = 0 + for var count in socksDict.values { + countPairs += count / 2 + } + print(countPairs) +} \ No newline at end of file diff --git a/Algorithms/Implementation/SockMerchant.playground/contents.xcplayground b/Algorithms/Implementation/SockMerchant.playground/contents.xcplayground new file mode 100644 index 0000000..06828af --- /dev/null +++ b/Algorithms/Implementation/SockMerchant.playground/contents.xcplayground @@ -0,0 +1,4 @@ + + + + \ No newline at end of file diff --git a/Algorithms/Implementation/SockMerchant.playground/playground.xcworkspace/contents.xcworkspacedata b/Algorithms/Implementation/SockMerchant.playground/playground.xcworkspace/contents.xcworkspacedata new file mode 100644 index 0000000..919434a --- /dev/null +++ b/Algorithms/Implementation/SockMerchant.playground/playground.xcworkspace/contents.xcworkspacedata @@ -0,0 +1,7 @@ + + + + + diff --git a/Algorithms/Implementation/SockMerchant.playground/timeline.xctimeline b/Algorithms/Implementation/SockMerchant.playground/timeline.xctimeline new file mode 100644 index 0000000..c25a29f --- /dev/null +++ b/Algorithms/Implementation/SockMerchant.playground/timeline.xctimeline @@ -0,0 +1,11 @@ + + + + + + + diff --git a/Algorithms/Implementation/StrangeCounter.java b/Algorithms/Implementation/StrangeCounter.java new file mode 100644 index 0000000..c606b9f --- /dev/null +++ b/Algorithms/Implementation/StrangeCounter.java @@ -0,0 +1,14 @@ +//https://www.hackerrank.com/challenges/strange-code + +import java.util.Scanner; + +class StrangeCounter { + public static void main(String args[]) throws Exception { + Scanner in = new Scanner(System.in); + long t = in.nextLong(); + long n = 2; + while (3 * (n - 1) < t) + n = 2 * n; + System.out.println((3 * (n - 1) - t + 1)); + } +} diff --git a/Algorithms/Implementation/TaumAndBday.java b/Algorithms/Implementation/TaumAndBday.java new file mode 100644 index 0000000..64563a4 --- /dev/null +++ b/Algorithms/Implementation/TaumAndBday.java @@ -0,0 +1,47 @@ +/* Taum and B'day +Taum is planning to celebrate the birthday of his friend, Diksha. There are two types of gifts that Diksha wants from Taum: one is black and the other is white. To make her happy, Taum has to buy B number of black gifts and W number of white gifts. + +The cost of each black gift is X units. +The cost of every white gift is Y units. +The cost of converting each black gift into white gift or vice versa is Z units. +Help Taum by deducing the minimum amount he needs to spend on Diksha's gifts. + +Input Format + +The first line will contain an integer T which will be the number of test cases. +There will be T pairs of lines. The first line of each test case will contain the values of integers B and W. Another line of each test case will contain the values of integers X, Y, and Z. + +Constraints +1≤T≤10 +0≤X,Y,Z,B,W≤10^9 +*/ +import java.io.*; +import java.util.*; + +public class TaumAndBday { + + public static void main(String[] args) { + /* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */ + + Scanner sc = new Scanner(System.in); + int numCases = sc.nextInt(); + + for(int i = 0;i= 0 && grid[i - 1][j] != 'O') + grid[i - 1][j] = '|'; + if (j - 1 >= 0 && grid[i][j - 1] != 'O') + grid[i][j - 1] = '|'; + } + } + } + for (int i = 0; i < row; i++) { + for (int j = 0; j < col; j++) { + if (grid[i][j] == '|') { + grid[i][j] = '.'; + } else if (grid[i][j] == '.') { + grid[i][j] = 'O'; + } + } + } + return grid; + } + + // Print Grid + private static void printGrid(char[][] grid, int row, int col) { + for (int i = 0; i < row; i++) { + for (int j = 0; j < col; j++) { + System.out.print(grid[i][j]); + } + System.out.println(); + } + } +} diff --git a/Algorithms/Implementation/UtopianTree.m b/Algorithms/Implementation/UtopianTree.m new file mode 100644 index 0000000..2624563 --- /dev/null +++ b/Algorithms/Implementation/UtopianTree.m @@ -0,0 +1,70 @@ +/* The Utopian Tree +The Utopian Tree goes through 2 cycles of growth every year. The first growth cycle occurs during the spring, when it doubles in height. The second growth cycle occurs during the summer, when its height increases by 1 meter. + +Now, a new Utopian Tree sapling is planted at the onset of spring. Its height is 1 meter. Can you find the height of the tree after N growth cycles? + +Input Format + +The first line contains an integer, T, the number of test cases. +T lines follow; each line contains an integer, N, that denotes the number of cycles for that test case. + +Constraints +1≤T≤10 +0≤N≤60 +Output Format + +For each test case, print the height of the Utopian Tree after N cycles. Each line thus has to contain a single integer, only. + +Sample Input + +3 +0 +1 +4 +Sample Output + +1 +2 +7 +Explanation + +There are 3 test cases. + +In the first case (N=0), the initial height (1) of the tree remains unchanged. + +In the second case (when N = 1, i.e. after the 1st cycle), the tree doubles its height as it's planted at the onset of spring. + +In the third case (N=4), the tree first doubles its height (2), then grows a meter (3), then doubles again (6), before growing another meter; at the end of the 4th cycle, its height is 7 meters. +*/ + +//Enter your code here. Read input from STDIN. Print output to STDOUT +#import + +int calculateTreeSize(int treeCase) +{ + int sum = 1; + for(int i = 1;i<=treeCase;i++){ + if(i%2==0){ + sum=sum+1; + }else{ + sum=sum+sum; + } + } + return sum; + +} +int main (int argc, const char * argv[]) { + NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; + int testCases; + scanf("%d", &testCases); + for(int i=0;i costArrayList = new ArrayList(); + for(int j = 0; jintArrayList = new ArrayList(); + for(int i = 0;i difference){ + break; + } + currentPos++; + + } + startPos++; + } + System.out.println(count); + + + } +} \ No newline at end of file diff --git a/Algorithms/Sorting/InsertionSort.java b/Algorithms/Sorting/InsertionSort.java new file mode 100644 index 0000000..04140f7 --- /dev/null +++ b/Algorithms/Sorting/InsertionSort.java @@ -0,0 +1,83 @@ +/* Insertion Sort - Part I +Sorting +One common task for computers is to sort data. For example, people might want to see all their files on a computer sorted by size. Since sorting is a simple problem with many different possible solutions, it is often used to introduce the study of algorithms. + +Insertion Sort +These challenges will cover Insertion Sort, a simple and intuitive sorting algorithm. We will first start with an already sorted list. + +Insert element into sorted list +Given a sorted list with an unsorted number V in the rightmost cell, can you write some simple code to insert V into the array so that it remains sorted? + +Print the array every time a value is shifted in the array until the array is fully sorted. The goal of this challenge is to follow the correct order of insertion sort. + +Guideline: You can copy the value of V to a variable and consider its cell "empty". Since this leaves an extra cell empty on the right, you can shift everything over until V can be inserted. This will create a duplicate of each value, but when you reach the right spot, you can replace it with V. + +Input Format +There will be two lines of input: + +s - the size of the array +ar - the sorted array of integers +Output Format +On each line, output the entire array every time an item is shifted in it. + +Constraints +1≤s≤1000 +−10000≤V≤10000,V ∈ ar +*/ + +import java.io.*; +import java.util.*; +import java.text.*; +import java.math.*; +import java.util.regex.*; + +public class Solution { + + + + public static void insertIntoSorted(int[] ar) + { + int numToInsert = ar[ar.length-1]; + int pos = ar.length-2; + while(pos>=0){ + if(ar[pos]>numToInsert){ + ar[pos+1]=ar[pos]; + pos--; + printArray(ar); + + }else{ + ar[pos+1]=numToInsert; + printArray(ar); + break; + } + } + if(pos == -1){ + ar[0]=numToInsert; + printArray(ar); + } + + } + + +/* Tail starts here */ + public static void main(String[] args) { + Scanner in = new Scanner(System.in); + int s = in.nextInt(); + int[] ar = new int[s]; + for(int i=0;i=0;i--){ + if(ar[currentPos] hm = new HashMap(); + sc.nextLine(); + String[]numArray = sc.nextLine().split(" "); + for (String num:numArray){ + Double number = hm.get(num); + if(number == null){ + hm.put(num,new Double(1)); + }else{ + hm.put(num,number+1); + } + } + + double total = 0; + for (Double value : hm.values()) { + total=total+(value*(value-1)); + } + + System.out.printf("%.0f\n",total); + + } + } +} \ No newline at end of file diff --git a/Algorithms/Strings/AlternatingCharacters.java b/Algorithms/Strings/AlternatingCharacters.java new file mode 100644 index 0000000..e27f155 --- /dev/null +++ b/Algorithms/Strings/AlternatingCharacters.java @@ -0,0 +1,51 @@ +/* Alternating Characters +Shashank likes strings in which consecutive characters are different. For example, he likes ABABA, while he doesn't like ABAA. Given a string containing characters A and B only, he wants to change it into a string he likes. To do this, he is allowed to delete the characters in the string. + +Your task is to find the minimum number of required deletions. + +Input Format + +The first line contains an integer T, i.e. the number of test cases. +The next T lines contain a string each. + +Output Format + +For each test case, print the minimum number of deletions required. + +Constraints + +1≤T≤10 +1≤ length of string ≤10^5 +*/ + +import java.io.*; +import java.util.*; + +public class AlternatingCharacters { + + public static int consecutiveChars(String str) + { + StringBuilder mutableStr = new StringBuilder(str); + int numDeletions = 0; + int pos = 0; + while(pos dict = new HashMap(); + int numTestCases = Integer.parseInt(sc.nextLine()); + for(int i = 0;ialphabet = new ArrayList(Arrays.asList("abcdefghijklmnopqrstuvwxyz".split(""))); + alphabet.remove(0); + Scanner sc = new Scanner(System.in); + String sentence = sc.nextLine().toLowerCase(); + + for(int i=0;i a.length - 1 ? k % a.length : k; + + for(int a0 = 0; a0 < q; a0++){ + int m = in.nextInt(); + int pos = m - offset; + if(pos < 0){ + pos = a.length + pos; + } + System.out.println(a[pos]); + } + + } +} + diff --git a/Algorithms/Warmup/DiagonalDifference.java b/Algorithms/Warmup/DiagonalDifference.java new file mode 100644 index 0000000..d79427d --- /dev/null +++ b/Algorithms/Warmup/DiagonalDifference.java @@ -0,0 +1,60 @@ +/* Diagonal Difference +You are given a square matrix of size N×N. Calculate the absolute difference of the sums across the two main diagonals. + +Input Format + +The first line contains a single integer N. The next N lines contain N integers describing the matrix. + +Constraints +1≤N≤100 +−100≤A[i]≤100 +Output Format + +Output a single integer equal to the absolute difference in the sums across the diagonals. + +Sample Input + +3 +11 2 4 +4 5 6 +10 8 -12 +Sample Output + +15 +Explanation + +The first diagonal of the matrix is: + +11 + 5 + -12 +Sum across the first diagonal = 11+5-12= 4 + +The second diagonal of the matrix is: + + 4 + 5 +10 +Sum across the second diagonal = 4+5+10 = 19 +Difference: |4-19| =15 +*/ + +import java.io.*; +import java.util.*; + +public class DiagonalDifference { + + public static void main(String[] args) { + /* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */ + Scanner sc = new Scanner(System.in); + + int length = Integer.parseInt(sc.nextLine()); + int diagonalOne=0, diagonalTwo =0; + for(int i=0;i0){ + positiveCount++; + }else{ + zeroCount++; + } + } + System.out.printf("%.6f\n%.6f\n%.6f",positiveCount/numCases,negativeCount/numCases,zeroCount/numCases); + } +} \ No newline at end of file diff --git a/Algorithms/Warmup/SavethePrisoner.java b/Algorithms/Warmup/SavethePrisoner.java new file mode 100644 index 0000000..ad3d152 --- /dev/null +++ b/Algorithms/Warmup/SavethePrisoner.java @@ -0,0 +1,56 @@ +/* Save the Prisoner! +https://www.hackerrank.com/challenges/save-the-prisoner + +A jail has prisoners, and each prisoner has a unique id number, S , ranging from 1 to N . +There are sweets that must be distributed to the prisoners. + +The jailer decides the fairest way to do this is by sitting the prisoners down in a circle (ordered by ascending ), +and then, starting with some random , distribute one candy at a time to each sequentially numbered prisoner until all candies are distributed. For example, if the jailer picks prisoner , then his distribution order would be until all sweets are distributed. + +But wait—there's a catch—the very last sweet is poisoned! Can you find and print the ID number of the last prisoner +to receive a sweet so he can be warned? + +Input Format + +The first line contains an integer, T , denoting the number of test cases. +The T subsequent lines each contain 3 space-separated integers: +N (the number of prisoners), M (the number of sweets), and S (the prisoner ID), respectively. + + +Output Format + +For each test case, print the ID number of the prisoner who receives the poisoned sweet on a new line. + +Sample Input + +1 +5 2 1 +Sample Output + +2 +*/ + +import java.io.*; +import java.util.*; + +public class SavethePrisoner { + + public static void main(String[] args) + { + Scanner sc = new Scanner(System.in); + int numTestCases = sc.nextInt(); + for(int i = 0; i < numTestCases; i++){ + int numPrisoners = sc.nextInt(); + int numCandies = sc.nextInt(); + int startID = sc.nextInt(); + + if ((startID + numCandies) > numPrisoners) { + int leftCandies = (startID + numCandies) - numPrisoners - 1; + System.out.println(leftCandies <= 1 || (leftCandies % numPrisoners) == 0?numPrisoners : (leftCandies % numPrisoners)); + } else { + System.out.println("" + ((startID + numCandies) - 1) ); + } + } + + } +} \ No newline at end of file diff --git a/Algorithms/Warmup/SimpleArraySum.java b/Algorithms/Warmup/SimpleArraySum.java new file mode 100644 index 0000000..d3b749e --- /dev/null +++ b/Algorithms/Warmup/SimpleArraySum.java @@ -0,0 +1,36 @@ +/* Simple Array Sum + +You are given an array of integers of size N. Can you find the sum of the elements in the array? + +Input +The first line of input consists of an integer N. The next line contains N space-separated integers +representing the array elements. +Sample: + +6 +1 2 3 4 10 11 +Output +Output a single value equal to the sum of the elements in the array. +For the sample above you would just print 31 since 1+2+3+4+10+11=31. + +*/ + +import java.io.*; +import java.util.*; +import java.text.*; +import java.math.*; +import java.util.regex.*; + +public class SimpleArraySum { + + public static void main(String[] args) { + + Scanner sc = new Scanner(System.in); + int number = sc.nextInt(); + int sum=0; + for(int i = 0;i + + +int main(int argc, const char * argv[]){ + NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; + NSInteger a0; + NSInteger a1; + NSInteger a2; + scanf("%li %li %li",&a0,&a1,&a2); + NSInteger b0; + NSInteger b1; + NSInteger b2; + scanf("%li %li %li",&b0,&b1,&b2); + NSInteger aliceTotal = 0; + NSInteger bobTotal = 0; + a0 > b0?aliceTotal++:a0 < b0?bobTotal++:0; + a1 > b1?aliceTotal++:a1 < b1?bobTotal++:0; + a2 > b2?aliceTotal++:a2 < b2?bobTotal++:0; + printf("%li %li",aliceTotal, bobTotal); + + [pool drain]; + return 0; +} \ No newline at end of file diff --git a/Contests/CodeWhiz.java 2016/ComparetheTriplets.java b/Contests/CodeWhiz.java 2016/ComparetheTriplets.java new file mode 100644 index 0000000..2749f57 --- /dev/null +++ b/Contests/CodeWhiz.java 2016/ComparetheTriplets.java @@ -0,0 +1,78 @@ +/* Compare the Triplets + +Alice and Bob each created one problem for HackerRank. A reviewer rates the two challenges, +awarding points on a scale from to for three categories: problem clarity, originality, and difficulty. + +We define the rating for Alice's challenge to be the triplet , and the rating for +Bob's challenge to be the triplet. + +Your task is to find their comparison scores by comparing with , with , and with. + +If , then Alice is awarded point. +If , then Bob is awarded point. +If , then neither person receives a point. +Given and , can you compare the two challenges and print their respective comparison points? + +Input Format + +The first line contains space-separated integers, , , and , describing the respective values in triplet . +The second line contains space-separated integers, , , and , describing the respective values in triplet . + +Constraints + + + +Output Format + +Print two space-separated integers denoting the respective comparison scores earned by Alice and Bob. + +Sample Input + +5 6 7 +3 6 10 +Sample Output + +1 1 +*/ + +import java.io.*; +import java.util.*; +import java.text.*; +import java.math.*; +import java.util.regex.*; + + +public class ComparetheTriplets { + + public static void main(String[] args)throws IOException { + Math ob = new Math(); + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + int T=Integer.parseInt(br.readLine()); + performOperation op; + int ret =0; + String ans=null; + while(T-->0){ + String s=br.readLine().trim(); + StringTokenizer st=new StringTokenizer(s); + int ch=Integer.parseInt(st.nextToken()); + int num=Integer.parseInt(st.nextToken()); + if(ch==1){ + op = ob.checkEvenOdd(); + ret = ob.checker(op,num); + ans = (ret == 0)?"EVEN":"ODD"; + } + else if(ch==2){ + op = ob.checkPrime(); + ret = ob.checker(op,num); + ans = (ret == 0)?"PRIME":"COMPOSITE"; + } + else if(ch==3){ + op = ob.checkPalindrome(); + ret = ob.checker(op,num); + ans = (ret == 0)?"PALINDROME":"NOT PALINDROME"; + + } + System.out.println(ans); + } + } +} \ No newline at end of file diff --git a/Contests/CodeWhiz.java 2016/CovariantReturnTypes.java b/Contests/CodeWhiz.java 2016/CovariantReturnTypes.java new file mode 100644 index 0000000..2242c4d --- /dev/null +++ b/Contests/CodeWhiz.java 2016/CovariantReturnTypes.java @@ -0,0 +1,113 @@ +/* Covariant Return Types + +Java allows for Covariant Return Types, which means you can vary your return type as long you are returning a +subclass of your specified return type. + +Method Overriding allows a subclass to override the behavior of an existing superclass method and specify a +return type that is some subclass of the original return type. + +Note: It is best practice to use the @Override annotation when overriding a superclass method. + +We will append a hidden class to test your code; the method in our test class takes the +name of a state as input and prints the national flower of that state using the classes and +methods you written by you. + +Resources +Covariant Return Type +Java Covariant Type + +Input Format + +Input is handled for you by the hidden test class. + +Output Format + +Output is handled for you by the hidden test class. + +Sample Input + +A single line containing the name of a State: + +AndhraPradesh +Sample Output + +A single line containing the national flower of the State received as input: + +Lily +*/ + +import java.io.*; +import java.util.*; +import java.text.*; +import java.math.*; +import java.util.regex.*; + +class Flower +{ + String whats_Your_Name() + { + return "I have many names and types"; + } +} + +class Jasmine extends Flower +{ + @Override + String whats_Your_Name() + { + return "Jasmine"; + } +} + +class Lily extends Flower +{ + @Override + String whats_Your_Name() + { + return "Lily"; + } +} + +class Lotus extends Flower +{ + @Override + String whats_Your_Name() + { + return "Lotus"; + } +} + +class State +{ + Flower your_National_Flower() + { + return new Flower(); + } +} + +class WestBengal extends State +{ + @Override + Flower your_National_Flower() + { + return new Jasmine(); + } +} + +class Karnataka extends State +{ + @Override + Flower your_National_Flower() + { + return new Lotus(); + } +} + +class AndhraPradesh extends State +{ + @Override + Flower your_National_Flower() + { + return new Lily(); + } +} \ No newline at end of file diff --git a/Contests/CodeWhiz.java 2016/JavaLambdaExpressions.java b/Contests/CodeWhiz.java 2016/JavaLambdaExpressions.java new file mode 100644 index 0000000..cfcd20c --- /dev/null +++ b/Contests/CodeWhiz.java 2016/JavaLambdaExpressions.java @@ -0,0 +1,128 @@ +/* JavaLambdaExpressions + +This Java 8 challenge tests your knowledge of Lambda expressions! + +Write the following methods that return a lambda expression performing a specified action: + +performOperation checkEvenOdd(): The lambda expression must return if a number is even or if it is odd. +performOperation checkPrime(): The lambda expression must return if a number is prime or if it is composite. +performOperation checkPalindrome(): The lambda expression must return if a number is a palindrome or if it is not. +Input Format + +Input is handled for you by the locked stub code in your editor. + +Output Format + +The locked stub code in your editor will print lines of output. + +Sample Input + +The first line contains an integer, (the number of test cases). + +The subsequent lines each describe a test case in the form of space-separated integers: +The first integer specifies the condition to check for ( for Odd/Even, for Prime, or for Palindrome). +The second integer denotes the number to be checked. + +5 +1 4 +2 5 +3 898 +1 3 +2 12 +Sample Output + +EVEN +PRIME +PALINDROME +ODD +COMPOSITE +*/ + +import java.io.*; +import java.util.*; +import java.text.*; +import java.math.*; +import java.util.regex.*; + + + interface performOperation + { + int check(int a); + } + class Math{ + public static int checker(performOperation p ,int num){ + return p.check(num); + } + + performOperation checkEvenOdd() + { + performOperation p = (a) -> {return a%2;}; + + return p; + } + + performOperation checkPrime () + { + performOperation p = (a) -> { + if (a == 1) return 1; + for(int i = 2;i { + String word = ""+a; + boolean isPalindrome = true; + for(int i = 0;i<(int)word.length()/2;i++) + { + if(word.charAt(i) != word.charAt(word.length()-1-i)){ + isPalindrome = false; + break; + + } + } + return isPalindrome?0:1; + }; + return p; + } + } + +public class JavaLambdaExpressions { + + public static void main(String[] args)throws IOException { + Math ob = new Math(); + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + int T=Integer.parseInt(br.readLine()); + performOperation op; + int ret =0; + String ans=null; + while(T-->0){ + String s=br.readLine().trim(); + StringTokenizer st=new StringTokenizer(s); + int ch=Integer.parseInt(st.nextToken()); + int num=Integer.parseInt(st.nextToken()); + if(ch==1){ + op = ob.checkEvenOdd(); + ret = ob.checker(op,num); + ans = (ret == 0)?"EVEN":"ODD"; + } + else if(ch==2){ + op = ob.checkPrime(); + ret = ob.checker(op,num); + ans = (ret == 0)?"PRIME":"COMPOSITE"; + } + else if(ch==3){ + op = ob.checkPalindrome(); + ret = ob.checker(op,num); + ans = (ret == 0)?"PALINDROME":"NOT PALINDROME"; + + } + System.out.println(ans); + } + } +} \ No newline at end of file diff --git a/Contests/CodeWhiz.java 2016/JavaList.java b/Contests/CodeWhiz.java 2016/JavaList.java new file mode 100644 index 0000000..c0ceee3 --- /dev/null +++ b/Contests/CodeWhiz.java 2016/JavaList.java @@ -0,0 +1,82 @@ +/* Java List + +For this problem, we have types of queries you can perform on a List: + +Insert at index : + +Insert +x y +Delete the element at index : + +Delete +x +Given a list, , of integers, perform queries on the list. Once all queries are completed, +print the modified list as a single line of space-separated integers. + +Input Format + +The first line contains an integer, (the initial number of elements in ). +The second line contains space-separated integers describing . +The third line contains an integer, (the number of queries). +The subsequent lines describe the queries, and each query is described over two lines: + +If the first line of a query contains the String Insert, then the second line contains +two space separated integers , and the value must be inserted into at index. +If the first line of a query contains the String Delete, then the second line contains index, +whose element must be deleted from . +Constraints + +Each element in is a 32-bit integer. +Output Format + +Print the updated list as a single line of space-separated integers. + +Sample Input + +5 +12 0 1 78 12 +2 +Insert +5 23 +Delete +0 +Sample Output + +0 1 78 12 23 + +*/ + +import java.io.*; +import java.util.*; +import java.text.*; +import java.math.*; +import java.util.regex.*; + +public class JavaList +{ + + public static void main(String[] args) { + + Scanner sc = new Scanner(System.in); + int numElements = Integer.parseInt(sc.nextLine()); + ArrayList numList = new ArrayList<>(); + for(int i = 0;i < numElements;i++){ + numList.add(sc.nextInt()); + } + int numQueries = sc.nextInt(); + sc.nextLine(); + for(int i = 0;i < numQueries;i++){ + String queryType = sc.nextLine(); + if(queryType.equals("Insert")){ + String[] queryArray = sc.nextLine().split(" "); + numList.add(Integer.parseInt(queryArray[0]),Integer.parseInt(queryArray[1])); + }else{ + int removeIndex = Integer.parseInt(sc.nextLine()); + numList.remove(removeIndex); + } + } + for(Integer num : numList){ + System.out.print(num+" "); + } + } +} \ No newline at end of file diff --git a/Contests/CodeWhiz.java 2016/JavaPrimalityTest.java b/Contests/CodeWhiz.java 2016/JavaPrimalityTest.java new file mode 100644 index 0000000..8117024 --- /dev/null +++ b/Contests/CodeWhiz.java 2016/JavaPrimalityTest.java @@ -0,0 +1,91 @@ +/* Java List + +Java's BitSet class implements a vector of bit values (i.e.: () or ()) that grows as needed, +allowing us to easily manipulate bits while optimizing space (when compared to other collections). +Any element having a bit value of is called a set bit. + +Given BitSets, and , of size where all bits in both BitSets are initialized to, +perform a series of operations. After each operation, print the number of set bits +in the respective BitSets as two space-separated integers on a new line. + +Input Format + +The first line contains space-separated integers, (the length of both BitSets and ) +and (the number of operations to perform), respectively. +The subsequent lines each contain an operation in one of the following forms: + +AND +OR +XOR +FLIP +SET +In the list above, is the integer or , where denotes and denotes. + is an integer denoting a bit's index in the BitSet corresponding to. + +For the binary operations , , and , operands are read from left to right and the BitSet resulting +from the operation replaces the contents of the first operand. For example: + +AND 2 1 + is the left operand, and is the right operand. This operation should assign the result of to . + +Constraints + +Output Format + +After each operation, print the respective number of set bits in BitSet and BitSet +as space-separated integers on a new line. + +Sample Input + +5 4 +AND 1 2 +SET 1 4 +FLIP 2 2 +OR 2 1 +Sample Output + +0 0 +1 0 +1 1 +1 2 + +*/ + +import java.io.*; +import java.util.*; +import java.text.*; +import java.math.*; +import java.util.regex.*; + +public class JavaPrimalityTest +{ + + public static void main(String[] args) + { + Scanner sc = new Scanner(System.in); + int bitSetSize = sc.nextInt(); + int numOperations = sc.nextInt(); + BitSet[] bitSetArray = new BitSet[2]; + bitSetArray[0] = new BitSet(bitSetSize); + bitSetArray[1] = new BitSet(bitSetSize); + sc.nextLine(); + for(int i = 0;i < numOperations; i++) + { + String[] opArray = sc.nextLine().split(" "); + switch(opArray[0]){ + case "AND": bitSetArray[Integer.parseInt(opArray[1])-1].and(bitSetArray[Integer.parseInt(opArray[2])-1]); + break; + case "OR": bitSetArray[Integer.parseInt(opArray[1])-1].or(bitSetArray[Integer.parseInt(opArray[2])-1]); + break; + case "XOR": bitSetArray[Integer.parseInt(opArray[1])-1].xor(bitSetArray[Integer.parseInt(opArray[2])-1]); + break; + case "FLIP": bitSetArray[Integer.parseInt(opArray[1])-1].flip(Integer.parseInt(opArray[2])); + break; + case "SET": bitSetArray[Integer.parseInt(opArray[1])-1].set(Integer.parseInt(opArray[2])); + break; + } + System.out.println(bitSetArray[0].cardinality() + " " + bitSetArray[1].cardinality()); + + } + } +} \ No newline at end of file diff --git a/Contests/CodeWhiz.java 2016/JavaSingleton.java b/Contests/CodeWhiz.java 2016/JavaSingleton.java new file mode 100644 index 0000000..b143ea7 --- /dev/null +++ b/Contests/CodeWhiz.java 2016/JavaSingleton.java @@ -0,0 +1,50 @@ +/* Java Singleton + +"The singleton pattern is a design pattern that restricts the instantiation of a class to one object. +This is useful when exactly one object is needed to coordinate actions across the system." +- Wikipedia: Singleton Pattern + +Complete the Singleton class in your editor which contains the following components: + +A private Singleton non parameterized constructor. +A public String instance variable named . +Write a static method named getSingleInstance that returns the single instance of the Singleton class. +Once submitted, our hidden Solution class will check your code by taking a String as input and +then using your Singleton class to print a line. + +Input Format + +You will not be handling any input in this challenge. + +Output Format + +You will not be producing any output in this challenge. + +Sample Input + +hello world +Sample Output + +Hello I am a singleton! Let me say hello world to you + +*/ + +import java.io.*; +import java.util.*; +import java.text.*; +import java.math.*; +import java.util.regex.*; + +public class JavaSingleton +{ + + public String str; + private static Singleton singleton = new Singleton(); + + private Singleton(){}; + + public static Singleton getSingleInstance() + { + return singleton; + } +} \ No newline at end of file diff --git a/Contests/CodeWhiz.java 2016/MaximumandMinimum.java b/Contests/CodeWhiz.java 2016/MaximumandMinimum.java new file mode 100644 index 0000000..68c145e --- /dev/null +++ b/Contests/CodeWhiz.java 2016/MaximumandMinimum.java @@ -0,0 +1,105 @@ +/* Maximum and Minimum + +The locked code in your editor passes array (of size ) and index to the print method, whose try +block attempts to print element ; if is Out-of-Range, an Array Index Out Of Bounds Exception is thrown. + +Complete the code in your editor so that it prints the maximum and minimum elements in array +regardless of whether or not an exception is thrown. + +Input Format + +The first line contains an integer, , the number of elements in . +The second line contains space-separated integers describing . +The third line contains an index, , to be accessed. + +Note: Input from stdin handled by the locked code in the editor. + +Constraints + + + +Output Format + +The try block will print the value accessed at ; if an Exception is thrown, it will be printed by +the locked code in your editor. +You must print the respective maximum and minimum values in array as a single pair of space-separated integers +on a new line—regardless of whether an exception is thrown. + +Note: Observe that your max/min values may print on either the first or second line, depending on +whether or not an Exception was thrown! + +Sample Input 0 + +12 +-12 0 1 -899 23 45 96 10 75 23 0 33 +100 +Sample Output 0 + +96 -899 +java.lang.ArrayIndexOutOfBoundsException +Sample Input 1 + +10 +4 908 -05 445 -208 325 -2 -718 863 400 +9 +Sample Output 1 + +400 +908 -718 + +*/ + +import java.io.*; +import java.util.*; +import java.text.*; +import java.math.*; +import java.util.regex.*; + +public class MaximumandMinimum +{ + + public static void print(int A[],int i) + { + try{ + System.out.println(A[i]); + } + catch(ArrayIndexOutOfBoundsException e){ + int max = A[0]; + int min = A[0]; + for(int j = 0;j < A.length;j++){ + if(max < A[j]) max = A[j]; + if(min > A[j]) min = A[j]; + } + System.out.println(max+" "+min); + throw e; + } + int max = A[0]; + int min = A[0]; + for(int j = 0;j < A.length;j++){ + if(max < A[j]) max = A[j]; + if(min > A[j]) min = A[j]; + } + System.out.println(max+" "+min); + } + + public static void main(String[] args) { + int N; + Scanner st=new Scanner(System.in); + N=st.nextInt(); + int A[]=new int[N]; + for(int i=0;i s.cgpa){ + return 1; + } + if(this.fname.compareTo(s.fname) > 0){ + return -1; + }else if(this.fname.compareTo(s.fname) < 0){ + return 1; + }else{ + if(this.token < s.token){ + return -1; + } + } + return 1; + } + + public String toString() + { + return ""+ this.token +" " + this.fname + " " + this.cgpa; + } +} + +public class ServetheStudents { + + public static ArrayList studentQueue = new ArrayList<>(); + + public static void insertStudent(Student s) + { + int insertPos = 0; + for(int i = 0;i < studentQueue.size() ;i++){ + if(studentQueue.get(insertPos).compareTo(s)>0){ + insertPos = i+1; + }else{ + break; + } + } + studentQueue.add(insertPos,s); + } + + public static void main(String[] args) { + Scanner in = new Scanner(System.in); + int totalEvents = Integer.parseInt(in.nextLine()); + while(totalEvents>0){ + String[] eventArr = in.nextLine().split(" "); + if(eventArr.length == 1){ + if(!studentQueue.isEmpty()){ + studentQueue.remove(0); + } + }else{ + Student s = new Student(Integer.parseInt(eventArr[3]),eventArr[1],Double.parseDouble(eventArr[2])); + insertStudent(s); + } + totalEvents--; + } + if(studentQueue.size() > 0){ + for(int i = 0;i scencesMap = new HashMap(); //stores number of actors for a specific scene + + //cachedSearchMap stores the amount of scenecs have certain amount of actors + //For example there are 2 scences with 3 actors, 5 scences with 1 actor + //They keys are in sorted ordered so they can be itterated to find out count the number of scenes having

cachedSearchMap = new TreeMap(); + Integer numActorsInScene = 0; + + for(int i = 0;i 1){ + cachedSearchMap.put(new Integer(numActorsInScene),smValue-1); + } + + }else{ + scencesMap.put(scenePos,one); + Integer smValue = cachedSearchMap.get(one); + if(smValue != null){ + cachedSearchMap.put(one, smValue+1); + }else{ + cachedSearchMap.put(one,one); + } + } + } + for(int i = 0; i < numOfActions;i++) + { + + int actionType = sc.nextInt(); + if(actionType == 2 ){ + int actorsCount = sc.nextInt(); + + int total = 0; + //itterates through search tree to sum up the scences that have

1){ + scencesMap.put(prevPos,prevNumActors-1); + } + + //moving actors from one scene to another will require to update cachedSearchMap and add count to + //actors new position and subctract one from previous + Integer prvNumValue = cachedSearchMap.remove(prevNumActors); + if(prvNumValue != null && prvNumValue > 1){ + cachedSearchMap.put(new Integer(prevNumActors),prvNumValue-1); + } + + + if((prevNumActors-1) > 0 ) { + Integer prvNumActorsOneVal = cachedSearchMap.get(prevNumActors-1); + + if(prvNumActorsOneVal != null){ + cachedSearchMap.put(new Integer(prevNumActors-1), prvNumActorsOneVal+1); + }else{ + cachedSearchMap.put(new Integer(prevNumActors-1), one); + } + } + Integer posNumValue = scencesMap.get(pos); + int posNumActors = 1; + if(posNumValue != null){ + scencesMap.put(pos, posNumValue+1); + posNumActors = posNumValue+1; + }else{ + scencesMap.put(pos, one); + } + + Integer smValue = cachedSearchMap.remove(posNumActors-1); + if(smValue != null && smValue > 1){ + cachedSearchMap.put(new Integer(posNumActors-1),smValue-1); + } + smValue = cachedSearchMap.get(posNumActors); + if(smValue != null){ + cachedSearchMap.put(new Integer(posNumActors), smValue+1); + }else{ + cachedSearchMap.put(new Integer(posNumActors), one); + } + } + + } + } +} \ No newline at end of file diff --git a/Contests/Indeed Prime CodeSprint/TheUlitmateQuestion.java b/Contests/Indeed Prime CodeSprint/TheUlitmateQuestion.java new file mode 100644 index 0000000..88767e3 --- /dev/null +++ b/Contests/Indeed Prime CodeSprint/TheUlitmateQuestion.java @@ -0,0 +1,87 @@ +/* The Ultimate Question + +42 is the answer to "The Ultimate Question of Life, The Universe, and Everything". But what The +Ultimate Question really is? We may never know! + +Given three integers, a, b, and c, insert two operators between them so that the following equation is true: +a (operator1) b (operator2) c=42. + +You may only use the addition (+) and multiplication (∗) operators. You can't change the order of the variables. + +If a valid equation exists, print it; otherwise, print This is not the ultimate question. + +Input Format + +A single line consisting three space-separated integers: a, b, and c. + +Constraints: +0≤a,b,c≤42 +Output Format + +Print the equation with no whitespace between the operators and the three numbers. If there is no answer, +print This is not the ultimate question. + +Note: It is guaranteed that there is no more than one valid equation per test case. + +Sample Input + +Example 1: + +12 5 6 +Example 2: + +10 20 12 +Example 3: + +5 12 6 +Sample Output + +Example 1: + +12+5*6 +Example 2: + +10+20+12 +Example 3: + +This is not the ultimate question +*/ + +import java.io.*; +import java.util.*; + +public class TheUltimateQuestion { + + public static void main(String[] args) { + + Scanner sc = new Scanner(System.in); + int a = sc.nextInt(); + int b = sc.nextInt(); + int c = sc.nextInt(); + int ultNum = 0; + String equation = null; + for(int i = 0; i < 4; i++) + { + + if((i&2) == 2){ + if((i&1) == 1){ + ultNum = a*b*c; + }else{ + ultNum = a*b+c; + } + }else{ + if((i&1) == 1){ + ultNum = a+b*c; + }else{ + ultNum = a+b+c; + } + } + if(ultNum == 42){ + equation = ((i&2)==2?""+a+"*"+b:a+"+"+b) + ((i&1)==1?"*"+c:"+"+c); + break; + } + ultNum = 0; + } + System.out.println(equation != null?equation:"This is not the ultimate question"); + } +} \ No newline at end of file diff --git a/Contests/OpenBracket CodeSprint/FraudulentActivityNotifications.java b/Contests/OpenBracket CodeSprint/FraudulentActivityNotifications.java new file mode 100644 index 0000000..996377e --- /dev/null +++ b/Contests/OpenBracket CodeSprint/FraudulentActivityNotifications.java @@ -0,0 +1,117 @@ +/* + +Fraudulent Activity Notifications + +OpenBracket CodeSprint + +https://www.hackerrank.com/contests/openbracket/challenges/fraudulent-activity-notifications + +*/ + +import java.io.*; +import java.util.*; +import java.text.*; +import java.math.*; +import java.util.regex.*; + +public class FraudulentActivityNotifications { + + static double calculateMedian(ArrayList spendingsArrayList) + { + + if(spendingsArrayList.size() % 2 == 0){ + int middle = ((int) spendingsArrayList.size() / 2) - 1; //offset start 0 + double median = (spendingsArrayList.get(middle) + spendingsArrayList.get(middle+1)) / 2.0; + return median; + } + return spendingsArrayList.get((int) Math.ceil(spendingsArrayList.size() / 2)); + } + + public static void binaryInsertIntegerSortedIntoArrayList(ArrayList spendingsArrayList, Integer num) + { + if (spendingsArrayList.size() == 0) { + spendingsArrayList.add(num); + return; + } + int lowerBound = 0; + int upperBound = spendingsArrayList.size(); + int position = ( lowerBound + upperBound) / 2; + while(position < spendingsArrayList.size() && (spendingsArrayList.get(position) != num) && (lowerBound <= upperBound)) + { + if (spendingsArrayList.get(position) > num) + { + upperBound = position - 1; + } + else + { + lowerBound = position + 1; + } + position = (lowerBound + upperBound) / 2; + + } + + if(position >= spendingsArrayList.size()){ + spendingsArrayList.add(num); + }else if(spendingsArrayList.get(position) == num){ + spendingsArrayList.add(position, num); + } else if(num > spendingsArrayList.get(position)){ + spendingsArrayList.add(upperBound+1, num); + } else { + spendingsArrayList.add(lowerBound, num); + } + } + + + + static void removeFromSpendingsArrayList(ArrayList spendingsArrayList, Integer num) + { + if (spendingsArrayList.size() == 0) return; + //Using binary search to remove any integer object with the same value as num + //Doesn't have to be the same object + + int lowerBound = 0; + int upperBound = spendingsArrayList.size(); + int position = ( lowerBound + upperBound) / 2; + while(spendingsArrayList.get(position).intValue() != num.intValue()) + { + if (spendingsArrayList.get(position).intValue() > num.intValue()) + { + upperBound = position - 1; + } + else + { + lowerBound = position + 1; + } + position = (lowerBound + upperBound) / 2; + + } + //value should be found + spendingsArrayList.remove(position); + } + + public static void main(String[] args) { + + Scanner sc = new Scanner(System.in); + double numDays = sc.nextInt(); + double numDaysToCalculateSpendings = sc.nextInt(); + ArrayList spendingsArrayList = new ArrayList<>(); + ArrayList expenditures = new ArrayList<>(); + int numNotifications = 0; + int pos = 0; + double median = 0; + for(double i = 0; i < numDays;i++){ + Integer expenditure = new Integer(sc.nextInt()); + expenditures.add(expenditure); + if(i >= numDaysToCalculateSpendings){ + median = calculateMedian(spendingsArrayList); + if(expenditure.intValue() >= (median * 2)){ + numNotifications++; + } + removeFromSpendingsArrayList(spendingsArrayList, expenditures.get(pos++)); + } + binaryInsertIntegerSortedIntoArrayList(spendingsArrayList,expenditure); + } + sc.close(); + System.out.println(numNotifications); + } +} \ No newline at end of file diff --git a/Contests/OpenBracket CodeSprint/ViralAdvertising.java b/Contests/OpenBracket CodeSprint/ViralAdvertising.java new file mode 100644 index 0000000..52fd40f --- /dev/null +++ b/Contests/OpenBracket CodeSprint/ViralAdvertising.java @@ -0,0 +1,33 @@ +/* + +Viral Advertising + +OpenBracket CodeSprint + +https://www.hackerrank.com/contests/openbracket/challenges/strange-advertising/copy-from/7419577 + +*/ + +import java.io.*; +import java.util.*; +import java.text.*; +import java.math.*; +import java.util.regex.*; + +public class ViralAdvertising { + + + public static void main(String[] args) { + Scanner sc = new Scanner(System.in); + int numDays = sc.nextInt(); + int numReceived = 5; + int numPeopleLiked = 0; + for(int i = 0;i < numDays; i++){ + int numPeopleLikedToday = (int) Math.floor(numReceived / 2); + numPeopleLiked += numPeopleLikedToday; + numReceived = numPeopleLikedToday * 3; + } + System.out.println(numPeopleLiked); + + } +} \ No newline at end of file diff --git a/Contests/TechHire CodeSprint /ComparetheTriplets.java b/Contests/TechHire CodeSprint /ComparetheTriplets.java new file mode 100644 index 0000000..5c9071b --- /dev/null +++ b/Contests/TechHire CodeSprint /ComparetheTriplets.java @@ -0,0 +1,44 @@ + +/* Large Matrix + +Sam has a matrix of infinite dimensions. He starts out by placing a black ball in the top-left cell of the matrix and +then fills the rest of the cells by placing the remaining balls in such a way that no two adjacent cells +contain balls of the same color. + +Two cells are considered to be adjacent if they share a common side (i.e., cell is adjacent to cells and . + +You're given queries in the form of two integers denoting the location of a cell at row and column . +For each query, print the color of the ball Sam placed in that cell (i.e., either red or black) on a new line. + + +*/ + +import java.io.*; +import java.util.*; +import java.text.*; +import java.math.*; +import java.util.regex.*; + + +public class LargeMatrix { + + public static void main(String[] args) { + Scanner in = new Scanner(System.in); + int Q = in.nextInt(); + for(int a0 = 0; a0 < Q; a0++){ + int r = in.nextInt(); + int c = in.nextInt(); + if(r % 2 == 0){ + if(c % 2 == 0){ + System.out.println("black"); + } else { + System.out.println("red"); + } + } else if(c % 2 == 0){ + System.out.println("red"); + } else { + System.out.println("black"); + } + } + } +} \ No newline at end of file diff --git a/Contests/TechHire CodeSprint /FindPrefix.java b/Contests/TechHire CodeSprint /FindPrefix.java new file mode 100644 index 0000000..5e32a85 --- /dev/null +++ b/Contests/TechHire CodeSprint /FindPrefix.java @@ -0,0 +1,63 @@ + +/* Find Prefix + +Lea is building a search engine. She just implemented a predictive feature that shows all possible search +results when the first few characters of a search term are typed. She modified this problem slightly and +turned it into a HackerRank challenge! Your task is as follows: + +Given q queries where each query is a list of n strings, reverse the functionality of Lea's search +feature by finding the longest common prefix for any two strings in the list and print its length on a new +line. If no two strings share a common prefix, print 0 instead. +*/ + +import java.io.*; +import java.util.*; +import java.text.*; +import java.math.*; +import java.util.regex.*; + + +public class FindPrefix { + + public static int lengthOfLCP(String[] words) + { + if(words.length == 1) { + return 0; + } + + int maxLength = 0; + + Arrays.sort(words); + for(int i = 0; i < words.length; i++){ + for(int j = i+1; j < words.length; j++){ + if(words[i].charAt(0) != words[j].charAt(0)){ + break; + } + int tempMaxLength = 0; + for(int k = 0; k < Math.min(words[i].length(), words[j].length()); k++){ + if(words[i].charAt(k) == words[j].charAt(k)) { + tempMaxLength++; + } else { + break; + } + } + maxLength = Math.max(maxLength,tempMaxLength); + } + } + return maxLength; + } + public static void main(String[] args) { + /* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */ + Scanner sc = new Scanner(System.in); + int numQueries = sc.nextInt(); + for(int i = 0;i < numQueries;i++){ + int numWords = sc.nextInt(); + sc.nextLine(); + String[] words = new String[numWords]; + for(int j = 0; j < numWords; j++){ + words[j] = sc.nextLine(); + } + System.out.println(lengthOfLCP(words)); + } + } +} \ No newline at end of file diff --git a/Contests/TechHire CodeSprint /HackerRankTournament.java b/Contests/TechHire CodeSprint /HackerRankTournament.java new file mode 100644 index 0000000..03b41bb --- /dev/null +++ b/Contests/TechHire CodeSprint /HackerRankTournament.java @@ -0,0 +1,118 @@ + +/* HackerRank Tournament + +HackerRank just ended a programming tournament consisting of contests where each contest had teams compete. +For each contest, there is a leaderboard that lists the respective (number of problem solved during that contest) and time +(specific to that contest) for each team that participated in the contest. + +HackerRank wants you to assemble the tournament's final leaderboard according to the following rules: + +It must contain data for all teams who participated in at least one of the tournament's contests. +A team's final is the total number of problems the team solved across all the contests they participated in. +A team's final time is the sum of their time penalties for each contest they participated in. +Assigning final : +Rankings are assigned according to Standard Competition Ranking, meaning that the assigned to each team is equal to the number of teams ranked higher than that team. For example, if teams and tie for and team came in next, then team will have . +Teams are ranked according to their final , which is the sum of all scores achieved in individual contests. +The team(s) who solved the most problems must be ranked highest, and the team(s) who solved the least problems +must be ranked lowest. +If two teams have the same final , the team having the lesser final time must be ranked higher than the team +having the greater final time . +If two teams have the same final and final (i.e., there is a tie), then they have the same . +Teams having the same should be ordered alphabetically (or lexicographically for alphanumeric team names) by team . +Given the contest leaderboard for each contest in the tournament, print the final tournament leaderboard. +Each line must contain four space-separated values describing a team's respective , , final , and final time . +Order your output by non-decreasing rank according to the rules stated above. +*/ + +import java.io.*; +import java.util.*; +import java.text.*; +import java.math.*; +import java.util.regex.*; + + +class Team implements Comparable { + String name; + int score; + int penalty; + + public Team(String name, int score, int penalty){ + + this.name = name; + this.score = score; + this.penalty = penalty; + } + + public int compareTo(Object o2) + { + Team team1 = this; + Team team2 = (Team)o2; + + if(this.score < team2.score) { + return 1; + } else if (this.score > team2.score) { + return -1; + } else if (this.penalty < team2.penalty) { + return -1; + } else if (this.penalty > team2.penalty) { + return 1; + } + return this.name.compareTo(team2.name); + } + public String toString() + { + return "" + name +" " + score +" "+ penalty; + } +} + +public class HackerRankTournament{ + + + public static void main(String[] args) { + /* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. + */ + Scanner sc = new Scanner(System.in); + int numContests = sc.nextInt(); + HashMap teamsMap = new HashMap<>(); + + for(int i = 0; i < numContests; i++){ + int numTeams = sc.nextInt(); + sc.nextLine(); + for(int j = 0;j < numTeams; j++){ + String[] strArray = sc.nextLine().split(" "); + String teamName = strArray[0]; + int score = Integer.parseInt(strArray[1]); + int penalty = Integer.parseInt(strArray[2]); + Team team = teamsMap.get(teamName); + if(team != null){ + team.score += score; + team.penalty += penalty; + }else { + team = new Team(teamName,score,penalty); + teamsMap.put(teamName, team); + } + } + } + Team[] teamsArray = new Team[teamsMap.size()]; + int index = 0; + for(Team team : teamsMap.values()) { + teamsArray[index++] = team; + } + Arrays.sort(teamsArray); + index = 0; + int currentScore = 0; + int currentPenalty = 0; + for(int i = 0; i < teamsArray.length; i++ ){ + Team team = teamsArray[i]; + if(team.score == currentScore && team.penalty == currentPenalty ){ + System.out.println(""+index + " " + team); + } else { + index = i + 1; + System.out.println("" + (index) + " " + team); + currentScore = team.score; + currentPenalty = team.penalty; + } + } + + } +} \ No newline at end of file diff --git a/Contests/TechHire CodeSprint /PaintTheClassRoom.java b/Contests/TechHire CodeSprint /PaintTheClassRoom.java new file mode 100644 index 0000000..0bb2a93 --- /dev/null +++ b/Contests/TechHire CodeSprint /PaintTheClassRoom.java @@ -0,0 +1,54 @@ + +/* Paint the Classroom + +Emma is wallpapering her classroom. She put up wallpaper panels indexed from to and each panel has a color, , where . + +Emma wants to paint the white wallpaper panels either blue or red in such a way that no two adjacent wallpaper panels are +painted the same color. Two wallpapers with indices and are adjacent if . + +Given the initial sequence of colors for the wallpaper panels, help Emma determine if it's possible to paint +the white wallpaper panels in such a way that no two adjacent panels are +painted the same color. If such a configuration exists, print yes on a new line; otherwise, print no. + +*/ + +import java.io.*; +import java.util.*; +import java.text.*; +import java.math.*; +import java.util.regex.*; + + +public class PaintTheClassRoom { + + public static void main(String[] args) { + Scanner in = new Scanner(System.in); + int n = in.nextInt(); + String c[] = new String[n]; + for(int c_i=0; c_i < n; c_i++){ + c[c_i] = in.next(); + } + boolean isPossible = true; + if(c.length == 1){ + System.out.println("yes"); + }else { + if(c[0].equals("white")) { + c[0] = c[1].equals("red")?"blue":"red"; + } + + for(int i = 1; i < c.length-1; i++){ + String color = c[i]; + + if (color.equals("white")){ + c[i] = c[i-1].equals("red")?"blue":"red"; + if(c[i].equals(c[i+1])){ + isPossible = false; + break; + } + } + } + System.out.println(isPossible?"yes":"no"); + } + + } +} \ No newline at end of file diff --git a/Contests/Week of Code - 16/SomeOfAbsolute.java b/Contests/Week of Code - 16/SomeOfAbsolute.java new file mode 100644 index 0000000..21ba944 --- /dev/null +++ b/Contests/Week of Code - 16/SomeOfAbsolute.java @@ -0,0 +1,62 @@ +/* Sum Of Absolutes +You are given an array of integers A and you will be asked to answer some queries. + +Function Find(int L,int R) +{ + int sum = 0; + for ( i = L ; i<= R; i=i+1 ) + { + sum = abs(sum + A[i]); + } + return sum +} +Now Each Query will ask whether the value returned by the function Find is Even or Odd. + +Note: abs(x) is x if x>=0 otherwise −1×x. + +Input Format +First Line of Input contains N and Q separated by space. +Next Line contains N space separated integers. +Next Q queries follows, each query contains two integers L and R separated by a space. + +Constraints +1≤N≤105 +1≤Q≤105 +−9≤A[i]≤9 +1≤L≤R≤N + +Output Format +For each query output Even if the value returned by Find(L,R) is even otherwise Odd. +*/ + + +import java.io.*; +import java.util.*; + +public class SomeOfAbsolute { + public static String isSumEvenOrOdd(int l,int r,int[]intArray) + { + int sum = 0; + for(int i=l-1;ishiftList = new HashMap(); + for(int i = 0;i < P.length();i++){ + if(E.charAt(i)>P.charAt(i)){ + shift = new Integer(('z'- E.charAt(i))+(P.charAt(i)-'a')+1); + }else{ + shift = new Integer(P.charAt(i) - E.charAt(i)); + } + + Integer countShifts = shiftList.get(shift); + if(countShifts == null){ + + shiftList.put(shift,new Integer(1)); + }else{ + shiftList.put(shift,++countShifts); + } + } + int mostShifts = 0; + for(Map.Entry shiftEntry : shiftList.entrySet()) { + Integer key = shiftEntry.getKey(); + Integer value = shiftEntry.getValue(); + + if(mostShifts == 0){ + + mostShifts = value; + } + if(mostShifts shoeList = new ArrayList<>(); + Scanner sc = new Scanner(System.in); + int numShoes = Integer.parseInt(sc.nextLine()); + int numOfPairs = 0; + for(int i = 0;i < numShoes;i++){ + String shoe = sc.nextLine(); + String shoeDesc = shoe.substring(0,shoe.length()-2); + String shoeType = shoe.substring(shoe.length()-1,shoe.length()-0); + System.out.println(shoeDesc + ":"+shoeType); + if(shoeType.equals("L")){ + int indexRightShoe = shoeList.indexOf(shoeDesc+" R"); + if(indexRightShoe != -1) + { + numOfPairs++; + shoeList.remove(indexRightShoe); + }else{ + shoeList.add(shoe); + } + }else if(shoeType.equals("R")){ + int indexRightShoe = shoeList.indexOf(shoeDesc+" L"); + if(indexRightShoe != -1) + { + numOfPairs++; + shoeList.remove(indexRightShoe); + }else{ + shoeList.add(shoe); + } + } + + } + } +} + + + + + + + + diff --git a/Java/Advanced/CanYouAccess.java b/Java/Advanced/CanYouAccess.java new file mode 100644 index 0000000..0200688 --- /dev/null +++ b/Java/Advanced/CanYouAccess.java @@ -0,0 +1,21 @@ +/* Can You Access? + +You are given a class Solution and an inner class Inner.Private. The main method of class Solution +takes an integer num as input. The powerof2 in class Inner.Private checks whether a number is a power of 2. +You have to call the method powerof2 of the class Inner.Private from the main method of the class Solution. + +Constraints +1≤num≤230 + +Sample Input + +8 + +Sample Output + +8 is power of 2 +An instance of class: Solution.Inner.Private has been created +*/ + +o = new Inner().new Private(); +System.out.println(""+num+" is "+((Inner.Private)o).powerof2(num)); \ No newline at end of file diff --git a/Java/Advanced/JavaAnnotations.java b/Java/Advanced/JavaAnnotations.java new file mode 100644 index 0000000..de86cc7 --- /dev/null +++ b/Java/Advanced/JavaAnnotations.java @@ -0,0 +1,198 @@ +/* Java Annotations + +Java annotation can be used to define the meta data of a Java class or class element. We can use +Java annotation at the compile time to instruct the compiler about the build process. Annotation is also used at runtime to get insight about the properties of class elements. + +Java annotation can be added to an element in the following way: + +@Entity +Class DemoClass{ + +} +We can also set a value to the annotation member. For example: + +@Entity(EntityName="DemoClass") +Class DemoClass{ + +} +In Java, there are several built-in annotations. You can also define your own annotations in the following way: + +@Target(ElementType.METHOD) +@Retention(RetentionPolicy.RUNTIME) +@interface FamilyBudget { + String userRole() default "GUEST"; +} +Here, we define an annotation FamilyBudget, where userRole is the only member in that custom annotation. +The userRole takes only String type values, and the default is "GUEST". If we do not define the value for +this annotation member, then it takes the default. By using @Target, we can specify where our annotation can be used. +For example, the FamilyBudget annotation can only be used with the method in a class. @Retention defines + whether the annotation is available at runtime. To learn more about Java annotation, you can read the + tutorial and oracle docs. + +Take a look at the following code segment: + +@Target(ElementType.METHOD) +@Retention(RetentionPolicy.RUNTIME) +@interface FamilyBudget { + String userRole() default "GUEST"; +} + +class FamilyMember { + + public void seniorMember(int budget, int moneySpend) { + System.out.println("Senior Member"); + System.out.println("Spend: " + moneySpend); + System.out.println("Budget Left: " + (budget - moneySpend)); + } + + public void juniorUser(int budget, int moneySpend) { + System.out.println("Junior Member"); + System.out.println("Spend: " + moneySpend); + System.out.println("Budget Left: " + (budget - moneySpend)); + } +} + +public class Solution { + public static void main(String[] args) { + Scanner in = new Scanner(System.in); + int testCases = Integer.parseInt(in.nextLine()); + while (testCases > 0) { + String role = in.next(); + int spend = in.nextInt(); + try { + Class annotatedClass = FamilyMember.class; + Method[] methods = annotatedClass.getMethods(); + for (Method method : methods) { + if (method.isAnnotationPresent(FamilyBudget.class)) { + FamilyBudget family = method + .getAnnotation(FamilyBudget.class); + String userRole = family.userRole(); + int budgetLimit = family.budgetLimit(); + if (userRole.equals(role)) { + if(spend<=budgetLimit){ + method.invoke(FamilyMember.class.newInstance(), + budgetLimit, spend); + }else{ + System.out.println("Budget Limit Over"); + } + } + } + } + } catch (Exception e) { + e.printStackTrace(); + } + testCases--; + } + } +} +Here, we partially define an annotation, FamilyBudget and a class, FamilyMember. In this problem, +we give the user role and the amount of money that a user spends as inputs. Based on the user role, +you have to call the appropriate method in the FamilyMember class. If the amount of money spent is +over the budget limit for that user role, it prints "Budget Limit Over", without quotes. + +Your task is to complete the FamilyBudget annotation and the FamilyMember class so that the +Solution class works perfectly with the defined constraints. + +Note: You must complete the 5 incomplete lines in the editor, don't change any other lines. +To restore the original code, click on the top-left button on the editor and create a new buffer. + +Input Format + +The first line of input contains an integer N representing the total number of test cases. +Each test case contains a string and an integer separated by a space on a single line in the following format: + +UserRole MoneySpend +Constraints + +2≤N≤10 +0≤MoneySpend≤200 +|UserRole|=6 + +Name contains only lowercase English letters. + +Output Format + +Based on the user role and budget outputs, output the contents of the certain method. +If the amount of money spent is over the budget limit, then output "Budget Limit Over", without quotes. + +Sample Input + +3 +SENIOR 75 +JUNIOR 45 +SENIOR 40 + +Sample Output + +Senior Member +Spend: 75 +Budget Left: 25 +Junior Member +Spend: 45 +Budget Left: 5 +Senior Member +Spend: 40 +Budget Left: 60 + +*/ + +import java.lang.annotation.*; +import java.lang.reflect.*; +import java.util.*; + +@Target(ElementType.METHOD) +@Retention(RetentionPolicy.RUNTIME) +@interface FamilyBudget { + String userRole() default "GUEST"; + int budgetLimit() default 0; +} + +class FamilyMember { + @FamilyBudget(userRole = "SENIOR", budgetLimit = 100) + public void seniorMember(int budget, int moneySpend) { + System.out.println("Senior Member"); + System.out.println("Spend: " + moneySpend); + System.out.println("Budget Left: " + (budget - moneySpend)); + } + + @FamilyBudget(userRole = "JUNIOR", budgetLimit = 50) + public void juniorUser(int budget, int moneySpend) { + System.out.println("Junior Member"); + System.out.println("Spend: " + moneySpend); + System.out.println("Budget Left: " + (budget - moneySpend)); + } +} + +public class JavaAnnotations { + public static void main(String[] args) { + Scanner in = new Scanner(System.in); + int testCases = Integer.parseInt(in.nextLine()); + while (testCases > 0) { + String role = in.next(); + int spend = in.nextInt(); + try { + Class annotatedClass = FamilyMember.class; + Method[] methods = annotatedClass.getMethods(); + for (Method method : methods) { + if (method.isAnnotationPresent(FamilyBudget.class)) { + FamilyBudget family = method + .getAnnotation(FamilyBudget.class); + String userRole = family.userRole(); + int budgetLimit = family.budgetLimit(); + if (userRole.equals(role)) { + if(budgetLimit>=spend){ + method.invoke(FamilyMember.class.newInstance(), + budgetLimit, spend); + }else{ + System.out.println("Budget Limit Over"); + } + } + } + } + } catch (Exception e) { + e.printStackTrace(); + } + testCases--; + } + } +} \ No newline at end of file diff --git a/Java/Advanced/JavaFactory.java b/Java/Advanced/JavaFactory.java new file mode 100644 index 0000000..fd77cc3 --- /dev/null +++ b/Java/Advanced/JavaFactory.java @@ -0,0 +1,33 @@ +/* Java Factory + +According to Wikipedia, a factory is simply an object that returns another object from some other method call, which is assumed to be "new". + +In this problem, you are given an interface Food. There are two classes Pizza and Cake which implement the Food interface, and they both contain a method getType(). + +The main function in the Main class creates an instance of the FoodFactory class. The FoodFactory class contains a method getFood(String) that returns a new instance of Pizza or Cake according to its parameter. + +You are given the partially completed code in the editor. Please complete the FoodFactory class. + +Sample Input 1 + +cake +Sample Output 1 + +The factory returned class Cake +Someone ordered a Dessert! +Sample Input 2 + +pizza +Sample Output 2 + +The factory returned class Pizza +Someone ordered Fast Food! + +*/ + +if(order.equals("cake")){ + + return new Cake(); +}else{ + return new Pizza(); +} \ No newline at end of file diff --git a/Java/Advanced/JavaReflection.java b/Java/Advanced/JavaReflection.java new file mode 100644 index 0000000..2f2c073 --- /dev/null +++ b/Java/Advanced/JavaReflection.java @@ -0,0 +1,59 @@ +/* Java Reflection - Attributes + +JAVA reflection is a very powerful tool to inspect the attributes of a class in runtime. For example, +we can retrieve the list of public fields of a class using getDeclaredMethods(). + +In this problem, you will be given a class Solution in the editor. You have to fill in the incompleted +lines so that it prints all the methods of another class called Student in alphabetical order. +We will append your code with the Student class before running it. The Student class looks like this: + +class Student{ + private String name; + private String id; + private String email; + + public String getName() { + return name; + } + public void setId(String id) { + this.id = id; + } + public void setEmail(String email) { + this.email = email; + } + public void anothermethod(){ } + ...... + ...... + some more methods + ...... + } +You have to print all the methods of the student class in alphabetical order like this: + +anothermethod +getName +setEmail +setId +...... +...... +some more methods +...... +There is no sample input/output for this problem. If you press "Run Code", it will compile it, but it won't show any outputs. + +*/ + +public class JavaReflection { + + public static void main(String[] args){ + Class student = new Student().getClass(); + Method[] methods = student.getDeclaredMethods(); + + ArrayList methodList = new ArrayList<>(); + for(Method method:methods){ + methodList.add(method.getName()); + } + Collections.sort(methodList); + for(String name: methodList){ + System.out.println(name); + } + } +} \ No newline at end of file diff --git a/Java/Advanced/JavaVarargs.java b/Java/Advanced/JavaVarargs.java new file mode 100644 index 0000000..3d4a824 --- /dev/null +++ b/Java/Advanced/JavaVarargs.java @@ -0,0 +1,50 @@ +/* Java Varargs - Simple Addition + +You are given a class Solution and its main method in the editor. +Your task is to create the class Add and the required methods so that the code prints the sum of the numbers +passed to the function add. + +Note: Your add method in the Add class must print the sum as given in the Sample Output + +Input Format + +There are six lines of input, each containing an integer. + +Output Format + +There will be only four lines of output. Each line contains the sum of the integers passed as the parameters +to add in the main method. + +Sample Input + +1 +2 +3 +4 +5 +6 +Sample Output + +1+2=3 +1+2+3=6 +1+2+3+4+5=15 +1+2+3+4+5+6=21 + +*/ + +class Add +{ + static void add(int...numbers) + { + int sum = 0; + for(int num:numbers) + { + if(sum !=0){ + System.out.print("+"); + } + sum+=num; + System.out.print(num); + } + System.out.println("="+sum); + } +} \ No newline at end of file diff --git a/Java/Advanced/PrimeChecker.java b/Java/Advanced/PrimeChecker.java new file mode 100644 index 0000000..9b5c086 --- /dev/null +++ b/Java/Advanced/PrimeChecker.java @@ -0,0 +1,60 @@ +/* Prime Checker + +You are given a class Solution and its main method in the editor. Your task is to create a +class Prime which contains a single method checkPrime so that the code prints only prime numbers as the output. + +Please do not use method overloading! + +Note: You may get a compile time error in this problem due to the below statement: + + BufferedReader br=new BufferedReader(new InputStreamReader(in)); +This was added intentionally, and you have to figure out a way to get rid of the error. + +Input Format + +There are only five lines of input, each containing one integer. + +Output Format + +There will be only four lines of output. Each line contains only prime numbers depending +upon the parameters passed to checkPrime in the main method of the class Solution. In case there is +no prime number, then a blank line should be printed. + +Sample Input + + 2 + 1 + 3 + 4 + 5 + +Sample Output + +2 +2 +2 3 +2 3 5 + +*/ + +import static java.lang.System.in; +class Prime +{ + public boolean isPrime(int num) + { + if (num == 1) return false; + for(int i = 2;i() { + @Override + public int compare(Object a1, Object a2) { + BigDecimal bigDec1 = new BigDecimal((String)a1); + BigDecimal bigDec2 = new BigDecimal((String)a2); + return bigDec2.compareTo(bigDec1); + } + }); + + for(int i=0;ilastJumpPos && gameArray[lowRange-1].equals("0") && (lowRange+jumpLength) > range+1 ){ + lowRange--; + } + currentPos = lowRange; + for(int i = currentPos;i<=range;i++){ + if((i+jumpLength)=gameArray.length || (i+1)>=gameArray.length){ + didWin = true; + break; + } + } + + return didWin; + } + + public static void main(String[] args) { + + Scanner sc = new Scanner(System.in); + int numCases = sc.nextInt(); + for(int i=0;ilargestSum){ + largestSum=sum; + } + } + } + } + System.out.println(largestSum); + } +} diff --git a/Java/Collections/JavaArrayList.java b/Java/Collections/JavaArrayList.java new file mode 100644 index 0000000..4527190 --- /dev/null +++ b/Java/Collections/JavaArrayList.java @@ -0,0 +1,88 @@ +/* Java Arraylist + +Sometimes it's better to use dynamic size arrays. Java's Arraylist can provide you this feature. +Try to solve this problem using Arraylist. + +You are given n lines. In each line there are zero or more integers. You need to answer a few queries +where you need to tell the number located in yth position of xth line. + +Take your input from System.in. + +Input Format +The first line has an integer n. In each of the next n lines there will be an integer d denoting number +of integers on that line and then there will be d space-separated integers. In the next line there will +be an integer q denoting number of queries. Each query will consist of two integers x and y. + +Constraints + +1<=n<=20000 +0<=d<=50000 +1<=q<=1000 +1<=x,y<=n + +Each number will fit in signed integer. +Total number of integers in n lines will not cross 100000. + +Output Format +In each line, output the number located in yth position of xth line. If there is no such position, just print "ERROR!" + +Sample Input + +5 +5 41 77 74 22 44 +1 12 +4 37 34 36 52 +0 +3 20 22 33 +5 +1 3 +3 4 +3 1 +4 3 +5 5 + +Sample Output + +74 +52 +37 +ERROR! +ERROR! + +*/ + +import java.io.*; +import java.util.*; +import java.text.*; +import java.math.*; +import java.util.regex.*; + +public class Solution { + + public static void main(String[] args) { + + Scanner sc = new Scanner(System.in); + int numLines = Integer.parseInt(sc.nextLine()); + ArrayList listArray = new ArrayList(); + for(int i = 0;i intArrayList = new ArrayList(); + for(int j=0;j desc = new Comparator() { + + @Override + public int compare(Player o1, Player o2) { + + if(o1.score==o2.score){ + return o2.name.compareTo(o1.name); + } + return o1.score>o2.score?-1:1; + } + }; + +} \ No newline at end of file diff --git a/Java/Collections/JavaDeque.java b/Java/Collections/JavaDeque.java new file mode 100644 index 0000000..05d35e3 --- /dev/null +++ b/Java/Collections/JavaDeque.java @@ -0,0 +1,73 @@ +/* Java Deque + +In computer science, a double-ended queue (dequeue, often abbreviated to deque, pronounced deck) is an +abstract data type that generalizes a queue, for which elements can be added to or removed from either the +front (head) or back (tail). + +Deque interfaces can be implemented using various types of collections such as LinkedList or ArrayDeque +classes. For example, deque can be declared as: + +Deque deque = new LinkedList<>(); +or +Deque deque = new ArrayDeque<>(); +You can find more details about Deque here. + +In this problem, you are given N integers. You need to find the maximum number of unique integers among +all the possible contiguous subarrays of size M. + +Note: Time limit is 3 second for this problem. + +Input Format + +The first line of input contains two integers N and M: representing the total number of integers and +the size of the subarray, respectively. The next line contains N space separated integers. + +Constraints + +1≤N≤100000 +1≤M≤100000 +M≤N +The numbers in the array will range between [0,10000000]. + +Output Format + +Print the maximum number of unique integers among all possible contiguous subarrays of size M separated by a space. + +Sample Input + +6 3 +5 3 5 2 3 2 + +Sample Output + +3 + +*/ + +import java.util.*; +public class test { + public static void main(String[] args) { + + Scanner in = new Scanner(System.in); + Deque deque = new ArrayDeque(); + int n = in.nextInt(); + int m = in.nextInt(); + int maxUnique = 0; + for (int i = 0; i < n; i++) { + int num = in.nextInt(); + if(i == 0){ + deque.add(num); + maxUnique++; + }else{ + if(deque.size() == m){ + deque.removeFirst(); + } + if(!deque.contains(num) && maxUniqueclosingParan = Arrays.asList("}", ")", "]"); + boolean isBallanced = true; + ArrayList stack = new ArrayList(); + if(paranString.length()>0){ + for(int i = 0;i0) isBallanced = false; + return isBallanced; + } + public static void main(String[] args) { + Scanner sc = new Scanner(System.in); + while(sc.hasNext()){ + if(isBallanced(sc.nextLine())){ + System.out.println("true"); + }else{ + System.out.println("false"); + } + } + + } +} \ No newline at end of file diff --git a/Java/Exception Handling/JavaExceptionHandling.java b/Java/Exception Handling/JavaExceptionHandling.java new file mode 100644 index 0000000..914489f --- /dev/null +++ b/Java/Exception Handling/JavaExceptionHandling.java @@ -0,0 +1,23 @@ +/* Java Exception Handling +Create a class myCalculator which consists of a single method power(int,int). This method takes two integers, +n and p, as parameters and finds np. If either n or p is negative, then the method must throw an exception +which says "n and p should be non-negative". + +Please read the partially completed code in the editor and complete it. Your code mustn't be public. + +No need to worry about constraints, there won't be any overflow if your code is correct. + +*/ + +class JavaExceptionHandling +{ + public int power(int n, int p) throws Exception + { + if(n<0 || p<0){ + throw new Exception("n and p should be non-negative"); + } + return (int) Math.pow(n,p); + + } + +} \ No newline at end of file diff --git a/Java/Exception Handling/JavaExceptionHandlingTryCatch.java b/Java/Exception Handling/JavaExceptionHandlingTryCatch.java new file mode 100644 index 0000000..072ae80 --- /dev/null +++ b/Java/Exception Handling/JavaExceptionHandlingTryCatch.java @@ -0,0 +1,74 @@ +/* Java Exception Handling Try Catch +Exception handling is the process of responding to the occurrence, during computation, of +exceptions – anomalous or exceptional conditions requiring special processing – often changing +the normal flow of program execution. (Wikipedia) +Java has built-in mechanism to handle exceptions. Using the try statement we can test a block +of code for errors. The catch block contains the code that says what to do if exception occurs. + +This problem will test your knowledge on try-catch block. + +You will be given two integers x and y as input, you have to compute x/y. If x and y are +not 32 bit signed integers or if y is zero, exception will occur and you have to report it. +Read sample Input/Output to know what to report in case of exceptions. + +Sample Input 1: + +10 +3 + +Sample Output 1: + +3 + +Sample Input 2: + +10 +Hello + +Sample Output 2: + +java.util.InputMismatchException + +Sample Input 3: + +10 +0 + +Sample Output 3: + +java.lang.ArithmeticException: / by zero + +Sample Input 4: + +23.323 +0 +Sample Output 4: + +java.util.InputMismatchException +*/ +import java.io.*; +import java.util.*; +import java.text.*; +import java.math.*; +import java.util.regex.*; + +public class JavaExceptionHanldingTryCatch { + + public static void main(String[] args) { + /* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */ + Scanner sc = new Scanner(System.in); + try{ + try{ + int x = new Integer(sc.nextInt()); + int y = new Integer(sc.nextInt()); + System.out.println(""+(x/y)); + }catch (InputMismatchException e){ + System.out.println("java.util.InputMismatchException"); + } + + }catch(Exception e){ + System.out.println(e); + } + + } +} \ No newline at end of file diff --git a/Java/Introduction/JavaDatatypes.java b/Java/Introduction/JavaDatatypes.java new file mode 100644 index 0000000..b80ecee --- /dev/null +++ b/Java/Introduction/JavaDatatypes.java @@ -0,0 +1,66 @@ +/* Java Datatypes + +Java has 8 Primitive Data Types; they are char, boolean, byte, short, int, long, float, and double. In this problem we are only concerned about integer datatypes used to hold integer values (byte, short, int, long). Let's take a closer look at them: + +byte data type is an 8-bit signed integer. +short data type is an 16-bit signed integer. +int data type is an 32-bit signed integer. +long data type is an 64-bit signed integer. +(Reference: https://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html) + +Given an integer number, you have to determine which of these datatypes you can use to store that number. +If there are multiple suitable datatypes, list them all in the order above. + +Input Format + +The first line will contain an integer T, which denotes the number of inputs that will follow. +Each of the next T lines will contain an integer n. The number can be arbitrarily large or small! + +Output Format + +For each n, list all the datatypes it can be fitted into ordered by the size of the datatype. +If it can't be fitted into any of these datatypes, print "n can't be fitted anywhere." See the sample output for the exact +formatting. + +*/ + +import java.io.*; +import java.util.*; +import java.text.*; +import java.math.*; +import java.util.regex.*; + +public class JavaDatatypes { + + static String whoCanFitTheNumber(String numString) + { + String answer = ""; + try{ + long num = Long.parseLong(numString); + answer = numString + " can be fitted in:\n"; + if((num<=Byte.MAX_VALUE) && (num>=Byte.MIN_VALUE)){ + answer = answer.concat("* byte\n* short\n* int\n* long"); + }else if((num <= Short.MAX_VALUE) && (num >= Short.MIN_VALUE)){ + answer = answer.concat("* short\n* int\n* long"); + }else if((num <= Integer.MAX_VALUE) && (num >= Integer.MIN_VALUE)){ + answer = answer.concat("* int\n* long"); + }else{ + answer = answer.concat("* long"); + } + }catch (NumberFormatException e){ + answer = numString+" can't be fitted anywhere."; + } + return answer; + } + public static void main(String[] args) { + /* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. + */ + Scanner scanner = new Scanner(System.in); + int numTestCases = scanner.nextInt() ; + scanner.nextLine(); + for(int i=0; i42 +element[1]=>10 +element[2]=>"###" +element[3]=>"Hello" +element[4]=>"Java" +You have to modify the func method by editing at most 2 lines so that the code only prints the elements +after the special string "###". For the sample above the output will be: + +Hello +Java +Note: The stdin doesn't contain the string "###", it is added in the main method. +*/ + +import java.util.*; +public class JavaIterator +{ + static Iterator func(ArrayList mylist) + { + Iterator it=mylist.iterator(); + while(it.hasNext()) + { + Object element = it.next(); + if(element instanceof String) //Hints: use instanceof operator + break; + } + return it; + + } + + public static void main(String []argh) + { + ArrayList mylist = new ArrayList(); + Scanner sc=new Scanner(System.in); + int n=sc.nextInt(); + int m=sc.nextInt(); + for(int i=0;i0){ + String input = in.nextLine(); + Matcher m = r.matcher(input); + boolean findMatch = true; + while(m.find( )){ + input = input.replaceAll(pattern,"$1"); + findMatch = false; + } + System.out.println(input); + testCases--; + } + } +} + diff --git a/Java/Strings/JavaRegex3.java b/Java/Strings/JavaRegex3.java new file mode 100644 index 0000000..ce38539 --- /dev/null +++ b/Java/Strings/JavaRegex3.java @@ -0,0 +1,45 @@ +/* +Java Regex 3 - Username Checker + +Regular expressions (regexp) help us match or search for patterns in strings. In this problem, you will be given a username. +Your task is to check whether that username is valid. A valid username will have the following properties: + +The username can contain alphanumeric characters and/or underscores(_). +The username must start with an alphabetic character. +8 ≤ |Username| ≤ 30. +To simplify your task, we have provided a portion of the code in the editor. You just need to write down the regex pattern +which will be used to validate the username input. + +Input Format + +The first line of input contains an integer N, representing the number of testcases. Each of the next N lines contains a +string that represents a username. + +Constraints + +The username consists of any printable characters. + +1≤N≤50 +Output Format + +For each username, output Valid if the username is valid; otherwise, output Invalid. + +Sample Input + +4 +alpha_naheed +xahidbuffon +nagib@007 +123Swakkhar + +Sample Output + +Valid +Valid +Invalid +Invalid +*/ + + + String pattern = "^[a-zA-Z][a-zA-Z0-9_]{7,29}$"; + diff --git a/Java/Strings/JavaStringCompare.java b/Java/Strings/JavaStringCompare.java new file mode 100644 index 0000000..70f510e --- /dev/null +++ b/Java/Strings/JavaStringCompare.java @@ -0,0 +1,47 @@ +/* Java String Compare + +Given a string, find out the lexicographically smallest and largest substring of length k. + +[Note: Lexicographic order is also known as alphabetic order dictionary order. So "ball" is smaller than "cat", "dog" is smaller +than "dorm". Capital letter always comes before smaller letter, so "Happy" is smaller than "happy" and "Zoo" is smaller than "ball".] + +Input Format + +First line will consist a string containing english alphabets which has at most 1000 characters. +2nd line will consist an integer k. + +Output Format + +In the first line print the lexicographically minimum substring. In the second line print the lexicographically maximum substring. + +*/ + +import java.io.*; +import java.util.*; +import java.text.*; +import java.math.*; +import java.util.regex.*; + +public class Solution { + + public static void main(String[] args) { + Scanner sc = new Scanner(System.in); + String inputString = sc.nextLine(); + int length = sc.nextInt(); + String smallest=""; + String largest=""; + for(int i = 0;i<=inputString.length()-length;i++){ + String subString = inputString.substring(i,i+length); + if(i == 0){ + smallest = subString; + } + if(subString.compareTo(largest)>0){ + largest = subString; + }else if(subString.compareTo(smallest)<0) + smallest = subString; + } + System.out.println(smallest); + System.out.println(largest); + + } +} \ No newline at end of file diff --git a/Java/Strings/JavaStringReverse.java b/Java/Strings/JavaStringReverse.java new file mode 100644 index 0000000..424485e --- /dev/null +++ b/Java/Strings/JavaStringReverse.java @@ -0,0 +1,46 @@ +/* Java String Reverse + +Problem Statement + +A palindrome is a word, phrase, number, or other sequence of characters which reads the same backward or forward.(Wikipedia) +Given a string A, print "Yes" if it is a palindrome, print "No" otherwise. The strings will consist lower case english letters only. +The strings will have at most 50 characters. + +Some examples of palindromes are "madam", "anna", "reviver". + +Sample Input + +madam +Sample Output + +Yes +*/ + +import java.io.*; +import java.util.*; + +public class JavaStringReverse { + + public static boolean isPalindrome(String word) + { + boolean isPalindrome = true; + + for(int i = 0;i<(int)word.length()/2;i++) + { + if(word.charAt(i) != word.charAt(word.length()-1-i)){ + isPalindrome = false; + break; + + } + } + + return isPalindrome; + } + public static void main(String[] args) { + + Scanner sc=new Scanner(System.in); + String A=sc.next(); + System.out.println(isPalindrome(A)?"Yes":"No"); + + } +} \ No newline at end of file diff --git a/Java/Strings/JavaStringToken.java b/Java/Strings/JavaStringToken.java new file mode 100644 index 0000000..1309b54 --- /dev/null +++ b/Java/Strings/JavaStringToken.java @@ -0,0 +1,64 @@ +/* Java String Token + +Given a string, find number of words in that string. For this problem a word is defined by a string of one or more +english alphabets. + +There are multiple ways to tokenize a string in java, learn how to tokenize a string in java and demonstrate your +skill by solving this problem! + +Input Format +A string not more than 400000 characters long. The string can be defined by following regular expression: + +[A-Za-z !,?.\_'@]+ +That means the string will only contain english alphabets, blank spaces and this characters: "!,?._'@". + +Output Format +In the first line, print number of words n in the string. The words don't need to be unique. In the next n lines, +print all the words you found in the order they appeared in the input. + +Sample Input + +He is a very very good boy, isn't he? +Sample Output + +10 +He +is +a +very +very +good +boy +isn +t +he +*/ + +import java.io.*; +import java.util.*; +import java.text.*; +import java.math.*; +import java.util.regex.*; + +public class JavaStringToken { + + public static void main(String[] args) { + Scanner sc = new Scanner(System.in); + + if (!sc.hasNext()){ + System.out.println(0); + }else { + String input=sc.nextLine(); + String[]a = input.trim().split("[ !,?._'@]+"); + ArrayListlistOfStrings =new ArrayList(Arrays.asList(a)); + System.out.println(listOfStrings.size()); + + for(String str:listOfStrings){ + System.out.println(str); + } + } + + + + } +} \ No newline at end of file diff --git a/Java/Strings/JavaStrings.java b/Java/Strings/JavaStrings.java new file mode 100644 index 0000000..bff3b3f --- /dev/null +++ b/Java/Strings/JavaStrings.java @@ -0,0 +1,44 @@ +/* Java Strings +Today we will learn about java strings. Your task is simple, given a string, find out the lexicographically smallest and largest substring of length k. + +[Note: Lexicographic order is also known as alphabetic order dictionary order. So "ball" is smaller than "cat", "dog" is smaller than "dorm". Capital letter always comes before smaller letter, so "Happy" is smaller than "happy" and "Zoo" is smaller than "ball".] + +Input Format + +First line will consist a string containing english alphabets which has at most 1000 characters. 2nd line will consist an integer k. + +Output Format + +In the first line print the lexicographically minimum substring. In the second line print the lexicographically maximum substring. +*/ + +import java.io.*; +import java.util.*; +import java.text.*; +import java.math.*; +import java.util.regex.*; + +public class JavaStrings { + + public static void main(String[] args) { + + Scanner sc = new Scanner(System.in); + String inputString = sc.nextLine(); + int length = sc.nextInt(); + String smallest=""; + String largest=""; + for(int i = 0;i<=inputString.length()-length;i++){ + String subString = inputString.substring(i,i+length); + if(i == 0){ + smallest = subString; + } + if(subString.compareTo(largest)>0){ + largest = subString; + }else if(subString.compareTo(smallest)<0) + smallest = subString; + } + System.out.println(smallest); + System.out.println(largest); + + } +} \ No newline at end of file diff --git a/Java/Strings/PatternSyntaxChecker.java b/Java/Strings/PatternSyntaxChecker.java new file mode 100644 index 0000000..46a9a77 --- /dev/null +++ b/Java/Strings/PatternSyntaxChecker.java @@ -0,0 +1,58 @@ +/* Patern Syntax Checker + +Using Regex, we can easily match or search for patterns in a text. Before searching for a pattern, +we have to specify one using some well-defined syntax. + +In this problem, you are given a pattern. You have to check whether the syntax of the given pattern is valid. + +Note: In this problem, a regex is only valid if you can compile it using the Pattern.compile method. + +Input Format + +The first line of input contains an integer N, denoting the number of testcases. The next N lines contain a +string of any printable characters representing the pattern of a regex. + +Output Format + +For each testcase, print "Valid" if the syntax of the given pattern is correct. Otherwise, print "Invalid". +Do not print the quotes. + +Sample Input + +3 +([A-Z])(.+) +[AZ[a-z](a-z) +batcatpat(nat + +Sample Output + +Valid +Invalid +Invalid + +*/ + + +import java.util.Scanner; +import java.util.regex.*; + +public class PatternSyntaxChecker +{ + public static void main(String[] args){ + Scanner in = new Scanner(System.in); + int testCases = Integer.parseInt(in.nextLine()); + while(testCases>0){ + testCase--; + String pattern = in.nextLine(); + //Write your code + try{ + Pattern.compile(pattern); + System.out.println("Valid"); + }catch(PatternSyntaxException e){ + System.out.println("Invalid"); + } + + + } + } +} diff --git a/Java/Strings/TagContentExtractor.java b/Java/Strings/TagContentExtractor.java new file mode 100644 index 0000000..7b6dbe5 --- /dev/null +++ b/Java/Strings/TagContentExtractor.java @@ -0,0 +1,94 @@ +/* +Tag Content Extractor + +In a tag based language, like XML or HTML, contents are enclosed by a start tag and an end tag. For example: + +contents +In this problem, you will be given a text in a tag based language. Your task is to parse this text and retrieve +the contents which are enclosed by well organized tag sequences. Well organized tags maintain the following constraints: + +The name of the start and end tag must be same. The following HTML code is not valid: + +

Hello World

+Tag can be nested, but there will be no content in between the nested tags. The following code is not valid: + +

contentsinvalid

+Tags can consist of any printable characters. + +Input Format + +The first line of input contains a single integer N, representing the number of lines. The next N lines +contains a line of text. + +Constraints + +1<=N<=100 +Each line contains at most 104 printable characters. The total number of characters in all test cases will not exceed 106. + +Output Format + +For each line, print the valid content enclosed by proper tags. If there is multiple valid content in a test case, +print out each of the valid content on separate lines. If no valid content is found in a test case, print "None" without quotes. + +Sample Input + +4 +

Nayeem loves counseling

+

Sanjay has no watch

So wait for a while +safat codes like a ninja +Imtiaz has a secret crush + +Sample Output + +Nayeem loves counseling +Sanjay has no watch +So wait for a while +None +Imtiaz has a secret crush +*/ + + +import java.io.*; +import java.util.*; +import java.text.*; +import java.math.*; +import java.util.regex.*; + +public class TagContentExtractor{ + + public static void main(String[] args){ + + Scanner in = new Scanner(System.in); + int testCases = Integer.parseInt(in.nextLine()); + String regexPatern = "(<[^>]*>)"; + Pattern stringPatern = Pattern.compile(regexPatern); + while(testCases>0){ + String line = in.nextLine(); + int pos = 0; + Matcher m = stringPatern.matcher(line); + String previousHTMLTag = null; + int previousTagPos = -1; + boolean didFind = false; + while(m.find()) + { + String htmlTag = line.substring(m.start(),m.end()); + if(htmlTag.charAt(1) != '/') + { + previousHTMLTag = htmlTag; + previousTagPos = m.end(); + }else if(htmlTag.charAt(1) == '/' && previousHTMLTag != null){ + if(previousHTMLTag.substring(1).equals(htmlTag.substring(2))&&previousHTMLTag.length()>2 && m.start()>previousTagPos+1){ + System.out.println(line.substring(previousTagPos,m.start())); + didFind = true; + } + previousHTMLTag = null; + } + + } + System.out.print(didFind?"":"None\n"); + testCases--; + } + + } +} + diff --git a/README.md b/README.md new file mode 100644 index 0000000..33477d1 --- /dev/null +++ b/README.md @@ -0,0 +1 @@ +My Solutions to Hackerrank.com Challenges \ No newline at end of file