From 9c849e026fbd100434aa32b622a00f360a935816 Mon Sep 17 00:00:00 2001 From: Yan Zverev Date: Tue, 7 Jul 2015 11:51:09 -0400 Subject: [PATCH 01/46] Another set of solutions --- Algorithms/Bit Manipulation/FlippingBits.m | 33 ++++++++ Algorithms/Bit Manipulation/LonlyInteger.java | 43 ++++++++++ Algorithms/Bit Manipulation/MaximizingXOR.m | 41 +++++++++ Algorithms/Code Golf/F.java | 12 +++ Algorithms/Implementation/FindDigits.java | 60 ++++++++++++++ Algorithms/Implementation/UtopianTree.m | 70 ++++++++++++++++ Algorithms/Sorting/InsertionSort.java | 83 +++++++++++++++++++ Algorithms/Strings/AlternatingCharacters.java | 51 ++++++++++++ Algorithms/Strings/FunnyStrings.java | 47 +++++++++++ Algorithms/Strings/Pangrams.java | 40 +++++++++ Algorithms/Warmup/DiagonalDifference.java | 60 ++++++++++++++ Algorithms/Warmup/PlusMinus.java | 56 +++++++++++++ Algorithms/Warmup/StairCase.java | 42 ++++++++++ 13 files changed, 638 insertions(+) create mode 100644 Algorithms/Bit Manipulation/FlippingBits.m create mode 100644 Algorithms/Bit Manipulation/LonlyInteger.java create mode 100644 Algorithms/Bit Manipulation/MaximizingXOR.m create mode 100644 Algorithms/Code Golf/F.java create mode 100644 Algorithms/Implementation/FindDigits.java create mode 100644 Algorithms/Implementation/UtopianTree.m create mode 100644 Algorithms/Sorting/InsertionSort.java create mode 100644 Algorithms/Strings/AlternatingCharacters.java create mode 100644 Algorithms/Strings/FunnyStrings.java create mode 100644 Algorithms/Strings/Pangrams.java create mode 100644 Algorithms/Warmup/DiagonalDifference.java create mode 100644 Algorithms/Warmup/PlusMinus.java create mode 100644 Algorithms/Warmup/StairCase.java 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/Code Golf/F.java b/Algorithms/Code Golf/F.java new file mode 100644 index 0000000..dbe4713 --- /dev/null +++ b/Algorithms/Code Golf/F.java @@ -0,0 +1,12 @@ +/* Fizz Buzz +Write a short program that prints (to STDOUT) the numbers from 1 to 100. But for multiples of three print "Fizz" instead of the number and for the multiples of five print "Buzz". For numbers which are multiples of both three and five print "FizzBuzz". + +The goal is to write the shortest code possible. + +Scoring: Your score is (200 - number of characters in your source code)/10 +*/ + +/* The solutions is 131 characters */ + +class F{static public void main(String[]b){for(int i=0;i<100;System.out.println((++i%3<1?"Fizz":"")+(i%5<1?"Buzz":i%3<1?"":i)));}} + 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 + +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=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;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;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/StairCase.java b/Algorithms/Warmup/StairCase.java new file mode 100644 index 0000000..b2fecc1 --- /dev/null +++ b/Algorithms/Warmup/StairCase.java @@ -0,0 +1,42 @@ +/* Staircase +Your teacher has given you the task to draw the structure of a staircase. Being an expert programmer, you decided to make a program for the same. You are given the height of the staircase. You need to print a staircase as shown in the example. + +Input Format + +You are given an integer N depicting the height of the staircase. + +Constraints +1≤N≤100 +Output Format + +Draw a staircase of height N in the format given below. + +For example: + + # + ## + ### + #### + ##### +###### +Staircase of height 6, note that last line has 0 spaces before it. +*/ + +import java.io.*; +import java.util.*; + +public class Solution { + + public static void main(String[] args) { + + Scanner sc = new Scanner(System.in); + int num = Integer.parseInt(sc.nextLine()); + for(int j=0;j Date: Tue, 7 Jul 2015 12:09:22 -0400 Subject: [PATCH 02/46] Java Domain Solutions --- Java/Big Number/BigInteger.java | 33 ++++++++ Java/Data Structures/Java2DArray.java | 68 +++++++++++++++++ Java/Data Structures/JavaArrayList.java | 58 ++++++++++++++ Java/Data Structures/JavaStack.java | 75 +++++++++++++++++++ .../JavaExceptionHandling.java | 21 ++++++ Java/Introduction/JavaDatatypes.java | 62 +++++++++++++++ Java/Introduction/JavaEOF.java | 34 +++++++++ Java/Introduction/JavaLoops.java | 53 +++++++++++++ Java/Introduction/WelcomeToJava.java | 25 +++++++ .../JavaInheritance.java | 48 ++++++++++++ .../JavaInterface.java | 24 ++++++ Java/Strings/JavaStrings.java | 44 +++++++++++ 12 files changed, 545 insertions(+) create mode 100644 Java/Big Number/BigInteger.java create mode 100644 Java/Data Structures/Java2DArray.java create mode 100644 Java/Data Structures/JavaArrayList.java create mode 100644 Java/Data Structures/JavaStack.java create mode 100644 Java/Exception Handling/JavaExceptionHandling.java create mode 100644 Java/Introduction/JavaDatatypes.java create mode 100644 Java/Introduction/JavaEOF.java create mode 100644 Java/Introduction/JavaLoops.java create mode 100644 Java/Introduction/WelcomeToJava.java create mode 100644 Java/Object Oriented Programming/JavaInheritance.java create mode 100644 Java/Object Oriented Programming/JavaInterface.java create mode 100644 Java/Strings/JavaStrings.java diff --git a/Java/Big Number/BigInteger.java b/Java/Big Number/BigInteger.java new file mode 100644 index 0000000..41edbcc --- /dev/null +++ b/Java/Big Number/BigInteger.java @@ -0,0 +1,33 @@ +/* Java Big Integer + +In this problem you have to add and multiply huge numbers! These numbers are so big that you can't contain them in any ordinary data types like long integer. + +Use the power of Java's BigInteger class and solve this problem. + +Input Format + +There will be two lines containing two numbers, a and b. The numbers are non-negative and can have maximum 200 digits. + +Output Format + +Output two lines. The first line should contain a+b, and the second line should contain a×b. Don't print any leading zeros. +*/ +import java.io.*; +import java.util.*; +import java.text.*; +import java.math.*; +import java.util.regex.*; + +public class BigInteger { + + 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); + String numOne = sc.nextLine(); + String numTwo = sc.nextLine(); + BigInteger bigNumOne = new BigInteger(numOne); + BigInteger bigNumTwo = new BigInteger(numTwo); + System.out.println(bigNumOne.add(bigNumTwo)); + System.out.println(bigNumOne.multiply(bigNumTwo)); + } +} \ No newline at end of file diff --git a/Java/Data Structures/Java2DArray.java b/Java/Data Structures/Java2DArray.java new file mode 100644 index 0000000..9021b31 --- /dev/null +++ b/Java/Data Structures/Java2DArray.java @@ -0,0 +1,68 @@ +/* Java 2D Array +You are given a 6*6 2D array. You have to find the sum of all the hourglasses within the array. An hourglass in an array is a portion shaped like this: + +a b c + d +e f g +For example, if we create an hourglass using the number 1 within an array full of zeros, it may look like this: + +1 1 1 0 0 0 +0 1 0 0 0 0 +1 1 1 0 0 0 +0 0 0 0 0 0 +0 0 0 0 0 0 +0 0 0 0 0 0 +Actually there are many hourglasses in the array above. The three leftmost hourglasses are the following: + +1 1 1 1 1 0 1 0 0 + 1 0 0 +1 1 1 1 1 0 1 0 0 +The sum of an hourglass is the sum of all the numbers within it. The sum for the hourglasses above are 7, 4, and 2, respectively. + +In this problem you have to print the largest sum among all the hourglasses in the array. + +Input Format + +There will be exactly 6 lines, each containing 6 integers seperated by spaces. Each integer will be between -9 and 9 inclusive. + +Output Format + +Print the answer to this problem on a single line. +*/ + +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) { + /* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */ + Scanner sc = new Scanner(System.in); + String[][] numArray = new String[6][]; + int largestSum = 0; + for(int i=0; i<6; i++){ + numArray[i]=sc.nextLine().split(" "); + } + + for(int i=0;i<=3;i++){ + for(int j=0;j<=3;j++){ + int sum = Integer.parseInt(numArray[i][j])+Integer.parseInt(numArray[i][j+1])+Integer.parseInt(numArray[i][j+2])+Integer.parseInt(numArray[i+1][j+1])+Integer.parseInt(numArray[i+2][j])+Integer.parseInt(numArray[i+2][j+1])+Integer.parseInt(numArray[i+2][j+2]); + //System.out.println(sum); + if(i==0 && j==0){ + largestSum=sum; + }else{ + if(sum>largestSum){ + largestSum=sum; + } + } + } + } + + + System.out.println(largestSum); + + } +} \ No newline at end of file diff --git a/Java/Data Structures/JavaArrayList.java b/Java/Data Structures/JavaArrayList.java new file mode 100644 index 0000000..9331d04 --- /dev/null +++ b/Java/Data Structures/JavaArrayList.java @@ -0,0 +1,58 @@ +/* Java Array List +Some times its better to use dynamic size array, java Arraylist can provide you this feature. Try to solve this problem using Arraylist. + +You are given n lines. In each of the line there are zero or more integers. You need to answer few queries. In each query, you need to tell the number located in yth position of xth line. + +Take your input from System.in. + +Input Format +In the first line there will 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 seperated 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!" +*/ +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) { + /* 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 numLines = Integer.parseInt(sc.nextLine()); + ArrayList listArray = new ArrayList(); + for(int i = 0;i intArrayList = new ArrayList(); + for(int j=0;jclosingParan = 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) { + /* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */ + 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..33cf993 --- /dev/null +++ b/Java/Exception Handling/JavaExceptionHandling.java @@ -0,0 +1,21 @@ +/* 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/Introduction/JavaDatatypes.java b/Java/Introduction/JavaDatatypes.java new file mode 100644 index 0000000..7e78452 --- /dev/null +++ b/Java/Introduction/JavaDatatypes.java @@ -0,0 +1,62 @@ +/* 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; i0){ + largest = subString; + }else if(subString.compareTo(smallest)<0) + smallest = subString; + } + System.out.println(smallest); + System.out.println(largest); + + } +} \ No newline at end of file From cbbaf85e4d8f4204635a57140f8090e0fe9f43e4 Mon Sep 17 00:00:00 2001 From: Yan Zverev Date: Tue, 7 Jul 2015 12:30:21 -0400 Subject: [PATCH 03/46] More challenge and contest solutions --- .../EpicCode CodeSprint/PerfectHiring.java | 53 +++++++++++++++++++ 1 file changed, 53 insertions(+) create mode 100644 Contests/EpicCode CodeSprint/PerfectHiring.java diff --git a/Contests/EpicCode CodeSprint/PerfectHiring.java b/Contests/EpicCode CodeSprint/PerfectHiring.java new file mode 100644 index 0000000..ea53cb0 --- /dev/null +++ b/Contests/EpicCode CodeSprint/PerfectHiring.java @@ -0,0 +1,53 @@ +/* Perfect Hiring + +You are the hiring manager of a startup and you are interviewing N candidates, each having an ID numbered from 1 to N. Each candidate has a score Ai calculated from their HackerRank tests. You start with patience P and lose patience X after each interview. + +One by one candidates enter your room in the sequence of their ID numbers. To save time you decide to give a rating of (P×Ai). In the end you hire the candidate with maximum rating. Print the ID of this candidate. +NOTE: It is guaranteed that a unique ID gets selected. + +Input Format +The first line begins with 3 space-separated integers, N, P, and X. +The next line contains an array A[], containing the scores of the N candidates. + +Constraints +1≤N≤10^5 +1≤P≤10^9 +1≤X≤100 +1≤Ai≤10^9 + +Output Format +Output the ID of the Applicant who get selected. + +NOTE: ID's are numbered from 1 to N. +*/ + +import java.io.*; +import java.util.*; +import java.text.*; +import java.math.*; +import java.util.regex.*; + +public class PerfectHiring { + + public static void main(String[] args) { + + Scanner sc = new Scanner(System.in); + String[] firstLineArray = sc.nextLine().split(" "); + BigInteger numOfApplicants = new BigInteger(firstLineArray[0]); + BigInteger patienceLeft = new BigInteger(firstLineArray[1]); + BigInteger loosePatience =new BigInteger(firstLineArray[2]); + BigInteger selectedCandidate= new BigInteger("0"); + BigInteger maxRating = new BigInteger("0"); + BigInteger pos = new BigInteger("1"); + while(sc.hasNext()){ + BigInteger score = sc.nextBigInteger().multiply(patienceLeft); + if(maxRating.compareTo(score)<0){ + maxRating = score; + selectedCandidate = pos; + } + patienceLeft = patienceLeft.subtract(loosePatience); + pos = pos.add(BigInteger.ONE); + } + System.out.println(selectedCandidate); + } +} \ No newline at end of file From 8790aeb346dc94c54cfe06de8ed78905ea7f6904 Mon Sep 17 00:00:00 2001 From: Yan Zverev Date: Tue, 7 Jul 2015 20:26:12 -0400 Subject: [PATCH 04/46] Week of code 16 solution --- .../Week of Code - 16/SomeOfAbsolute.java | 62 +++++++++++++++++++ 1 file changed, 62 insertions(+) create mode 100644 Contests/Week of Code - 16/SomeOfAbsolute.java 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;i Date: Mon, 5 Oct 2015 17:19:47 -0400 Subject: [PATCH 05/46] New Challenges Solved --- Java/Algorithms/Search/IceCreamParlor.java | 54 +++++++++++++++ Java/Algorithms/Search/Pairs.java | 51 +++++++++++++++ .../Sorting/InsertionSortPart2.java | 65 +++++++++++++++++++ Java/Strings/JavaAnagrams.java | 46 +++++++++++++ 4 files changed, 216 insertions(+) create mode 100644 Java/Algorithms/Search/IceCreamParlor.java create mode 100644 Java/Algorithms/Search/Pairs.java create mode 100644 Java/Algorithms/Sorting/InsertionSortPart2.java create mode 100644 Java/Strings/JavaAnagrams.java diff --git a/Java/Algorithms/Search/IceCreamParlor.java b/Java/Algorithms/Search/IceCreamParlor.java new file mode 100644 index 0000000..496a2b2 --- /dev/null +++ b/Java/Algorithms/Search/IceCreamParlor.java @@ -0,0 +1,54 @@ +/* Ice Cream Parlor + +Sunny and Johnny together have M dollars they want to spend on ice cream. The parlor offers N flavors, and they want to choose two flavors so that they end up spending the whole amount. + +You are given the cost of these flavors. The cost of the ith flavor is denoted by ci. You have to display the indices of the two flavors whose sum is M. + +Input Format + +The first line of the input contains T; T test cases follow. +Each test case follows the format detailed below: The first line contains M. The second line contains N. The third line contains N space-separated integers denoting the price of each flavor. Here, the ith integer denotes ci. + +Output Format + +Output two integers, each of which is a valid index of a flavor. The lower index must be printed first. Indices are indexed from 1 to N. + +*/ + +import java.io.*; +import java.util.*; + +public class IceCreamParlor { + + public static void printCombination(ArrayList listArray, int money) + { + int startPos = 0; + while(startPos 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/Java/Algorithms/Sorting/InsertionSortPart2.java b/Java/Algorithms/Sorting/InsertionSortPart2.java new file mode 100644 index 0000000..4c142a3 --- /dev/null +++ b/Java/Algorithms/Sorting/InsertionSortPart2.java @@ -0,0 +1,65 @@ +/* Insertion Sort Part 2 +In Insertion Sort Part 1, you sorted one element into an array. Using the same approach repeatedly, can you sort an entire unsorted array? + +Guideline: You already can place an element into a sorted array. How can you use that code to build up a sorted array, one element at a time? Note that in the first step, when you consider an element with just the first element - that is already "sorted" since there's nothing to its left that is smaller. + +In this challenge, don't print every time you move an element. Instead, print the array after each iteration of the insertion-sort, i.e., whenever the next element is placed at its correct position. + +Since the array composed of just the first element is already "sorted", begin printing from the second element and on. + +Input Format +There will be two lines of input: + +s - the size of the array +ar - a list of numbers that makes up the array +Output Format +On each line, output the entire array at every iteration. +*/ + +import java.io.*; +import java.util.*; + +public class InsertionSortPart2 { + + public static void insertionSortPart2(int[] ar) + { + // Fill up the code for the required logic here + // Manipulate the array as required + // The code for Input/Output is already provided + int pos = 1; + while (pos < ar.length){ + int currentPos = pos; + for(int i = pos-1; i>=0;i--){ + if(ar[currentPos] Date: Mon, 5 Oct 2015 17:22:58 -0400 Subject: [PATCH 06/46] Folder Updates --- {Java/Algorithms => Algorithms}/Search/IceCreamParlor.java | 0 {Java/Algorithms => Algorithms}/Search/Pairs.java | 0 {Java/Algorithms => Algorithms}/Sorting/InsertionSortPart2.java | 0 3 files changed, 0 insertions(+), 0 deletions(-) rename {Java/Algorithms => Algorithms}/Search/IceCreamParlor.java (100%) rename {Java/Algorithms => Algorithms}/Search/Pairs.java (100%) rename {Java/Algorithms => Algorithms}/Sorting/InsertionSortPart2.java (100%) diff --git a/Java/Algorithms/Search/IceCreamParlor.java b/Algorithms/Search/IceCreamParlor.java similarity index 100% rename from Java/Algorithms/Search/IceCreamParlor.java rename to Algorithms/Search/IceCreamParlor.java diff --git a/Java/Algorithms/Search/Pairs.java b/Algorithms/Search/Pairs.java similarity index 100% rename from Java/Algorithms/Search/Pairs.java rename to Algorithms/Search/Pairs.java diff --git a/Java/Algorithms/Sorting/InsertionSortPart2.java b/Algorithms/Sorting/InsertionSortPart2.java similarity index 100% rename from Java/Algorithms/Sorting/InsertionSortPart2.java rename to Algorithms/Sorting/InsertionSortPart2.java From 95af6bfa0eac7358a2c6f890287f4f26587d0012 Mon Sep 17 00:00:00 2001 From: "yanz67@gmail.com" Date: Tue, 6 Oct 2015 17:17:22 -0400 Subject: [PATCH 07/46] Added TaumAndBday Challenge --- Algorithms/Implementation/TaumAndBday.java | 47 ++++++++++++++++++++++ 1 file changed, 47 insertions(+) create mode 100644 Algorithms/Implementation/TaumAndBday.java 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 Date: Tue, 6 Oct 2015 17:47:24 -0400 Subject: [PATCH 08/46] Flowers Challenge --- Algorithms/Greedy/Flowers.java | 44 ++++++++++++++++++++++++++++++++++ 1 file changed, 44 insertions(+) create mode 100644 Algorithms/Greedy/Flowers.java diff --git a/Algorithms/Greedy/Flowers.java b/Algorithms/Greedy/Flowers.java new file mode 100644 index 0000000..c55fa88 --- /dev/null +++ b/Algorithms/Greedy/Flowers.java @@ -0,0 +1,44 @@ +/* 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; i Date: Wed, 7 Oct 2015 11:01:08 -0400 Subject: [PATCH 09/46] Flowers --- Algorithms/Greedy/Flowers.java | 2 ++ 1 file changed, 2 insertions(+) diff --git a/Algorithms/Greedy/Flowers.java b/Algorithms/Greedy/Flowers.java index c55fa88..50400b5 100644 --- a/Algorithms/Greedy/Flowers.java +++ b/Algorithms/Greedy/Flowers.java @@ -32,9 +32,11 @@ public static void main(String[] args) { int friendNum = 0; int total = 0; for(int price:flowerPriceList){ + //itterate throught all the flower prices and calculate the total total +=(flowersBought+1)*price; friendNum++; if(friendNum == numFriends){ + //if all friends bought flowers reset the friend counter and restart the cycle friendNum = 0; flowersBought++; } From c845c6e17a52f0c079c6f7aca2e733a4f66a7080 Mon Sep 17 00:00:00 2001 From: "yanz67@gmail.com" Date: Thu, 8 Oct 2015 00:05:52 -0400 Subject: [PATCH 10/46] Service Lane Challenge --- Algorithms/Implementation/ServiceLane.java | 69 ++++++++++++++++++++++ 1 file changed, 69 insertions(+) create mode 100644 Algorithms/Implementation/ServiceLane.java 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 Date: Thu, 8 Oct 2015 10:11:02 -0400 Subject: [PATCH 11/46] Cavity Map --- Algorithms/Implementation/CavityMap.java | 53 ++++++++++++++++++++++++ 1 file changed, 53 insertions(+) create mode 100644 Algorithms/Implementation/CavityMap.java 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;row Date: Wed, 14 Oct 2015 10:02:47 -0400 Subject: [PATCH 12/46] Java 1D array (Hard) Challenge --- Java/Data Structures/Java1DArrayH.java | 98 + Java/Data Structures/Java1DTestCase.txt | 10001 ++++++++++++++++++++++ 2 files changed, 10099 insertions(+) create mode 100644 Java/Data Structures/Java1DArrayH.java create mode 100644 Java/Data Structures/Java1DTestCase.txt diff --git a/Java/Data Structures/Java1DArrayH.java b/Java/Data Structures/Java1DArrayH.java new file mode 100644 index 0000000..ec8f722 --- /dev/null +++ b/Java/Data Structures/Java1DArrayH.java @@ -0,0 +1,98 @@ +/* Java 1D Array (Hard) +In this problem you will test your knowledge on the Java 1D array. + +You are playing a game on your cellphone. You are given an array of length n, indexed from 0 to n−1. Each element of the array is either 0 or 1. You can only move to an index which contains 0. At first you are at the 0th position. In each move you can do one of the following things: + +Walk one step forward or backward. +Make a jump of exactly length m forward. +That means you can move from position x to x+1, x−1 or x+m in one move. The new position must contain 0. Also you can move to any position greater than n-1. + +You can't move backward from position 0. If you move to any position greater than n−1, you win the game. + +Given the array and the length of the jump, you need to determine if it's possible to win the game or not. + +Input Format + +In the first line there will be an integer T denoting the number of test cases. Each test case will consist of two lines. The first line will contain two integers, n and m. On the second line there will be n space-sperated integers, each of which is either 0 or 1. + +Constraints: + +1<=T<=5000 +2≤n≤100 +0≤m≤100 +The first integer of the array is always 0. + +Output Format + +For each case output "YES" if it's possible to win the game, output "NO" otherwise. + + +*/ +import java.util.*; +import java.io.*; + +public class Java1DArrayH { + + static boolean didWinGame(String[] gameArray,int jumpLength) + { + int arrayPos = 0; + boolean didWin = true; + boolean isGoingBack = false; + boolean isGoingForward = false; + int posReached = -1; + while(arrayPos=gameArray.length || (arrayPos+1)>=gameArray.length){ + break; + } + if(isGoingBack && (arrayPos+jumpLength)<=posReached){ + return false; + }else if(gameArray[arrayPos+jumpLength].equals("0") && jumpLength!=0){ + arrayPos +=jumpLength; + posReached = arrayPos; + isGoingBack=false; + isGoingForward = false; + }else if(gameArray[arrayPos+1].equals("0") && !isGoingBack){ + arrayPos+=1; + posReached = arrayPos; + isGoingForward = true; + }else{ + if(isGoingForward){ + arrayPos-=1; + isGoingForward=false; + } + if(arrayPos>1 && gameArray[arrayPos-1].equals("0")){ + isGoingBack=true; + arrayPos-=1; + isGoingForward=false; + }else{ + didWin = false; + break; + } + } + } + return didWin; + } + + public static void main(String[] args) throws IOException + { + //Scanner sc = new Scanner(System.in); + Scanner sc = new Scanner(new FileReader("Java1DTestCase.txt")); + int numCases = sc.nextInt(); + + for(int i=0;i Date: Wed, 14 Oct 2015 14:21:24 -0400 Subject: [PATCH 13/46] Java1DArrayH Latest Version --- Java/Data Structures/Java1DArrayH.java | 117 +++++++++++-------------- 1 file changed, 53 insertions(+), 64 deletions(-) diff --git a/Java/Data Structures/Java1DArrayH.java b/Java/Data Structures/Java1DArrayH.java index ec8f722..3268172 100644 --- a/Java/Data Structures/Java1DArrayH.java +++ b/Java/Data Structures/Java1DArrayH.java @@ -28,71 +28,60 @@ */ -import java.util.*; import java.io.*; +import java.util.*; +import java.text.*; +import java.math.*; +import java.util.regex.*; +import java.util.ArrayList; -public class Java1DArrayH { - - static boolean didWinGame(String[] gameArray,int jumpLength) - { - int arrayPos = 0; - boolean didWin = true; - boolean isGoingBack = false; - boolean isGoingForward = false; - int posReached = -1; - while(arrayPos=gameArray.length || (arrayPos+1)>=gameArray.length){ - break; - } - if(isGoingBack && (arrayPos+jumpLength)<=posReached){ - return false; - }else if(gameArray[arrayPos+jumpLength].equals("0") && jumpLength!=0){ - arrayPos +=jumpLength; - posReached = arrayPos; - isGoingBack=false; - isGoingForward = false; - }else if(gameArray[arrayPos+1].equals("0") && !isGoingBack){ - arrayPos+=1; - posReached = arrayPos; - isGoingForward = true; - }else{ - if(isGoingForward){ - arrayPos-=1; - isGoingForward=false; - } - if(arrayPos>1 && gameArray[arrayPos-1].equals("0")){ - isGoingBack=true; - arrayPos-=1; - isGoingForward=false; - }else{ - didWin = false; - break; - } - } - } - return didWin; - } - - public static void main(String[] args) throws IOException - { - //Scanner sc = new Scanner(System.in); - Scanner sc = new Scanner(new FileReader("Java1DTestCase.txt")); - int numCases = sc.nextInt(); - - 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;i Date: Thu, 10 Dec 2015 21:38:06 -0500 Subject: [PATCH 14/46] Zenefits CodeSprint --- .../Zenefits CodeSprint/EncryptionModule.java | 96 +++++++++++++++++++ .../MiseryofJarJarBinks.java | 81 ++++++++++++++++ 2 files changed, 177 insertions(+) create mode 100644 Contests/Zenefits CodeSprint/EncryptionModule.java create mode 100644 Contests/Zenefits CodeSprint/MiseryofJarJarBinks.java diff --git a/Contests/Zenefits CodeSprint/EncryptionModule.java b/Contests/Zenefits CodeSprint/EncryptionModule.java new file mode 100644 index 0000000..4ef63cd --- /dev/null +++ b/Contests/Zenefits CodeSprint/EncryptionModule.java @@ -0,0 +1,96 @@ +/* +Encryption Module + +"There is an encryption module aboard this Separatist dreadnaught. This device is scrambling all Separatist communication in the region." + +―Mace Windu + + + +An encryption module was an encryption device used to encode messages sent over comlink or through subspace. +For this problem, we will consider a very simplistic version of Encryption module. The encryption module works as following: + +P = plaintext to be encrypted, which consists of characters a−z (no spaces or punctuation marks). This is the input to the encryption module. + +E = P encrypted by Caesar cipher. The shift width is not known to us. + +E′ = 'scrambled' E. That is, some letters of E have been changed arbitrarily. E′ still consists of letters a−z only, and its length is same as E. +This is the output of the encryption module. + +R2-D2 is trying to analyze the encryption module. It knows the value of P and E′, help R2-D2 find the value of E so that the number of +mismatched characters between E and E′ is minimal. You have to just return the minimum possible number of mismatches. + +Note: Number of mismatches between two string E and E′ of the same length is defined as the number of positions i for which E[i]≠E′[i]. + +Input Format + +The first line contains T, the number of test cases. T test cases follow. Each test case consists of a single line containing two space +separated strings, P and E′. + +Constraints: + +1≤T≤100 +1≤|P|=|E′|≤100 +Both P and E′ consist of small case characters +*/ + + +import java.io.*; +import java.util.*; +import java.text.*; +import java.math.*; +import java.util.regex.*; +import java.util.*; + +public class EncryptionModule{ + + public static void main(String[] args) { + Scanner in = new Scanner(System.in); + int t = in.nextInt(); + for(int a0 = 0; a0 < t; a0++){ + String P = in.next(); + String E = in.next(); + int charSum = 0; + Integer shift = null; + HashMapshiftList = 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); + } + } + + } + } +} + + + + + + + + From 85c6c30ffd9227c39cb32c261d12b1451ea242d0 Mon Sep 17 00:00:00 2001 From: "yanz67@gmail.com" Date: Thu, 10 Dec 2015 22:43:52 -0500 Subject: [PATCH 15/46] Add Java Domain Solutions --- Java/Big Number/JavaBigDecimal.java | 82 +++++++++++++ Java/Collections/Java1DArray.java | 76 ++++++++++++ Java/Collections/Java1DArrayHard.java | 111 ++++++++++++++++++ Java/Collections/Java2DArray.java | 77 ++++++++++++ Java/Collections/JavaArrayList.java | 88 ++++++++++++++ Java/Collections/JavaComparator.java | 59 ++++++++++ Java/Collections/JavaDeque.java | 73 ++++++++++++ Java/Collections/JavaGenerics.java | 29 +++++ Java/Collections/JavaHashSet.java | 69 +++++++++++ Java/Collections/JavaMap.java | 72 ++++++++++++ Java/Collections/JavaSort.java | 104 ++++++++++++++++ Java/Collections/JavaStack.java | 91 ++++++++++++++ Java/Introduction/JavaDatatypes.java | 10 +- Java/Introduction/JavaStaticInitBlock.java | 43 +++++++ .../JavaAbstractClass.java | 73 ++++++++++++ .../JavaInheritance1.java | 78 ++++++++++++ ...Inheritance.java => JavaInheritance2.java} | 0 .../JavaMethodOverriding.java | 76 ++++++++++++ Java/Strings/JavaRegex.java | 33 ++++++ Java/Strings/JavaRegex2.java | 72 ++++++++++++ Java/Strings/JavaRegex3.java | 45 +++++++ Java/Strings/JavaStringCompare.java | 47 ++++++++ Java/Strings/JavaStringReverse.java | 46 ++++++++ Java/Strings/JavaStringToken.java | 64 ++++++++++ Java/Strings/PatternSyntaxChecker.java | 57 +++++++++ Java/Strings/TagContentExtractor.java | 94 +++++++++++++++ 26 files changed, 1666 insertions(+), 3 deletions(-) create mode 100644 Java/Big Number/JavaBigDecimal.java create mode 100644 Java/Collections/Java1DArray.java create mode 100644 Java/Collections/Java1DArrayHard.java create mode 100644 Java/Collections/Java2DArray.java create mode 100644 Java/Collections/JavaArrayList.java create mode 100644 Java/Collections/JavaComparator.java create mode 100644 Java/Collections/JavaDeque.java create mode 100644 Java/Collections/JavaGenerics.java create mode 100644 Java/Collections/JavaHashSet.java create mode 100644 Java/Collections/JavaMap.java create mode 100644 Java/Collections/JavaSort.java create mode 100644 Java/Collections/JavaStack.java create mode 100644 Java/Introduction/JavaStaticInitBlock.java create mode 100644 Java/Object Oriented Programming/JavaAbstractClass.java create mode 100644 Java/Object Oriented Programming/JavaInheritance1.java rename Java/Object Oriented Programming/{JavaInheritance.java => JavaInheritance2.java} (100%) create mode 100644 Java/Object Oriented Programming/JavaMethodOverriding.java create mode 100644 Java/Strings/JavaRegex.java create mode 100644 Java/Strings/JavaRegex2.java create mode 100644 Java/Strings/JavaRegex3.java create mode 100644 Java/Strings/JavaStringCompare.java create mode 100644 Java/Strings/JavaStringReverse.java create mode 100644 Java/Strings/JavaStringToken.java create mode 100644 Java/Strings/PatternSyntaxChecker.java create mode 100644 Java/Strings/TagContentExtractor.java diff --git a/Java/Big Number/JavaBigDecimal.java b/Java/Big Number/JavaBigDecimal.java new file mode 100644 index 0000000..60c6bfc --- /dev/null +++ b/Java/Big Number/JavaBigDecimal.java @@ -0,0 +1,82 @@ +/* +Java BigDecimal + +Java BigDecimal class can handle arbitrary-precision signed decimal numbers. Lets test your knowledge on them! + +You are given n real numbers, sort them in descending order! Read data from System.in. + +Note: To make the problem easier, we provided you the input/output part in the editor. Print the numbers as +they appeared in the input, don't change anything. If two numbers represent numerically equivalent values, +the output must list them in original order of the input. + +Input Format + +The first line will consist an integer n, each of the next n lines will contain a real number. n will be at most 200. +The numbers can have at most 300 digits! + +Output Format + +Print the numbers in descending orders, one number in each line. + +Sample Input + +9 +-100 +50 +0 +56.6 +90 +0.12 +.12 +02.34 +000.000 + +Sample Output + +90 +56.6 +50 +02.34 +0.12 +.12 +0 +000.000 +-100 +*/ + + +import java.math.BigDecimal; +import java.util.*; + +class JavaBigDecimal{ + + public static void main(String []argh) + { + Scanner sc= new Scanner(System.in); + int n=sc.nextInt(); + String []s=new String[n]; + + for(int i=0;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/Introduction/JavaDatatypes.java b/Java/Introduction/JavaDatatypes.java index 7e78452..b80ecee 100644 --- a/Java/Introduction/JavaDatatypes.java +++ b/Java/Introduction/JavaDatatypes.java @@ -8,15 +8,19 @@ 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. +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! +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. +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. */ diff --git a/Java/Introduction/JavaStaticInitBlock.java b/Java/Introduction/JavaStaticInitBlock.java new file mode 100644 index 0000000..384c75b --- /dev/null +++ b/Java/Introduction/JavaStaticInitBlock.java @@ -0,0 +1,43 @@ +/* +Java Static Initializer Block + +Static initialization blocks are executed when the class is loaded, and you can initialize static variables in those blocks. + +It's time to test your knowledge of Static initialization blocks. You can read about it here. + +You are given a class Solution with a main method. Complete the given code so that it outputs the +area of a parallelogram with breadth B and height H. You should read the variables from the standard input. + +If B≤0 or H ≤0, the output should be "java.lang.Exception: Breadth and height must be positive" without quotes. + +Input Format + +There are two lines of input. The first line contains B: the breadth of the parallelogram. +The next line contains H: the height of the parallelogram. + +Constraints +−100≤B≤100 +−100≤H≤100 + +Output Format + +If both values are greater than zero, then the main method must output the area of the parallelogram. +Otherwise, print "java.lang.Exception: Breadth and height must be positive" without quotes. + +*/ + + +public class JavaStaticInitBlock +{ + static int B,H; + static boolean flag = true; + static { + Scanner sc = new Scanner(System.in); + B = sc.nextInt(); + H = sc.nextInt(); + if(B<=0 || H<=0){ + System.out.println("java.lang.Exception: Breadth and height must be positive"); + flag = false; + } + } +} \ No newline at end of file diff --git a/Java/Object Oriented Programming/JavaAbstractClass.java b/Java/Object Oriented Programming/JavaAbstractClass.java new file mode 100644 index 0000000..b87ad10 --- /dev/null +++ b/Java/Object Oriented Programming/JavaAbstractClass.java @@ -0,0 +1,73 @@ +/* Java Abstract Class + +A Java abstract class is a class that can't be instantiated, that means you cannot create +new instances of an abstract class. It works as a base for subclasses. You should learn about +Java Inheritence before attempting this challenge. + +Following is an example of abstact class: + +abstract class Book +{ + String title; + abstract void setTitle(String s); + String getTitle() + { + return title; + } + +} +If you try to create an instance of this class like the following line you will get an error: + +Book new_novel=new Book(); +You have to create another class that extends the abstract class. Then you can create instance of the new class. + +Notice that setTitle method is abstract too and has no body. That means you must implement the body of +the that method in the child class. + +In the editor we have provided the abstract Book class and a Main class. In the Main class we created +instance of a class called MyBook. Your task is to write just the Mybook class. Your class mustn't be public. + +Sample Input + +A tale of two cities +Sample Output + +The title is: A tale of two cities + +*/ + +import java.util.*; +abstract class Book +{ + String title; + abstract void setTitle(String s); + String getTitle() + { + return title; + } + +} + +//Write MyBook class here + class MyBook extends Book +{ + void setTitle(String s) + { + title = s; + } + +} + +public class JavaAbstractClass +{ + + public static void main(String []args) + { + Scanner sc=new Scanner(System.in); + String title=sc.nextLine(); + MyBook new_novel=new MyBook(); + new_novel.setTitle(title); + System.out.println("The title is: "+new_novel.getTitle()); + + } +} \ No newline at end of file diff --git a/Java/Object Oriented Programming/JavaInheritance1.java b/Java/Object Oriented Programming/JavaInheritance1.java new file mode 100644 index 0000000..d549875 --- /dev/null +++ b/Java/Object Oriented Programming/JavaInheritance1.java @@ -0,0 +1,78 @@ +/* Java Ingeritance 1 + +Using Inheritance one class can acquire the properties of others. Consider the following Animal class: + +class Animal{ + void walk() + { + System.out.println("I am walking"); + } +} +This class has only one method walk. Now we want to create a Bird class that also has fly method. +We can do it using extends keyword. + +class Bird extends Animal +{ + void fly() + { + System.out.println("I am flying"); + } +} +Now we can create a Bird object that can both fly and walk. + +public class Solution +{ + public static void main(String args[]) + { + + Bird bird = new Bird(); + bird.walk(); + bird.fly(); + } +} +This code will print: + +I am walking +I am flying +So Bird has all the properties that an animal have and it also have some unique properties. + +Your task is very simple. We provided the code above in the editor. Just add a sing method in the +Bird class and modify main function accordingly so that it prints the following lines: + +I am walking +I am flying +I am singing + +*/ + +class Animal{ + void walk() + { + System.out.println("I am walking"); + } +} + +class Bird extends Animal +{ + void fly() + { + System.out.println("I am flying"); + } + void sing() + { + System.out.println("I am singing"); + } +} +public class JavaInheritance1 +{ + + public static void main(String args[]) + { + + Bird bird = new Bird(); + bird.walk(); + bird.fly(); + bird.sing(); + + } +} \ No newline at end of file diff --git a/Java/Object Oriented Programming/JavaInheritance.java b/Java/Object Oriented Programming/JavaInheritance2.java similarity index 100% rename from Java/Object Oriented Programming/JavaInheritance.java rename to Java/Object Oriented Programming/JavaInheritance2.java diff --git a/Java/Object Oriented Programming/JavaMethodOverriding.java b/Java/Object Oriented Programming/JavaMethodOverriding.java new file mode 100644 index 0000000..c66b7dc --- /dev/null +++ b/Java/Object Oriented Programming/JavaMethodOverriding.java @@ -0,0 +1,76 @@ +/* Java Method Overriding + +When a subclass inherits a superclass, it can override methods of the superclass. Consider the following Sports class: + +class Sports{ + + String get_name() + { + return "Generic Sports"; + } + void get_number_of_team_members() + { + System.out.println("Each team has n players in "+get_name()); + } +} +Now we want to create a Soccer class that inherits the Sports class. We can override the get_name +method and return a different string. + +class Sports{ + + String get_name() + { + return "Soccer Class"; + } + +} +Note that to override a method, the parameters and return type of the new method should be exactly same as the old method. + +Your task is simple, you are given a partially completed code in the editor, complete the code so that +it prints the following lines: + +Generic Sports +Each team has n players in Generic Sports +Soccer Class +Each team has 11 players in Soccer Class + + +*/ + +import java.util.*; +class Sports{ + + String get_name() + { + return "Generic Sports"; + } + void get_number_of_team_members() + { + System.out.println("Each team has n players in "+get_name()); + } +} + +class Soccer extends Sports +{ + String get_name() + { + return "Soccer Class"; + } + void get_number_of_team_members() + { + System.out.println("Each team has 11 players in "+get_name()); + } +} +public class JavaMethodOverriding +{ + + public static void main(String []args) + { + Sports C1=new Sports(); + Soccer C2=new Soccer(); + System.out.println(C1.get_name()); + C1.get_number_of_team_members(); + System.out.println(C2.get_name()); + C2.get_number_of_team_members(); + } +} \ No newline at end of file diff --git a/Java/Strings/JavaRegex.java b/Java/Strings/JavaRegex.java new file mode 100644 index 0000000..3f4ad09 --- /dev/null +++ b/Java/Strings/JavaRegex.java @@ -0,0 +1,33 @@ +/* +Java Regex + +Write a class called myRegex which will contain a string pattern. You need to write a regular expression and assign it to +the pattern such that it can be used to validate an IP address. Use the following definition of an IP address: + +IP address is a string in the form "A.B.C.D", where the value of A, B, C, and D may range from 0 to 255. Leading zeros are +allowed. The length of A, B, C, or D can't be greater than 3. +Some valid IP address: + +000.12.12.034 +121.234.12.12 +23.45.12.56 +Some invalid IP address: + +000.12.234.23.23 +666.666.23.23 +.213.123.23.32 +23.45.22.32. +I.Am.not.an.ip +In this problem you will be provided strings containing any combination of ASCII characters. You have to write a regular +expression to find the valid IPs. + +Just write the myRegex class, and we will append your code after the following piece of code automatically before running it: + +*/ + + +class myRegex +{ + String pattern = "^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$"; + +} \ No newline at end of file diff --git a/Java/Strings/JavaRegex2.java b/Java/Strings/JavaRegex2.java new file mode 100644 index 0000000..c1d3eaf --- /dev/null +++ b/Java/Strings/JavaRegex2.java @@ -0,0 +1,72 @@ +/* +Java Regex 2 - Duplicate Words + +When we write something, it is easy to repeat words by mistake. For example: Monmoy loves to to code. Here, "to" +is written multiple times. + +Using Regex, we can easily identify the repeated pattern in a given text. In this problem, you will be given a text. +Your task is to identify the consecutively repeated words and delete them after the first occurrence of the word. + +Complete the code in the editor to solve this problem. Don't modify any extra lines. You will get the wrong answer +if you modify more than 3 lines. + +To restore the original code in the editor, create a new buffer by clicking on the top-left button in the editor. + +Input Format + +The first line of input contains an integer N, representing the number of testcases. The next N lines contain a +string of English letters and whitespaces. + +Constraints + +In each line, there will be at most 104 English letters and whitespaces. + +1≤N≤100 +Output Format + +Print the input string after deleting the consecutive words after the first occurrence of the word. + +Sample Input + +4 +Goodbye bye bye world world world +Swapnil went went to to to his business +Rana is is the the best player in eye eye game +in inthe + +Sample Output + +Goodbye bye world +Swapnil went to his business +Rana is the best player in eye game +in inthe +*/ + + +import java.util.Scanner; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +public class JavaRegex2 +{ + public static void main(String[] args){ + + String pattern = "(?i)\\b(\\w+)(\\s+\\1)+\\b"; + Pattern r = Pattern.compile(pattern,Pattern.CASE_INSENSITIVE); + + Scanner in = new Scanner(System.in); + int testCases = Integer.parseInt(in.nextLine()); + while(testCases>0){ + 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/PatternSyntaxChecker.java b/Java/Strings/PatternSyntaxChecker.java new file mode 100644 index 0000000..72858e8 --- /dev/null +++ b/Java/Strings/PatternSyntaxChecker.java @@ -0,0 +1,57 @@ +/* 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){ + String pattern = in.nextLine(); + //Write your code + try{ + Pattern.compile(pattern); + System.out.println("Valid"); + }catch(PatternSyntaxException e){ + System.out.println("Invalid"); + } + + + } + } +} \ No newline at end of file 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--; + } + + } +} + From 81fb8620f1b69effb8e2f925cc27f23f18ed0bb5 Mon Sep 17 00:00:00 2001 From: "yanz67@gmail.com" Date: Fri, 11 Dec 2015 09:01:06 -0500 Subject: [PATCH 16/46] Add Java Domain Solutions --- Java/Advanced/CanYouAccess.java | 21 ++ Java/Advanced/JavaAnnotations.java | 198 ++++++++++++++++++ Java/Advanced/JavaFactory.java | 33 +++ Java/Advanced/JavaReflection.java | 59 ++++++ Java/Advanced/JavaVarargs.java | 50 +++++ Java/Advanced/PrimeChecker.java | 60 ++++++ .../Java1DTestCase.txt | 0 Java/Data Structures/Java1DArrayH.java | 87 -------- Java/Data Structures/Java2DArray.java | 68 ------ Java/Data Structures/JavaArrayList.java | 58 ----- Java/Data Structures/JavaStack.java | 75 ------- .../JavaExceptionHandling.java | 4 +- .../JavaExceptionHandlingTryCatch.java | 74 +++++++ .../CalculatingVolume.java | 123 +++++++++++ .../JavaInstanceOf.java | 68 ++++++ .../JavaIterator.java | 79 +++++++ .../JavaMethodOverriding2.java | 50 +++++ 17 files changed, 818 insertions(+), 289 deletions(-) create mode 100644 Java/Advanced/CanYouAccess.java create mode 100644 Java/Advanced/JavaAnnotations.java create mode 100644 Java/Advanced/JavaFactory.java create mode 100644 Java/Advanced/JavaReflection.java create mode 100644 Java/Advanced/JavaVarargs.java create mode 100644 Java/Advanced/PrimeChecker.java rename Java/{Data Structures => Collections}/Java1DTestCase.txt (100%) delete mode 100644 Java/Data Structures/Java1DArrayH.java delete mode 100644 Java/Data Structures/Java2DArray.java delete mode 100644 Java/Data Structures/JavaArrayList.java delete mode 100644 Java/Data Structures/JavaStack.java create mode 100644 Java/Exception Handling/JavaExceptionHandlingTryCatch.java create mode 100644 Java/Object Oriented Programming/CalculatingVolume.java create mode 100644 Java/Object Oriented Programming/JavaInstanceOf.java create mode 100644 Java/Object Oriented Programming/JavaIterator.java create mode 100644 Java/Object Oriented Programming/JavaMethodOverriding2.java 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;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); - - } -} \ No newline at end of file diff --git a/Java/Data Structures/JavaArrayList.java b/Java/Data Structures/JavaArrayList.java deleted file mode 100644 index 9331d04..0000000 --- a/Java/Data Structures/JavaArrayList.java +++ /dev/null @@ -1,58 +0,0 @@ -/* Java Array List -Some times its better to use dynamic size array, java Arraylist can provide you this feature. Try to solve this problem using Arraylist. - -You are given n lines. In each of the line there are zero or more integers. You need to answer few queries. In each query, you need to tell the number located in yth position of xth line. - -Take your input from System.in. - -Input Format -In the first line there will 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 seperated 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!" -*/ -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) { - /* 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 numLines = Integer.parseInt(sc.nextLine()); - ArrayList listArray = new ArrayList(); - for(int i = 0;i intArrayList = new ArrayList(); - for(int j=0;jclosingParan = 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) { - /* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */ - 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 index 33cf993..914489f 100644 --- a/Java/Exception Handling/JavaExceptionHandling.java +++ b/Java/Exception Handling/JavaExceptionHandling.java @@ -1,5 +1,7 @@ /* 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". +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. 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/Object Oriented Programming/CalculatingVolume.java b/Java/Object Oriented Programming/CalculatingVolume.java new file mode 100644 index 0000000..19bdc90 --- /dev/null +++ b/Java/Object Oriented Programming/CalculatingVolume.java @@ -0,0 +1,123 @@ +/* Calculating Volume + +You are given a class Solution and its main method in the editor. In each test cases, it takes an input ch which +represents a choice of the following: + +ch=1 represents the volume of a cube that has to be calculated where a represents the length of the sides of the cube. +ch=2 represents the volume of a cuboid that has to be calculated where l,b,h represent the dimensions of a cuboid. +ch=3 represents the volume of a hemisphere that has to be calculated where r represents the radius of a hemisphere. +ch=4 represents the volume of a cylinder that has to be calculated where r,h represent the radius and height of the +cylinder respectively. +Your task is to create the class Calculate and the required methods so that the code prints the volume of the +figures rounded to exactly 3 decimal places. + +In case any of the values are ≤0, print "java.lang.NumberFormatException: All the values must be positive" +without quotes and terminate the program. + +Note: Use Math.PI or 3.14159265 as the value of pi. + +Input Format + +First line contains T, the number of test cases. Each test case contains ch, representing the choice as given +in the problem statement. + +When ch=1, Next line contains a, length of the sides of the cube. +When ch=2, Next three lines contain l, b, h representing length, breadth and height of the cuboid respectively. +l, b, h will be in three separate lines +When ch=3, Next line contains r, the radius of the hemisphere +When ch=4, Next two lines contain r, h representing the radius and height of the cylinder respectively. r, h +will be in two separate lines. +Note: You have to determine the data type of each parameter by looking at the code given in the main method. + +Constraints +1≤ch≤4 +−100≤a,l,b,h,r≤100 +There will be at most 3 digits after decimal point in input. + +Output Format + +For each test case, print the answer rounded up to exactly 3 decimal places in a single line. For example, +1.2345 should be rounded to 1.235, 3.12995 should be rounded to 3.130. + +Sample Input 1 + +2 +1 +4 +4 +67.89 +-98.54 + +Sample Output 1 + +64.000 +java.lang.NumberFormatException: All the values must be positive +*/ + +class Calculate +{ + class Output{ + + public void display(double volume) + { + System.out.printf("%.3f\n",volume); + } + } + + + Output output; + Scanner sc; + public Calculate() + { + output = new Output(); + sc = new Scanner(System.in); + } + public int getINTVal() + { + + int a = sc.nextInt(); + if(a<=0){throw new NumberFormatException("All the values must be positive");} + return a; + } + public double getDoubleVal() + { + double a = sc.nextDouble(); + if(a<=0){throw new NumberFormatException("All the values must be positive");} + return a; + } + public static Get_Vol get_Vol() + { + + return new Get_Vol(); + } +} + +class Get_Vol extends Calculate +{ + double main(int val) throws IOException + { + + return (val*val*val); + } + double main(int val, int val2, int val3) throws IOException + { + + + return val*val2*val3; + } + double main(double val) throws IOException + { + + double radius = Math.PI*(val*val*val) * (2.0/3.0); + + return radius; + } + double main(double val, double val2)throws IOException + { + + + return Math.PI*(val*val)*val2; + } + +} + diff --git a/Java/Object Oriented Programming/JavaInstanceOf.java b/Java/Object Oriented Programming/JavaInstanceOf.java new file mode 100644 index 0000000..db99760 --- /dev/null +++ b/Java/Object Oriented Programming/JavaInstanceOf.java @@ -0,0 +1,68 @@ +/* Java Instanceof keyword + +The Java instanceof operator is used to test if the object or instance is an instanceof the specified type. + +In this problem we have given you three classes in the editor, Student, Rockstar and Hacker. In the main +function we populated an ArrayList with instances of these classes. count method counts how many instance of each +type are present in the ArrayList. Some lines of the code are missing, and you have to fix it by modifying only 3 lines! + +To restore the original code in the editor, click on the top left icon in the editor and create a new buffer. + +Sample Input + +5 +Student +Student +Rockstar +Student +Hacker + +Sample Output + +3 1 1 + + +*/ + +import java.util.*; + + +class Student{} +class Rockstar{ } +class Hacker{} + + +public class JavaInstanceOf +{ + static String count(ArrayList mylist) + { + int a=0,b=0,c=0; + 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;i Date: Fri, 11 Dec 2015 10:05:53 -0500 Subject: [PATCH 17/46] All of my completed challenges --- Algorithms/Greedy/MarkAndToys.java | 52 +++++++++++ Algorithms/Greedy/PriyankaandToys.java | 58 ++++++++++++ Algorithms/Greedy/TwoArrays.java | 83 +++++++++++++++++ Algorithms/Implementation/AngryProfessor.java | 73 +++++++++++++++ Algorithms/Implementation/CeasarCipher.java | 60 ++++++++++++ Algorithms/Implementation/ChocolateFeast.java | 63 +++++++++++++ Algorithms/Implementation/CutTheSticks.java | 90 ++++++++++++++++++ .../Implementation/ExtraLongFactorial.java | 41 +++++++++ Algorithms/Implementation/LibraryFine.java | 52 +++++++++++ .../Implementation/SherlockAndTheBeast.java | 91 +++++++++++++++++++ Algorithms/Sorting/SherlockAndPairs.java | 71 +++++++++++++++ Algorithms/Strings/GemStones.java | 65 +++++++++++++ Algorithms/Strings/TheLoveLetterMistery.java | 65 +++++++++++++ Algorithms/Warmup/SimpleArraySum.java | 36 ++++++++ {Algorithms/Code Golf => Code Golf}/F.java | 0 15 files changed, 900 insertions(+) create mode 100644 Algorithms/Greedy/MarkAndToys.java create mode 100644 Algorithms/Greedy/PriyankaandToys.java create mode 100644 Algorithms/Greedy/TwoArrays.java create mode 100644 Algorithms/Implementation/AngryProfessor.java create mode 100644 Algorithms/Implementation/CeasarCipher.java create mode 100644 Algorithms/Implementation/ChocolateFeast.java create mode 100644 Algorithms/Implementation/CutTheSticks.java create mode 100644 Algorithms/Implementation/ExtraLongFactorial.java create mode 100644 Algorithms/Implementation/LibraryFine.java create mode 100644 Algorithms/Implementation/SherlockAndTheBeast.java create mode 100644 Algorithms/Sorting/SherlockAndPairs.java create mode 100644 Algorithms/Strings/GemStones.java create mode 100644 Algorithms/Strings/TheLoveLetterMistery.java create mode 100644 Algorithms/Warmup/SimpleArraySum.java rename {Algorithms/Code Golf => Code Golf}/F.java (100%) diff --git a/Algorithms/Greedy/MarkAndToys.java b/Algorithms/Greedy/MarkAndToys.java new file mode 100644 index 0000000..d3c4be4 --- /dev/null +++ b/Algorithms/Greedy/MarkAndToys.java @@ -0,0 +1,52 @@ +/* +Mark And Toys + +Mark and Jane are very happy after having their first kid. Their son is very fond of toys, so Mark wants to buy some. There are N different toys lying in front of him, tagged with their prices, but he has only $K. He wants to maximize the number of toys he buys with this money. + +Now, you are Mark's best friend and have to help him buy as many toys as possible. + +Input Format +The first line contains two integers, N and K, followed by a line containing N space separated integers indicating the products' prices. + +Output Format +An integer that denotes maximum number of toys Mark can buy for his son. + +Constraints +1<=N<=105 +1<=K<=109 +1<=price of any toy<=109 +A toy can't be bought multiple times. + +Sample Input + +7 50 +1 12 5 111 200 1000 10 +Sample Output + +4 +*/ + +import java.io.*; +import java.util.*; +import java.text.*; +import java.math.*; +import java.util.regex.*; + +public class MarkAndToys { + public static void main(String[] args) { + Scanner stdin=new Scanner(System.in); + int n=stdin.nextInt(),k=stdin.nextInt(); + int prices[]=new int[n]; + 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/CeasarCipher.java b/Algorithms/Implementation/CeasarCipher.java new file mode 100644 index 0000000..9d01cb8 --- /dev/null +++ b/Algorithms/Implementation/CeasarCipher.java @@ -0,0 +1,60 @@ +/* Ceasar Cipher + +Julius Caesar protected his confidential information by encrypting it in a cipher. Caesar's cipher rotated every letter in a string by a fixed number, K, making it unreadable by his enemies. Given a string, S, and a number, K, encrypt S and print the resulting string. + +Note: The cipher only encrypts letters; symbols, such as -, remain unencrypted. + +Input Format + +The first line contains an integer, N, which is the length of the unencrypted string. +The second line contains the unencrypted string, S. +The third line contains the integer encryption key, K, which is the number of letters to rotate. + +Constraints +1≤N≤100 +0≤K≤100 +S is a valid ASCII string and doesn't contain any spaces. + +Output Format + +For each test case, print the encoded string. + +Sample Input + +11 +middle-Outz +2 +Sample Output + +okffng-Qwvb +*/ + +import java.io.*; +import java.util.*; +import java.text.*; +import java.math.*; +import java.util.regex.*; + +public class CeasarCipher { + + public static void main(String[] args) { + + Scanner sc = new Scanner(System.in); + int numChars = Integer.parseInt(sc.nextLine()); + char[] inputString = sc.nextLine().toCharArray(); + int rotateValue = sc.nextInt(); + for(int i = 0;i0); + 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/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= 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/Sorting/SherlockAndPairs.java b/Algorithms/Sorting/SherlockAndPairs.java new file mode 100644 index 0000000..76711f1 --- /dev/null +++ b/Algorithms/Sorting/SherlockAndPairs.java @@ -0,0 +1,71 @@ +/* +Sherlock and Pairs + +Sherlock is given an array of N integers (A0, A1 ... AN−1 by Watson. Now Watson asks Sherlock how many +different pairs of indices i and j exist such that i is not equal to j but Ai is equal to Aj. + +That is, Sherlock has to count the total number of pairs of indices (i,j) where Ai =Aj AND i≠j. + +Input Format +The first line contains T, the number of test cases. T test cases follow. +Each test case consists of two lines; the first line contains an integer N, the size of array, while +the next line contains N space separated integers. + +Output Format +For each test case, print the required answer on a different line. + +Constraints +1≤T≤10 +1≤N≤105 +1≤A[i]≤106 + +Sample input + +2 +3 +1 2 3 +3 +1 1 2 +Sample output + +0 +2 +*/ + +import java.io.*; +import java.util.*; +import java.text.*; +import java.math.*; +import java.util.regex.*; + +public class SherlockAndPairs { + + public static void main(String[] args) { + + Scanner sc = new Scanner(System.in); + int numCases = sc.nextInt(); + for(int i = 0; i < numCases; i++){ + int count = 0; + int sizeArray = sc.nextInt(); + Map 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/GemStones.java b/Algorithms/Strings/GemStones.java new file mode 100644 index 0000000..66fbbba --- /dev/null +++ b/Algorithms/Strings/GemStones.java @@ -0,0 +1,65 @@ +/*Gem Stones + +John has discovered various rocks. Each rock is composed of various elements, and each element is +represented by a lower-case Latin letter from 'a' to 'z'. An element can be present multiple times in a rock. An element is called a gem-element if it occurs at least once in each of the rocks. + +Given the list of N rocks with their compositions, display the number of gem-elements that exist in those rocks. + +Input Format + +The first line consists of an integer, N, the number of rocks. +Each of the next N lines contains a rock's composition. Each composition consists of lower-case +letters of English alphabet. + +Constraints +1≤N≤100 +Each composition consists of only lower-case Latin letters ('a'-'z'). +1≤ length of each composition ≤100 +Output Format + +Print the number of gem-elements that are common in these rocks. If there are none, print 0. + +Sample Input + +3 +abcdde +baccd +eeabg + +Sample Output + +2 +*/ + +import java.io.*; +import java.util.*; + +public class GemStones { + + public static void main(String[] args) { + + Scanner sc = new Scanner(System.in); + Map dict = new HashMap(); + int numTestCases = Integer.parseInt(sc.nextLine()); + for(int i = 0;i Date: Tue, 15 Dec 2015 08:47:02 -0500 Subject: [PATCH 18/46] Added Solutions from Indeed Contest --- .../GretchenAndPlay.java | 177 ++++++++++++++++++ .../TheUlitmateQuestion.java | 87 +++++++++ 2 files changed, 264 insertions(+) create mode 100644 Contests/Indeed Prime CodeSprint/GretchenAndPlay.java create mode 100644 Contests/Indeed Prime CodeSprint/TheUlitmateQuestion.java diff --git a/Contests/Indeed Prime CodeSprint/GretchenAndPlay.java b/Contests/Indeed Prime CodeSprint/GretchenAndPlay.java new file mode 100644 index 0000000..f08791b --- /dev/null +++ b/Contests/Indeed Prime CodeSprint/GretchenAndPlay.java @@ -0,0 +1,177 @@ +/* Gretchen and the Play + +Gretchen is directing a new play with M scenes performed by N actors, where each actor only appears in exactly one scene. +To ensure that the distribution is perfect, she performs the following actions: + +Assign actor Ni to scene Mi. +Count the number of scenes having less than P actors assigned to them. +Given a list of actions, determine the distribution of actors in Gretchen's play. + +Input Format + +The first line contains three space-separated integers, M, N, and Q, respectively; M is the number of scenes, +N is the number of actors, and Q is the number of actions Gretchen plans to perform. N and M use zero-based indexing. + +The second line contains N space-separated integers; the ith integer represents the scene, Mi, that actor Ni is i +nitially assigned to. + +The Q subsequent lines describe Gretchen's actions; each of these lines starts with an integer, A, which corresponds +to Action 1 or Action 2 (as detailed in the Problem Statement). + +When A=1 (Action 1), it will be followed by two space-separated integers, Ni and Mi, respectively; this action +says to assign actor Ni to scene Mi. + +When A=2 (Action 2), it will be followed by a single integer, P; this action says to count the number of segments +having

scencesMap = new HashMap(); + TreeMap 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; + + for(Integer num : cachedSearchMap.keySet()){ + if(num < actorsCount){ + total+=cachedSearchMap.get(num); + }else { + break; + } + } + int scenesWithOutActors = numOfScenes - scencesMap.size(); + System.out.println(""+(total+scenesWithOutActors)); + + + }else if(actionType == 1){ + int actNum = sc.nextInt(); + + int prevPos = Integer.parseInt(actorsAssigmentsArray[actNum]); + int pos = sc.nextInt(); + actorsAssigmentsArray[actNum] = ""+pos; + + int prevNumActors = scencesMap.remove(prevPos); + + if(prevNumActors > 1){ + scencesMap.put(prevPos,prevNumActors-1); + } + + 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 From 4965ded1f4906bc786a2371910de66bf7191115c Mon Sep 17 00:00:00 2001 From: "yanz67@gmail.com" Date: Tue, 15 Dec 2015 08:57:41 -0500 Subject: [PATCH 19/46] Added Comments to Gretchen At Play Solution --- .../GretchenAndPlay.class | Bin 0 -> 2863 bytes .../Indeed Prime CodeSprint/GretchenAndPlay.java | 15 ++++++++++++--- 2 files changed, 12 insertions(+), 3 deletions(-) create mode 100644 Contests/Indeed Prime CodeSprint/GretchenAndPlay.class diff --git a/Contests/Indeed Prime CodeSprint/GretchenAndPlay.class b/Contests/Indeed Prime CodeSprint/GretchenAndPlay.class new file mode 100644 index 0000000000000000000000000000000000000000..506d5bc9b452abe9b7ff839e25d62e30d1e1007b GIT binary patch literal 2863 zcmaJ@S#VQj6#o93<)+C^)1+MBDo{|CutpIgq<{jlgdJL2cDXc{l9DDNy{&92Ac6~{ zGcFG}APk^&+`*Z!)M0$F4?4p*;{!83`Na6>1LF)#v7YlMZIW8a!^!#2@}2d+_x}9P z&07HG;G`Fm5moW57YgR7m|uk$>b-Dc0h5JH7J2ZT7tdp{iX~q7*nFuMeni>l1t!Z_ zyqvie%&lZ?oQdQ};m0Z;R%4A1Yq5^WdbZoZ!8WScHFV)+ zDo4Ws9Mo_Khcz5w!&mUCz^GE@h1M+TOr{c6P5>HS!%-&3G#rPe;&lxt@CLPdNGAkp zN+|1hw^=Q=KKOssCMv%HVQE1Y8~2RFWX36ysFv&#=|0 zU1qA&TEB;vE?yp{xD=GMCu`<9ESZ`<94;m6&ROl5E=qNBxj~_?_2sBV5rHPtb`yuD zdZ|MK^M>&(tNKw`j#i5R-21G94a@`w+Ev(L%cdIqr6EciPjYaSBP+}YMod2HUbABz z4M9$XF0qp*GISb)1vxvChq#yw7gL)52D-bY`Mb?*)=DP?W|mhwaKX#UtypZzWlZI8 zhN?YwrXZpvmX*@xl|`mnvYbbXS97??O_+d5^hD*K0@@#hiB6@{So)`n1=qA|5Lbv1 zm`2nsg$q%I>6k%0nYvEFg%N<`SPzsf&TDY2>49_0Rk*Ify>><(>LMmlr=%{To@OSY zsyw_gcMp79u0e~bJ@6A#9rHM@BM_@{M7_G#aNoL!KEthhXJ1E6)Mu!=kF54{LCl41OY zzZYS{&u*7dS7y#=Qk;-UFj{>vIRfFF=&zK@C^`>~?jxBDc)}~X`xV&(-E~n3%ij5P zpX&m;B(FK5e#4W;s2dn95UVz-Z@>^ZgIUZyCcwD{3~E(K*DhkTPS$+l_$1pE^>_E* z9&4z1Jf4VFU&WXnjHULE3)ST@Uia(OyYiTj#}j!x*)1;VKIa8-t`L}}p~-3Z<++;A z70%TK&jza9KR7Ik84c(GYMEY?)1lBP?u;Igma@Y&Molj!88w9tk12Fm4{&>>Y@odi z@CoAVTtt%14I05-Oc?NTCfF~?ScTo-vFH`r!h}`5TBb0O8y9p&Lku&Ka%FKj0Hs@i zi-x*MQ!pqFSPvC5k%iP6wY`{P)D{XER}4xfoRX9dltMLxWOP}9^eb+b9vU<*_6k3@k?-$tGbX=~rPcecUX zo3Wp`E^Ng+*oO1ij?37ApXd|dchcTP3+^EyYS1cb>CIn_5y3vO6zyU)8pTHJ z7u#S96P=7m{`#3Dl;)wVLN9kd5Ox(nAafjZ|f8eCJi#NqzcuV|^x0L`+ zD--apG6nA`^YMYQ5+5o}_(;j%jM9aVl~XvYoW?oj3!GPez(wU3TvBf1vho`~RsO_h z$~}DU0KRkt@s*))B{dj&-==Xv6o8L)h;)itCt3-T4(G`>_E&6|+=CR6Hew zko?msW|M@Teh;Y>;zm5cT&0g~BKM&_fU6IR=%6++aHZn literal 0 HcmV?d00001 diff --git a/Contests/Indeed Prime CodeSprint/GretchenAndPlay.java b/Contests/Indeed Prime CodeSprint/GretchenAndPlay.java index f08791b..ecc9ef9 100644 --- a/Contests/Indeed Prime CodeSprint/GretchenAndPlay.java +++ b/Contests/Indeed Prime CodeSprint/GretchenAndPlay.java @@ -72,11 +72,17 @@ public static void main(String[] args) { sc.nextLine(); String[] actorsAssigmentsArray = sc.nextLine().split(" "); - HashMap scencesMap = new HashMap(); - TreeMap cachedSearchMap = new TreeMap(); + HashMap 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(prevNumActors),prvNumValue-1); @@ -145,6 +153,7 @@ public static void main(String[] args) { if((prevNumActors-1) > 0 ) { Integer prvNumActorsOneVal = cachedSearchMap.get(prevNumActors-1); + if(prvNumActorsOneVal != null){ cachedSearchMap.put(new Integer(prevNumActors-1), prvNumActorsOneVal+1); }else{ From 1d797f6d4dfa8896f56b254f429b6fab26b51674 Mon Sep 17 00:00:00 2001 From: "yanz67@gmail.com" Date: Tue, 15 Dec 2015 08:59:26 -0500 Subject: [PATCH 20/46] Deleted .class file --- .../GretchenAndPlay.class | Bin 2863 -> 0 bytes 1 file changed, 0 insertions(+), 0 deletions(-) delete mode 100644 Contests/Indeed Prime CodeSprint/GretchenAndPlay.class diff --git a/Contests/Indeed Prime CodeSprint/GretchenAndPlay.class b/Contests/Indeed Prime CodeSprint/GretchenAndPlay.class deleted file mode 100644 index 506d5bc9b452abe9b7ff839e25d62e30d1e1007b..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 2863 zcmaJ@S#VQj6#o93<)+C^)1+MBDo{|CutpIgq<{jlgdJL2cDXc{l9DDNy{&92Ac6~{ zGcFG}APk^&+`*Z!)M0$F4?4p*;{!83`Na6>1LF)#v7YlMZIW8a!^!#2@}2d+_x}9P z&07HG;G`Fm5moW57YgR7m|uk$>b-Dc0h5JH7J2ZT7tdp{iX~q7*nFuMeni>l1t!Z_ zyqvie%&lZ?oQdQ};m0Z;R%4A1Yq5^WdbZoZ!8WScHFV)+ zDo4Ws9Mo_Khcz5w!&mUCz^GE@h1M+TOr{c6P5>HS!%-&3G#rPe;&lxt@CLPdNGAkp zN+|1hw^=Q=KKOssCMv%HVQE1Y8~2RFWX36ysFv&#=|0 zU1qA&TEB;vE?yp{xD=GMCu`<9ESZ`<94;m6&ROl5E=qNBxj~_?_2sBV5rHPtb`yuD zdZ|MK^M>&(tNKw`j#i5R-21G94a@`w+Ev(L%cdIqr6EciPjYaSBP+}YMod2HUbABz z4M9$XF0qp*GISb)1vxvChq#yw7gL)52D-bY`Mb?*)=DP?W|mhwaKX#UtypZzWlZI8 zhN?YwrXZpvmX*@xl|`mnvYbbXS97??O_+d5^hD*K0@@#hiB6@{So)`n1=qA|5Lbv1 zm`2nsg$q%I>6k%0nYvEFg%N<`SPzsf&TDY2>49_0Rk*Ify>><(>LMmlr=%{To@OSY zsyw_gcMp79u0e~bJ@6A#9rHM@BM_@{M7_G#aNoL!KEthhXJ1E6)Mu!=kF54{LCl41OY zzZYS{&u*7dS7y#=Qk;-UFj{>vIRfFF=&zK@C^`>~?jxBDc)}~X`xV&(-E~n3%ij5P zpX&m;B(FK5e#4W;s2dn95UVz-Z@>^ZgIUZyCcwD{3~E(K*DhkTPS$+l_$1pE^>_E* z9&4z1Jf4VFU&WXnjHULE3)ST@Uia(OyYiTj#}j!x*)1;VKIa8-t`L}}p~-3Z<++;A z70%TK&jza9KR7Ik84c(GYMEY?)1lBP?u;Igma@Y&Molj!88w9tk12Fm4{&>>Y@odi z@CoAVTtt%14I05-Oc?NTCfF~?ScTo-vFH`r!h}`5TBb0O8y9p&Lku&Ka%FKj0Hs@i zi-x*MQ!pqFSPvC5k%iP6wY`{P)D{XER}4xfoRX9dltMLxWOP}9^eb+b9vU<*_6k3@k?-$tGbX=~rPcecUX zo3Wp`E^Ng+*oO1ij?37ApXd|dchcTP3+^EyYS1cb>CIn_5y3vO6zyU)8pTHJ z7u#S96P=7m{`#3Dl;)wVLN9kd5Ox(nAafjZ|f8eCJi#NqzcuV|^x0L`+ zD--apG6nA`^YMYQ5+5o}_(;j%jM9aVl~XvYoW?oj3!GPez(wU3TvBf1vho`~RsO_h z$~}DU0KRkt@s*))B{dj&-==Xv6o8L)h;)itCt3-T4(G`>_E&6|+=CR6Hew zko?msW|M@Teh;Y>;zm5cT&0g~BKM&_fU6IR=%6++aHZn From bfa28db61ce3f4bb314703e0706d5933ac5ef5b0 Mon Sep 17 00:00:00 2001 From: "yanz67@gmail.com" Date: Thu, 7 Jul 2016 17:42:40 -0400 Subject: [PATCH 21/46] Added more Solutions --- Algorithms/Implementation/CeasarCipher.java | 4 +- Algorithms/Implementation/Encryption.class | Bin 0 -> 1393 bytes Algorithms/Implementation/Encryption.java | 40 +++++ Algorithms/Implementation/LisaWorkBook.class | Bin 0 -> 987 bytes Algorithms/Implementation/LisaWorkBook.java | 47 ++++++ .../ModifiedKaprekarNumbers.java | 89 +++++++++++ Algorithms/Warmup/SavethePrisoner.java | 56 +++++++ .../ComparetheTriplets.mm | 60 +++++++ .../ComparetheTriplets.java | 78 ++++++++++ .../CovariantReturnTypes.java | 113 ++++++++++++++ .../JavaLambdaExpressions.java | 128 +++++++++++++++ Contests/CodeWhiz.java 2016/JavaList.java | 82 ++++++++++ .../CodeWhiz.java 2016/JavaPrimalityTest.java | 91 +++++++++++ .../CodeWhiz.java 2016/JavaSingleton.java | 50 ++++++ .../CodeWhiz.java 2016/MaximumandMinimum.java | 105 +++++++++++++ .../CodeWhiz.java 2016/ServetheStudents.java | 147 ++++++++++++++++++ .../World CodeSprint/MarsExploration.java | 61 ++++++++ 17 files changed, 1150 insertions(+), 1 deletion(-) create mode 100644 Algorithms/Implementation/Encryption.class create mode 100644 Algorithms/Implementation/Encryption.java create mode 100644 Algorithms/Implementation/LisaWorkBook.class create mode 100644 Algorithms/Implementation/LisaWorkBook.java create mode 100644 Algorithms/Implementation/ModifiedKaprekarNumbers.java create mode 100644 Algorithms/Warmup/SavethePrisoner.java create mode 100644 Contests/ May World CodeSprint /ComparetheTriplets.mm create mode 100644 Contests/CodeWhiz.java 2016/ComparetheTriplets.java create mode 100644 Contests/CodeWhiz.java 2016/CovariantReturnTypes.java create mode 100644 Contests/CodeWhiz.java 2016/JavaLambdaExpressions.java create mode 100644 Contests/CodeWhiz.java 2016/JavaList.java create mode 100644 Contests/CodeWhiz.java 2016/JavaPrimalityTest.java create mode 100644 Contests/CodeWhiz.java 2016/JavaSingleton.java create mode 100644 Contests/CodeWhiz.java 2016/MaximumandMinimum.java create mode 100644 Contests/CodeWhiz.java 2016/ServetheStudents.java create mode 100644 Contests/World CodeSprint/MarsExploration.java diff --git a/Algorithms/Implementation/CeasarCipher.java b/Algorithms/Implementation/CeasarCipher.java index 9d01cb8..84b8468 100644 --- a/Algorithms/Implementation/CeasarCipher.java +++ b/Algorithms/Implementation/CeasarCipher.java @@ -1,6 +1,8 @@ /* Ceasar Cipher -Julius Caesar protected his confidential information by encrypting it in a cipher. Caesar's cipher rotated every letter in a string by a fixed number, K, making it unreadable by his enemies. Given a string, S, and a number, K, encrypt S and print the resulting string. +Julius Caesar protected his confidential information by encrypting it in a cipher. Caesar's cipher rotated every letter in a string +by a fixed number, K, making it unreadable by his enemies. Given a string, S, and a number, K, encrypt S and print the +resulting string. Note: The cipher only encrypts letters; symbols, such as -, remain unencrypted. diff --git a/Algorithms/Implementation/Encryption.class b/Algorithms/Implementation/Encryption.class new file mode 100644 index 0000000000000000000000000000000000000000..ed0b68f219746aeda15a0ad5ae3673017c6def2c GIT binary patch literal 1393 zcmZux&rcIU6#k~W-Pv8X{3t9xR1_7ogg2jCzs>!?LD zM~j9%*sH^bkT78#t!UHHjt*fug^6(Ng)#?DMwGf9fb^OoZ>)P|- zk(ifp+(fS^48%MuetpzR7xFod5o?Y{LD2w?lDwvy6&39 zqDcSM#%?co_B?}6NNN@ZbyAUGH=Xq;-L~d?8R|ouP6)A8*S_V67SX;#;f)QUwkB;i z;msA=O6ruCc#m2lEHB*15P3N?7^Y48uO?F|(nOBiPLhhPblP@j89G)e{MYOa%dJXE zl$H3Ll{s0!9S#pLYzqx+WLHX8z0^N(q*Rv5N>Yr|!752nU7$}2tqC*mv`9({2{+?8 ziJdU%{)o>9Itr*K+d!j6`qKe`zjX=hB{>XR$SQ>(hlZ`#Mn0voZ}8LA0hZswH}wkA z66BG#Jp7~Wc_s_YS^|9o>fWNQ=A@`^`oq#^Ctq2CGtT?C9-1Aqc7DzQh zA74SA84?f>Pe~an5g-}M(S{0oO)AlkAl=Mrx|KDUAlW?<{tiigmul`&^?iyzq>9Jb zjwjfGXK2C~`hUePe5cqCwBRQ_PK~re0{RMp`Z>09?BHl()T|X$L0c2y(3yxIT88=? jipcr}jU_mCu2ApF)~6O>d^AnoG6KugWJZgN&F%gR!H+66 literal 0 HcmV?d00001 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/LisaWorkBook.class b/Algorithms/Implementation/LisaWorkBook.class new file mode 100644 index 0000000000000000000000000000000000000000..4db051f265dda495c50ba79fe4c030d6163461e4 GIT binary patch literal 987 zcmZuw&rj1}7=FI3-M4lv48}M4RS^{IKsSGont*UnLb7BC$qdGj7|Li^Ve4>oMo%V& z#G4lrW1<(q1dqZ2j2aFe{agGCI5^+d!_d&f`+j|%=l$7!KYxEc1~86s6)MhgbSvmV zuZjrz0@JU;!1(|hP;mi+977xz8Dh6x&-JGnqGo21LAqO8br{+UuIJoqR9Bq(eS4)s zh*Y&*k0EU?71r%1cCKQ3Yq_FdcfGaAAW$#*c4=eI-VF5|m#71dVFtBWYt&25tQ%zM zD7ahpgIay#POY|)4H9WcKqDed+VI^OnDftYkGkRu-Eam@E7oTnUPL=RrPVsk2x0cI$n+=}^b?oXS zL$`S*5o~~a&Qm|{Q9W8ErEY6AGH3f`T4Bj?E9A_X%nXTY4U)F%EYK=jby8t4l|Kbj ziOoP%q5dQ@pIO8p6#Ce~69EerNmi#fgFGWIj~;>T(}B7n8w){BLG4J=nWXG3q9M2c z4UvZjh#o;Ij2%Lr3e0r>cXdLFTC$LPq~jfQ_DDhwi1}@q?KOW96SZQJ#iLeS#QS&P zkRYD5l&GZ&#i+deg4io7Az7Ma=|UHYT}%nxC=2ByI)oy0Y1JsNTIwER21RH>|9~Vp zby?`Uh*1%t8OxToty8rh+i|k*4#0(chhy>w25^CxL2L1-_HI7~xk$&Vw2 zTj;_BF;hrm7TuVmi?BedCG_DD?W>FdJf?f`97A|Pk*_g=H!$&@xE+f5L_gkV%GN=Z x94JkKV;r3vDaJUuXxS%7H>m~XG|CteO-kGLA4)_(8Ijc4F(;7e`-pJF^dG5xxz7Lq literal 0 HcmV?d00001 diff --git a/Algorithms/Implementation/LisaWorkBook.java b/Algorithms/Implementation/LisaWorkBook.java new file mode 100644 index 0000000..272b40e --- /dev/null +++ b/Algorithms/Implementation/LisaWorkBook.java @@ -0,0 +1,47 @@ +import java.io.*; +import java.util.*; +import java.text.*; +import java.math.*; +import java.util.regex.*; + +public class LisaWorkBook { + + 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 numChapters = sc.nextInt(); + int numProblemsPerPage = sc.nextInt(); + int[] numProblemsInChapter = new int[numChapters]; + for(int i = 0;i < numProblemsInChapter.length;i++){ + numProblemsInChapter[i] = sc.nextInt(); + } + + int numSpecialProblems = 0; + int pos = 0; + int currentPage = 1; + for(int i = 0;i < numChapters;i++) + { + int numProblemsCurrentChapter = numProblemsInChapter[i]; + int numProblemsInCurrentPage = 0; + int numPages = (int) Math.ceil(numProblemsCurrentChapter / numProblemsPerPage); + int currentNumProblem = 1; + + for(int j = 1;j <= numPages;j++){ + + if( (j * numProblemsPerPage) > 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/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/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/Contests/ May World CodeSprint /ComparetheTriplets.mm b/Contests/ May World CodeSprint /ComparetheTriplets.mm new file mode 100644 index 0000000..9027711 --- /dev/null +++ b/Contests/ May World CodeSprint /ComparetheTriplets.mm @@ -0,0 +1,60 @@ +/* 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 + + +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 Date: Mon, 25 Jul 2016 22:32:49 -0400 Subject: [PATCH 22/46] Added TechHire CodeSprint solutions --- .../ComparetheTriplets.java | 44 +++++++ Contests/TechHire CodeSprint /FindPrefix.java | 63 ++++++++++ .../HackerRankTournament.java | 118 ++++++++++++++++++ .../PaintTheClassRoom.java | 54 ++++++++ 4 files changed, 279 insertions(+) create mode 100644 Contests/TechHire CodeSprint /ComparetheTriplets.java create mode 100644 Contests/TechHire CodeSprint /FindPrefix.java create mode 100644 Contests/TechHire CodeSprint /HackerRankTournament.java create mode 100644 Contests/TechHire CodeSprint /PaintTheClassRoom.java 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 From 74f8cdb10924ca4bad6c9919da58d955f1d6f28c Mon Sep 17 00:00:00 2001 From: "yanz67@gmail.com" Date: Sun, 9 Oct 2016 11:10:34 -0400 Subject: [PATCH 23/46] Added new solutions to Algorithms Domain --- Algorithms/Implementation/Encryption.class | Bin 1393 -> 0 bytes Algorithms/Implementation/LisaWorkBook.class | Bin 987 -> 0 bytes Algorithms/Implementation/RepeatedString.java | 38 ++++++++++++++++++ .../SockMerchant.playground/Contents.swift | 29 +++++++++++++ .../contents.xcplayground | 4 ++ .../contents.xcworkspacedata | 7 ++++ .../timeline.xctimeline | 11 +++++ 7 files changed, 89 insertions(+) delete mode 100644 Algorithms/Implementation/Encryption.class delete mode 100644 Algorithms/Implementation/LisaWorkBook.class create mode 100644 Algorithms/Implementation/RepeatedString.java create mode 100644 Algorithms/Implementation/SockMerchant.playground/Contents.swift create mode 100644 Algorithms/Implementation/SockMerchant.playground/contents.xcplayground create mode 100644 Algorithms/Implementation/SockMerchant.playground/playground.xcworkspace/contents.xcworkspacedata create mode 100644 Algorithms/Implementation/SockMerchant.playground/timeline.xctimeline diff --git a/Algorithms/Implementation/Encryption.class b/Algorithms/Implementation/Encryption.class deleted file mode 100644 index ed0b68f219746aeda15a0ad5ae3673017c6def2c..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 1393 zcmZux&rcIU6#k~W-Pv8X{3t9xR1_7ogg2jCzs>!?LD zM~j9%*sH^bkT78#t!UHHjt*fug^6(Ng)#?DMwGf9fb^OoZ>)P|- zk(ifp+(fS^48%MuetpzR7xFod5o?Y{LD2w?lDwvy6&39 zqDcSM#%?co_B?}6NNN@ZbyAUGH=Xq;-L~d?8R|ouP6)A8*S_V67SX;#;f)QUwkB;i z;msA=O6ruCc#m2lEHB*15P3N?7^Y48uO?F|(nOBiPLhhPblP@j89G)e{MYOa%dJXE zl$H3Ll{s0!9S#pLYzqx+WLHX8z0^N(q*Rv5N>Yr|!752nU7$}2tqC*mv`9({2{+?8 ziJdU%{)o>9Itr*K+d!j6`qKe`zjX=hB{>XR$SQ>(hlZ`#Mn0voZ}8LA0hZswH}wkA z66BG#Jp7~Wc_s_YS^|9o>fWNQ=A@`^`oq#^Ctq2CGtT?C9-1Aqc7DzQh zA74SA84?f>Pe~an5g-}M(S{0oO)AlkAl=Mrx|KDUAlW?<{tiigmul`&^?iyzq>9Jb zjwjfGXK2C~`hUePe5cqCwBRQ_PK~re0{RMp`Z>09?BHl()T|X$L0c2y(3yxIT88=? jipcr}jU_mCu2ApF)~6O>d^AnoG6KugWJZgN&F%gR!H+66 diff --git a/Algorithms/Implementation/LisaWorkBook.class b/Algorithms/Implementation/LisaWorkBook.class deleted file mode 100644 index 4db051f265dda495c50ba79fe4c030d6163461e4..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 987 zcmZuw&rj1}7=FI3-M4lv48}M4RS^{IKsSGont*UnLb7BC$qdGj7|Li^Ve4>oMo%V& z#G4lrW1<(q1dqZ2j2aFe{agGCI5^+d!_d&f`+j|%=l$7!KYxEc1~86s6)MhgbSvmV zuZjrz0@JU;!1(|hP;mi+977xz8Dh6x&-JGnqGo21LAqO8br{+UuIJoqR9Bq(eS4)s zh*Y&*k0EU?71r%1cCKQ3Yq_FdcfGaAAW$#*c4=eI-VF5|m#71dVFtBWYt&25tQ%zM zD7ahpgIay#POY|)4H9WcKqDed+VI^OnDftYkGkRu-Eam@E7oTnUPL=RrPVsk2x0cI$n+=}^b?oXS zL$`S*5o~~a&Qm|{Q9W8ErEY6AGH3f`T4Bj?E9A_X%nXTY4U)F%EYK=jby8t4l|Kbj ziOoP%q5dQ@pIO8p6#Ce~69EerNmi#fgFGWIj~;>T(}B7n8w){BLG4J=nWXG3q9M2c z4UvZjh#o;Ij2%Lr3e0r>cXdLFTC$LPq~jfQ_DDhwi1}@q?KOW96SZQJ#iLeS#QS&P zkRYD5l&GZ&#i+deg4io7Az7Ma=|UHYT}%nxC=2ByI)oy0Y1JsNTIwER21RH>|9~Vp zby?`Uh*1%t8OxToty8rh+i|k*4#0(chhy>w25^CxL2L1-_HI7~xk$&Vw2 zTj;_BF;hrm7TuVmi?BedCG_DD?W>FdJf?f`97A|Pk*_g=H!$&@xE+f5L_gkV%GN=Z x94JkKV;r3vDaJUuXxS%7H>m~XG|CteO-kGLA4)_(8Ijc4F(;7e`-pJF^dG5xxz7Lq diff --git a/Algorithms/Implementation/RepeatedString.java b/Algorithms/Implementation/RepeatedString.java new file mode 100644 index 0000000..30e4ab5 --- /dev/null +++ b/Algorithms/Implementation/RepeatedString.java @@ -0,0 +1,38 @@ +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/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 @@ + + + + + + + From f18acc2e97022ca4630f05c35c98136c61160e2f Mon Sep 17 00:00:00 2001 From: "yanz67@gmail.com" Date: Sun, 9 Oct 2016 11:44:03 -0400 Subject: [PATCH 24/46] Added Challenges --- Algorithms/Implementation/BonAppetit.java | 41 +++++++++++++++++++ Algorithms/Implementation/RepeatedString.java | 4 ++ 2 files changed, 45 insertions(+) create mode 100644 Algorithms/Implementation/BonAppetit.java 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/RepeatedString.java b/Algorithms/Implementation/RepeatedString.java index 30e4ab5..265c42a 100644 --- a/Algorithms/Implementation/RepeatedString.java +++ b/Algorithms/Implementation/RepeatedString.java @@ -1,3 +1,7 @@ +/* +Reapeated Strings +https://www.hackerrank.com/challenges/repeated-string +*/ import java.io.*; import java.util.*; import java.text.*; From 30b10f0956f44756f60bb8d1304cc516e9d6e186 Mon Sep 17 00:00:00 2001 From: "yanz67@gmail.com" Date: Sun, 9 Oct 2016 23:08:19 -0400 Subject: [PATCH 25/46] Added Kangaroo Solution --- Algorithms/Implementation/Kangaroo.java | 44 +++++++++++++++++++++++++ 1 file changed, 44 insertions(+) create mode 100644 Algorithms/Implementation/Kangaroo.java 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 From 14fa9e7b9efc2487392e43aec8e5f21a452a4854 Mon Sep 17 00:00:00 2001 From: "yanz67@gmail.com" Date: Mon, 10 Oct 2016 00:06:52 -0400 Subject: [PATCH 26/46] Another Two solutions Added --- .../Implementation/JumpingOnTheClouds.java | 39 +++++++++++++++++++ .../JumpingOnTheCloudsRevisited.java | 38 ++++++++++++++++++ 2 files changed, 77 insertions(+) create mode 100644 Algorithms/Implementation/JumpingOnTheClouds.java create mode 100644 Algorithms/Implementation/JumpingOnTheCloudsRevisited.java 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 From 138df4ca95354458beb65d8cedb04d7a5d13fc16 Mon Sep 17 00:00:00 2001 From: "yanz67@gmail.com" Date: Mon, 17 Oct 2016 14:43:40 -0400 Subject: [PATCH 27/46] Added Solutions From OpenBracket CodeSprint --- .../FraudulentActivityNotifications.java | 117 ++++++++++++++++++ .../ViralAdvertising.java | 33 +++++ 2 files changed, 150 insertions(+) create mode 100644 Contests/OpenBracket CodeSprint/FraudulentActivityNotifications.java create mode 100644 Contests/OpenBracket CodeSprint/ViralAdvertising.java 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 From 57bdc205d35c406674eea7ca2b460449273e7611 Mon Sep 17 00:00:00 2001 From: "yanz67@gmail.com" Date: Mon, 24 Oct 2016 23:23:45 -0400 Subject: [PATCH 28/46] Added Algorithms Domain Solutions --- Algorithms/Warmup/CircularArrayRotation.java | 38 ++++++++++++++++++++ Algorithms/Warmup/StrangeCounter.java | 28 +++++++++++++++ Algorithms/Warmup/ViralAdvertising.java | 30 ++++++++++++++++ 3 files changed, 96 insertions(+) create mode 100644 Algorithms/Warmup/CircularArrayRotation.java create mode 100644 Algorithms/Warmup/StrangeCounter.java create mode 100644 Algorithms/Warmup/ViralAdvertising.java diff --git a/Algorithms/Warmup/CircularArrayRotation.java b/Algorithms/Warmup/CircularArrayRotation.java new file mode 100644 index 0000000..50f7ae8 --- /dev/null +++ b/Algorithms/Warmup/CircularArrayRotation.java @@ -0,0 +1,38 @@ +/* +Circular Array Rotation + +https://www.hackerrank.com/challenges/circular-array-rotation +*/ + +import java.io.*; +import java.util.*; +import java.text.*; +import java.math.*; +import java.util.regex.*; + +public class CircularArrayRotation { + + public static void main(String[] args) { + Scanner in = new Scanner(System.in); + int n = in.nextInt(); + int k = in.nextInt(); + int q = in.nextInt(); + int[] a = new int[n]; + for(int a_i=0; a_i < n; a_i++){ + a[a_i] = in.nextInt(); + } + + int offset = k > 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/StrangeCounter.java b/Algorithms/Warmup/StrangeCounter.java new file mode 100644 index 0000000..7807682 --- /dev/null +++ b/Algorithms/Warmup/StrangeCounter.java @@ -0,0 +1,28 @@ +/* +Strange Counter + +https://www.hackerrank.com/challenges/strange-code + +*/ + +import java.io.*; +import java.util.*; +import java.text.*; +import java.math.*; +import java.util.regex.*; + +public class StrangeCounter { + + public static void main(String[] args) { + Scanner in = new Scanner(System.in); + long t = in.nextLong(); + + int time = 1; + long counter = 3; + while(time + counter <= t){ + time += counter; + counter *=2; + } + System.out.println(counter - (t - time)); + } +} \ No newline at end of file diff --git a/Algorithms/Warmup/ViralAdvertising.java b/Algorithms/Warmup/ViralAdvertising.java new file mode 100644 index 0000000..279d14f --- /dev/null +++ b/Algorithms/Warmup/ViralAdvertising.java @@ -0,0 +1,30 @@ +/* +Viral Advertising + +https://www.hackerrank.com/challenges/strange-advertising + +*/ + +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 From ed80586774fe39e08e66bd246f59ce67bd3ab2a1 Mon Sep 17 00:00:00 2001 From: "yanz67@gmail.com" Date: Fri, 28 Oct 2016 23:20:38 -0400 Subject: [PATCH 29/46] Added Apple and Orange Solution --- Algorithms/Implementation/AppleAndOrange.java | 51 +++++++++++++++++++ 1 file changed, 51 insertions(+) create mode 100644 Algorithms/Implementation/AppleAndOrange.java 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 From 8875f7d73f9d1df7fc5cc530f24cb60cc46cddf0 Mon Sep 17 00:00:00 2001 From: "yanz67@gmail.com" Date: Tue, 1 Nov 2016 15:17:42 -0400 Subject: [PATCH 30/46] Added Minimum Spaces Solution --- .../Contents.swift | 50 +++++++++++++++++++ .../contents.xcplayground | 4 ++ .../contents.xcworkspacedata | 7 +++ 3 files changed, 61 insertions(+) create mode 100644 Algorithms/Implementation/MiniumumDistances.playground/Contents.swift create mode 100644 Algorithms/Implementation/MiniumumDistances.playground/contents.xcplayground create mode 100644 Algorithms/Implementation/MiniumumDistances.playground/playground.xcworkspace/contents.xcworkspacedata diff --git a/Algorithms/Implementation/MiniumumDistances.playground/Contents.swift b/Algorithms/Implementation/MiniumumDistances.playground/Contents.swift new file mode 100644 index 0000000..7b64879 --- /dev/null +++ b/Algorithms/Implementation/MiniumumDistances.playground/Contents.swift @@ -0,0 +1,50 @@ +/* + 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 numIntegers: [Int] = readLine() +let input: [Int] = readLine() + +var numDictionary = [Int : Int]() + +var minDistance = Int.max + +var pos = 0 + +for num in input { + if let numPos = numDictionary[num] { + numDictionary[num] = pos - numPos + if numDictionary[num]! < minDistance { + minDistance = numDictionary[num]! + } + } else { + numDictionary[num] = pos + } + pos+=1 +} + +print(minDistance == Int.max ? -1 : minDistance) \ No newline at end of file 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 @@ + + + + + From adf10529af5dbbc203441f432577c4a55f477f17 Mon Sep 17 00:00:00 2001 From: "yanz67@gmail.com" Date: Tue, 1 Nov 2016 16:09:23 -0400 Subject: [PATCH 31/46] Added Equilize the Array Solution --- .../Contents.swift | 51 +++++++++++++++++++ .../contents.xcplayground | 4 ++ .../contents.xcworkspacedata | 7 +++ .../Contents.swift | 2 +- 4 files changed, 63 insertions(+), 1 deletion(-) create mode 100644 Algorithms/Implementation/EqualizeTheArray.playground/Contents.swift create mode 100644 Algorithms/Implementation/EqualizeTheArray.playground/contents.xcplayground create mode 100644 Algorithms/Implementation/EqualizeTheArray.playground/playground.xcworkspace/contents.xcworkspacedata 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/MiniumumDistances.playground/Contents.swift b/Algorithms/Implementation/MiniumumDistances.playground/Contents.swift index 7b64879..aa1e283 100644 --- a/Algorithms/Implementation/MiniumumDistances.playground/Contents.swift +++ b/Algorithms/Implementation/MiniumumDistances.playground/Contents.swift @@ -47,4 +47,4 @@ for num in input { pos+=1 } -print(minDistance == Int.max ? -1 : minDistance) \ No newline at end of file +print(minDistance == Int.max ? -1 : minDistance) From e1e6610082e57da93e62cbff3d36c5ec8eb28724 Mon Sep 17 00:00:00 2001 From: "yanz67@gmail.com" Date: Tue, 1 Nov 2016 20:45:47 -0400 Subject: [PATCH 32/46] Added Flatland Space Stations Solution --- .../Contents.swift | 55 +++++++++++++++++++ .../contents.xcplayground | 4 ++ .../contents.xcworkspacedata | 7 +++ .../Contents.swift | 32 ++++++----- 4 files changed, 84 insertions(+), 14 deletions(-) create mode 100644 Algorithms/Implementation/FlatlandsSpaceStations.playground/Contents.swift create mode 100644 Algorithms/Implementation/FlatlandsSpaceStations.playground/contents.xcplayground create mode 100644 Algorithms/Implementation/FlatlandsSpaceStations.playground/playground.xcworkspace/contents.xcworkspacedata diff --git a/Algorithms/Implementation/FlatlandsSpaceStations.playground/Contents.swift b/Algorithms/Implementation/FlatlandsSpaceStations.playground/Contents.swift new file mode 100644 index 0000000..374417d --- /dev/null +++ b/Algorithms/Implementation/FlatlandsSpaceStations.playground/Contents.swift @@ -0,0 +1,55 @@ +/* + Flatland Space Stations + + https://www.hackerrank.com/challenges/flatland-space-stations + + */ + +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))) +} \ 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/MiniumumDistances.playground/Contents.swift b/Algorithms/Implementation/MiniumumDistances.playground/Contents.swift index aa1e283..351bd82 100644 --- a/Algorithms/Implementation/MiniumumDistances.playground/Contents.swift +++ b/Algorithms/Implementation/MiniumumDistances.playground/Contents.swift @@ -26,25 +26,29 @@ public func readLine() -> [Int] { return words.map { Int($0)! } } -let numIntegers: [Int] = readLine() -let input: [Int] = readLine() +let info: [Int] = readLine() +var stationLocations: [Int] = readLine() -var numDictionary = [Int : Int]() +var previousStationLocation = -1 -var minDistance = Int.max +var maxDistance = 0 var pos = 0 -for num in input { - if let numPos = numDictionary[num] { - numDictionary[num] = pos - numPos - if numDictionary[num]! < minDistance { - minDistance = numDictionary[num]! +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 } - } else { - numDictionary[num] = pos } - pos+=1 + + print(max(maxDistance,(info[0] - previousStationLocation - 1))) } - -print(minDistance == Int.max ? -1 : minDistance) From 54f6a312bc634e6756e3ff225eba72626eb2a883 Mon Sep 17 00:00:00 2001 From: "yanz67@gmail.com" Date: Tue, 1 Nov 2016 22:19:45 -0400 Subject: [PATCH 33/46] Added Fair Rations Solution --- .../FairRations.playground/Contents.swift | 48 +++++++++++++++++++ .../contents.xcplayground | 4 ++ .../contents.xcworkspacedata | 7 +++ 3 files changed, 59 insertions(+) create mode 100644 Algorithms/Implementation/FairRations.playground/Contents.swift create mode 100644 Algorithms/Implementation/FairRations.playground/contents.xcplayground create mode 100644 Algorithms/Implementation/FairRations.playground/playground.xcworkspace/contents.xcworkspacedata diff --git a/Algorithms/Implementation/FairRations.playground/Contents.swift b/Algorithms/Implementation/FairRations.playground/Contents.swift new file mode 100644 index 0000000..62a1a98 --- /dev/null +++ b/Algorithms/Implementation/FairRations.playground/Contents.swift @@ -0,0 +1,48 @@ +/* + Fair Rations + https://www.hackerrank.com/challenges/fair-rations + + */ + +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 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 @@ + + + + + From bec77c7eaec7a1e5454d5ae0055b5d39eaebefc8 Mon Sep 17 00:00:00 2001 From: "yanz67@gmail.com" Date: Wed, 23 Nov 2016 19:02:48 -0500 Subject: [PATCH 34/46] Added Mini-Max Sum Solution --- Algorithms/Implementation/MiniMaxSum.java | 29 +++++++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 Algorithms/Implementation/MiniMaxSum.java 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 From 3e08fc85d2bb23f88edecf1be49cab1b9950c43e Mon Sep 17 00:00:00 2001 From: "yanz67@gmail.com" Date: Wed, 23 Nov 2016 19:23:30 -0500 Subject: [PATCH 35/46] Added Beautiful Days At The Movies Solution --- .../BeautifulDaysAtTheMovies.java | 44 +++++++++++++++++++ 1 file changed, 44 insertions(+) create mode 100644 Algorithms/Implementation/BeautifulDaysAtTheMovies.java 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 From 18e9d0c4923938c245cd7ac6c03029a286d764b3 Mon Sep 17 00:00:00 2001 From: "yanz67@gmail.com" Date: Wed, 23 Nov 2016 19:25:55 -0500 Subject: [PATCH 36/46] Added README --- README.md | 1 + 1 file changed, 1 insertion(+) create mode 100644 README.md 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 From dc2d8eda541222628a0aa01ac50903d64dcdc6aa Mon Sep 17 00:00:00 2001 From: mehtayash23 Date: Mon, 13 Feb 2017 20:38:00 +0530 Subject: [PATCH 37/46] Created MatrixLayerRotation.java This file contains a solution of Algorithm Implementation's Matrix Layer Rotation(Difficulty: Hard) on HackerRank. --- .../Implementation/MatrixLayerRotation.java | 204 ++++++++++++++++++ 1 file changed, 204 insertions(+) create mode 100644 Algorithms/Implementation/MatrixLayerRotation.java 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(); + } + } +} From 4f438c34ad867596f5f6413cece39c59bd2ec21e Mon Sep 17 00:00:00 2001 From: Yash Mehta Date: Tue, 14 Feb 2017 13:02:42 +0530 Subject: [PATCH 38/46] Created CamelCase.java This file contains the solution of Algorithm-> String -> Camel Case problem on HackerRank (https://www.hackerrank.com/challenges/camelcase). --- Algorithms/Strings/CamelCase.java | 56 +++++++++++++++++++++++++++++++ 1 file changed, 56 insertions(+) create mode 100644 Algorithms/Strings/CamelCase.java diff --git a/Algorithms/Strings/CamelCase.java b/Algorithms/Strings/CamelCase.java new file mode 100644 index 0000000..0d7b17e --- /dev/null +++ b/Algorithms/Strings/CamelCase.java @@ -0,0 +1,56 @@ +/* + * https://www.hackerrank.com/challenges/camelcase + * Alice wrote a sequence of words in CamelCase as a string of letters, , having the following properties: + - It is a concatenation of one or more words consisting of English letters. + - All letters in the first word are lowercase. + - For each of the subsequent words, the first letter is uppercase and rest of the letters are lowercase. + +Given , print the number of words in s on a new line. + +Input Format + +A single line containing string . + +Constraints + +Output Format + +Print the number of words in string . + +Sample Input + +saveChangesInTheEditor + +Sample Output + +5 + +Explanation + +String s contains five words: + save + Changes + In + The + Editor + +Thus, we print 5 on a new line. +*/ + +import java.util.Scanner; + +public class CamelCase { + public static void main(String[] args) { + Scanner in = new Scanner(System.in); + int count = 0; + String str = in.nextLine(); + char[] arr = str.toCharArray(); + for (int i = 0; i < arr.length; i++) { + if (Character.isUpperCase(arr[i])) { + count++; + } + } + // First word's letter will not be in upper case. So, we have to add +1 in final answer + System.out.println(count + 1); + } +} From 483f66f31d29fa038de826312581e5ce40c44318 Mon Sep 17 00:00:00 2001 From: Yash Mehta Date: Tue, 14 Feb 2017 13:21:40 +0530 Subject: [PATCH 39/46] Created BeautifulBinaryString.java This file contains the solution of HackerRank -> Algorithm -> String -> Beautiful Binary String ( https://www.hackerrank.com/challenges/beautiful-binary-string ) --- Algorithms/Strings/BeautifulBinaryString.java | 68 +++++++++++++++++++ 1 file changed, 68 insertions(+) create mode 100644 Algorithms/Strings/BeautifulBinaryString.java diff --git a/Algorithms/Strings/BeautifulBinaryString.java b/Algorithms/Strings/BeautifulBinaryString.java new file mode 100644 index 0000000..a39ba9f --- /dev/null +++ b/Algorithms/Strings/BeautifulBinaryString.java @@ -0,0 +1,68 @@ +//https://www.hackerrank.com/challenges/beautiful-binary-string +/* + Alice has a binary string, B, of length n. She thinks a binary string is beautiful if and only if it doesn't contain the substring "010". + + In one step, Alice can change a 0 to a 1 (or vice-versa). Count and print the minimum number of steps needed to make Alice see the string as beautiful. + + Input Format + + The first line contains an integer, (the length of binary string B). + The second line contains a single binary string, B, of length n. + + Constraints + + 1 <= n <= 100 + Each character in B belongs to {1,2} . + + Output Format + + Print the minimum number of steps needed to make the string beautiful. + + Sample Input 0 + + 7 + 0101010 + + Sample Output 0 + + 2 + + Sample Input 1 + + 5 + 01100 + + Sample Output 1 + + 0 + + Sample Input 2 + + 10 + 0100101010 + + Sample Output 2 + + 3 + */ +import java.io.BufferedReader; +import java.io.InputStreamReader; + +public class BeautifulBinaryString { + public static void main(String[] args) throws Exception { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + int count = 0; + final int n = Integer.parseInt(br.readLine()); + String str = br.readLine(); + final String stringToBeFound = "010"; + int lastIndex = 0; + while (lastIndex != -1) { + lastIndex = str.indexOf(stringToBeFound, lastIndex); + if (lastIndex != -1) { + count++; + lastIndex += stringToBeFound.length(); + } + } + System.out.println(count); + } +} From 2eb2480084d006465f9f5f6c7f0ddef68e0aadad Mon Sep 17 00:00:00 2001 From: Yash Mehta Date: Tue, 14 Feb 2017 13:34:47 +0530 Subject: [PATCH 40/46] Created DivisibleSumPairs.java This file contains the solution of HackerRank -> Algorithm -> Implementation -> Divisible Sum Pairs ( https://www.hackerrank.com/challenges/divisible-sum-pairs ) --- .../Implementation/DivisibleSumPairs.java | 50 +++++++++++++++++++ 1 file changed, 50 insertions(+) create mode 100644 Algorithms/Implementation/DivisibleSumPairs.java 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); + } +} From b413f702fb25f701e7770f4653b41e9da41ebff8 Mon Sep 17 00:00:00 2001 From: Yash Mehta Date: Tue, 14 Feb 2017 13:44:36 +0530 Subject: [PATCH 41/46] Created SaveThePrisoner.java This file contains the solution of HackerRank -> Algorithm -> Implementation -> Save The Prisoner ( https://www.hackerrank.com/challenges/save-the-prisoner ) --- .../Implementation/SaveThePrisoner.java | 63 +++++++++++++++++++ 1 file changed, 63 insertions(+) create mode 100644 Algorithms/Implementation/SaveThePrisoner.java 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); + } + } +} From 24d28a2e4e0dd793909d1d7ac0369b165e155f03 Mon Sep 17 00:00:00 2001 From: Yash Mehta Date: Tue, 14 Feb 2017 13:50:34 +0530 Subject: [PATCH 42/46] Created StrangeCounter.java This file contains a solution of HackerRank -> Algorithm -> Implementation -> Strange Counter ( https://www.hackerrank.com/challenges/strange-code ) --- Algorithms/Implementation/StrangeCounter.java | 14 ++++++++++++++ 1 file changed, 14 insertions(+) create mode 100644 Algorithms/Implementation/StrangeCounter.java 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)); + } +} From dac5f3cbb518ff518d67a7ec5b61b93e347049ad Mon Sep 17 00:00:00 2001 From: Yash Mehta Date: Tue, 14 Feb 2017 13:52:55 +0530 Subject: [PATCH 43/46] Created TheBomberGame.java This file contains a solution of the bomberman game problem on Hackerrank ( https://www.hackerrank.com/challenges/bomber-man ) --- Algorithms/Implementation/TheBomberGame.java | 78 ++++++++++++++++++++ 1 file changed, 78 insertions(+) create mode 100644 Algorithms/Implementation/TheBomberGame.java diff --git a/Algorithms/Implementation/TheBomberGame.java b/Algorithms/Implementation/TheBomberGame.java new file mode 100644 index 0000000..ec66ba7 --- /dev/null +++ b/Algorithms/Implementation/TheBomberGame.java @@ -0,0 +1,78 @@ +//https://www.hackerrank.com/challenges/bomber-man + +import java.util.Scanner; + +class TheBomberGame { + public static void main(String args[]) { + Scanner in = new Scanner(System.in); + int row = in.nextInt(); + int col = in.nextInt(); + char grid[][] = new char[row][col]; + long n = in.nextLong(); + String s; + // Take Input + for (int i = 0; i < row; i++) { + s = in.next(); + for (int j = 0; j < col; j++) { + grid[i][j] = s.charAt(j); + } + } + if (n == 1) { + printGrid(grid, row, col); + } else if (n % 2 == 0) { + for (int i = 0; i < row; i++) { + for (int j = 0; j < col; j++) { + System.out.print('O'); + } + System.out.println(); + } + } else if ((n - 3) % 4 == 0) { + manipulateGrid(grid, row, col); + printGrid(grid, row, col); + } else { + manipulateGrid(grid, row, col); + manipulateGrid(grid, row, col); + printGrid(grid, row, col); + } + + } + + // Make Changes to grid + public static char[][] manipulateGrid(char[][] grid, int row, int col) { + for (int i = 0; i < row; i++) { + for (int j = 0; j < col; j++) { + if (grid[i][j] == 'O') { + grid[i][j] = '|'; + if (i + 1 < row && grid[i + 1][j] != 'O') + grid[i + 1][j] = '|'; + if (j + 1 < col && grid[i][j + 1] != 'O') + grid[i][j + 1] = '|'; + if (i - 1 >= 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(); + } + } +} From da2fb2ea2d6ee50b302202ac8f34f31a61a10cdf Mon Sep 17 00:00:00 2001 From: Prabhakaran Date: Sun, 23 Feb 2020 23:27:07 +0530 Subject: [PATCH 44/46] Update PatternSyntaxChecker.java --- Java/Strings/PatternSyntaxChecker.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Java/Strings/PatternSyntaxChecker.java b/Java/Strings/PatternSyntaxChecker.java index 72858e8..46a9a77 100644 --- a/Java/Strings/PatternSyntaxChecker.java +++ b/Java/Strings/PatternSyntaxChecker.java @@ -42,6 +42,7 @@ 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{ @@ -54,4 +55,4 @@ public static void main(String[] args){ } } -} \ No newline at end of file +} From aeaa60ec2416d96cdd12194c31c86a130485df4c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?M=C3=A1t=C3=A9=20Sz=C3=A9les?= Date: Tue, 6 Oct 2020 20:18:31 +0200 Subject: [PATCH 45/46] Create GradingStudents.java --- .../Implementation/GradingStudents.java | 53 +++++++++++++++++++ 1 file changed, 53 insertions(+) create mode 100644 Algorithms/Implementation/GradingStudents.java 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(); + } +} From 1bd6d6a64aea655a8b4d8f8d6a302a0bb26052ee Mon Sep 17 00:00:00 2001 From: Avani Gokhale <36026630+avani112@users.noreply.github.com> Date: Thu, 8 Oct 2020 14:37:23 +0530 Subject: [PATCH 46/46] Create JavaDateAndTime.java --- Java/Introduction/JavaDateAndTime.java | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) create mode 100644 Java/Introduction/JavaDateAndTime.java diff --git a/Java/Introduction/JavaDateAndTime.java b/Java/Introduction/JavaDateAndTime.java new file mode 100644 index 0000000..3e50da6 --- /dev/null +++ b/Java/Introduction/JavaDateAndTime.java @@ -0,0 +1,24 @@ + + +class Result { + + public static String findDay(int month, int day, int year) { + Calendar calendar = Calendar.getInstance(); + calendar.set(year, month-1, day); + String result = ""; + int n = (calendar.get(Calendar.DAY_OF_WEEK)); + switch(n){ + case 1 : result= "SUNDAY"; break; + case 2 : result= "MONDAY"; break; + case 3 : result= "TUESDAY"; break; + case 4 : result= "WEDNESDAY"; break; + case 5 : result= "THURSDAY";break; + case 6 : result= "FRIDAY"; break; + case 7 : result= "SATURDAY"; break; + } + return result; + + } + +} +