hackerrank - snippets

अब Quizwiz के साथ अपने होमवर्क और परीक्षाओं को एस करें!

Tax content extractor. In a tag-based language like XML or HTML, contents are enclosed between a start tag and an end tag like <tag>contents</tag>. Note that the corresponding end tag starts with a /. Given a string of text in a tag-based language, parse this text and retrieve the contents enclosed within sequences of well-organized tags meeting the following criterion: The name of the start and end tags must be same. The HTML code <h1>Hello World</h2> is not valid, because the text starts with an h1 tag and ends with a non-matching h2 tag. Tags can be nested, but content between nested tags is considered not valid. For example, in <h1><a>contents</a>invalid</h1>, contents is valid but invalid is not valid. Tags can consist of any printable characters.

///code here String pattern= "(<)(.+)(>)([-\\w!@\\#$%^&\\*()_+|~=`\"\\{\\}\\[\\]:'\\, ]+)(</)(\\2)(>)"; Pattern r = Pattern.compile(pattern, Pattern.MULTILINE); Matcher m = r.matcher(line); if (m.find()) { do { System.out.println(m.group(4)); } while (m.find()); } else { System.out.println("None"); } testCases--;

java bigdecimal Java's BigDecimal class can handle arbitrary-precision signed decimal numbers. Let's test your knowledge of them! Given an array, , of real number strings, sort them in descending order — but wait, there's more! Each number must be printed in the exact same format as it was read from stdin, meaning that is printed as , and is printed as . If two numbers represent numerically equivalent values (e.g., ), then they must be listed in the same order as they were received as input). Complete the code in the unlocked section of the editor below. You must rearrange array 's elements according to the instructions above.

//Write your code here Comparator customComparator = new Comparator<String>(){ @Override public int compare(String s1, String s2){ BigDecimal a = new BigDecimal(s1); BigDecimal b = new BigDecimal(s2); return b.compareTo(a); } }; Arrays.sort(s,0,n,customComparator);

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: Some valid IP address: 000.12.12.034 121.234.12.12 23.45.12.56 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 which contains a String . The string should contain the correct regular expression. (MyRegex class MUST NOT be public)

//Write your code here class MyRegex{ String from255 = "(25[0-5]|2[0-4][0-9]|[01]?[0-9]?[0-9])"; String pattern = String.format("%s.%s.%s.%s", from255, from255, from255, from255); }

java biginteger 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 a long integer. Use the power of Java's BigInteger class and solve this problem.

Scanner cin=new Scanner(System.in); BigInteger a=cin.nextBigInteger(),b=cin.nextBigInteger(); System.out.println(a.add(b)); System.out.println(a.multiply(b));

java 1D array The code in your editor does the following: Reads an integer from stdin and saves it to a variable, , denoting some number of integers. Reads integers corresponding to from stdin and saves each integer to a variable, . Attempts to print each element of an array of integers named . Write the following code in the unlocked portion of your editor: Create an array, , capable of holding integers. Modify the code in the loop so that it saves each sequential value to its corresponding location in the array. For example, the first value must be stored in , the second value must be stored in , and so on.

Scanner scan = new Scanner(System.in); int n = scan.nextInt(); int [] a = new int[n]; for (int i = 0 ; i < n; i++) { a[i] = scan.nextInt(); }

java regex2 - duplicate words In this challenge, we use regular expressions (RegEx) to remove instances of words that are repeated more than once, but retain the first occurrence of any case-insensitive repeated word. For example, the words love and to are repeated in the sentence I love Love to To tO code. Can you complete the code in the editor so it will turn I love Love to To tO code into I love to code? To solve this challenge, complete the following three lines: Write a RegEx that will match any repeated word. Complete the second compile argument so that the compiled RegEx is case-insensitive. Write the two necessary arguments for replaceAll such that each repeated word is replaced with the very first instance the word found in the sentence. It must be the exact first occurrence of the word, as the expected output is case-sensitive.

String regex = "\\b(\\w+)(\\W+\\1\\b)+"; Pattern p = Pattern.compile(regex, Pattern.CASE_INSENSITIVE); // Check for subsequences of input that match the compiled pattern while (m.find()) { input = input.replaceAll(m.group(), m.group(1)); }

java comparator - medium Comparators are used to compare two objects. In this challenge, you'll create a comparator and use it to sort an array. The Player class is provided for you in your editor. It has fields: a String and a integer. Given an array of Player objects, write a comparator that sorts them in order of decreasing score; if or more players have the same score, sort those players alphabetically by name. To do this, you must create a Checker class that implements the Comparator interface, then write an int compare(Player a, Player b) method implementing the Comparator.compare(T o1, T o2) method. Input Format Input from stdin is handled by the locked stub code in the Solution class. The first line contains an integer, , denoting the number of players.Each of the subsequent lines contains a player's and , respectively.

class Checker implements Comparator<Player>{ @Override public int compare(Player p1, Player p2){ if(p1.score == p2.score){ return p1.name.compareTo(p2.name); } else { return p2.score - p1.score; } } }

java stack - medium A string containing only parentheses is balanced if the following is true: 1. if it is an empty string 2. if A and B are correct, AB is correct, 3. if A is correct, (A) and {A} and [A] are also correct. Examples of some correctly balanced strings are: "{}()", "[{()}]", "({()})" Examples of some unbalanced strings are: "{}(", "({)}", "[[", "}{" etc. Given a string, determine if it is balanced or not. Input Format There will be multiple lines in the input file, each having a single non-empty string. You should read input till end-of-file. The part of the code that handles input operation is already provided in the editor. Output Format For each case, print 'true' if the string is balanced, 'false' otherwise. Sample Input {}() ({()}) {}( [] Sample Output true true false true

class Solution{ static Map<Character,Character> tbl; static boolean solve(String s){ Stack<Character> arr=new Stack<Character>(); for(int i=0;i<s.length();i++){ if(tbl.containsKey(s.charAt(i)))arr.push(s.charAt(i)); else if(arr.empty() || tbl.get(arr.pop())!=s.charAt(i))return false; } return arr.empty(); } public static void main(String[]args){ tbl=new HashMap<Character,Character>(); tbl.put('[',']'); tbl.put('{','}'); tbl.put('(',')'); Scanner cin=new Scanner(System.in); for(;cin.hasNext();){ System.out.println(solve(cin.nextLine())); } } }

valid username regular expressn.You are updating the username policy on your company's internal networking platform. According to the policy, a username is considered valid if all the following constraints are satisfied: The username consists of to characters inclusive. If the username consists of less than or greater than characters, then it is an invalid username. The username can only contain alphanumeric characters and underscores (_). Alphanumeric characters describe the character set consisting of lowercase characters , uppercase characters , and digits . The first character of the username must be an alphabetic character, i.e., either lowercase character or uppercase character ..

class UsernameValidator { /* * Write regular expression here. */ public static final String regularExpression = "[a-zA-Z][a-zA-Z0-9_]{7,29}$"; }

java subarray We define the following: A subarray of an -element array is an array composed from a contiguous block of the original array's elements. For example, if , then the subarrays are , , , , , and . Something like would not be a subarray as it's not a contiguous subsection of the original array. The sum of an array is the total sum of its elements.An array's sum is negative if the total sum of its elements is negative.An array's sum is positive if the total sum of its elements is positive. Given an array of integers, find and print its number of negative subarrays on a new line. Sample Input 5 1 -2 4 -5 1 Sample Output 9

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 in = new Scanner(System.in); int size = in.nextInt(); int[] arr = new int[size]; for (int i = 0; i < size; i++) { arr[i] = in.nextInt(); } in.close(); System.out.println(negativeSubarrays(arr)); } private static int negativeSubarrays(int[] arr) { int count = 0; for (int i = 0; i < arr.length; i++) { int sum = 0; for (int j = i; j < arr.length; j++) { sum += arr[j]; if (sum < 0) { count++; } } } return count; } }

java stack - medium balanaced A string containing only parentheses is balanced if the following is true: 1. if it is an empty string 2. if A and B are correct, AB is correct, 3. if A is correct, (A) and {A} and [A] are also correct. Examples of some correctly balanced strings are: "{}()", "[{()}]", "({()})" Examples of some unbalanced strings are: "{}(", "({)}", "[[", "}{" etc. Given a string, determine if it is balanced or not.

import java.util.*; class Solution{ static Map<Character, Character> tbl; static boolean solve(String s){ Stack<Character> arr = new Stack<Character>(); for(int i = 0; i < s.length(); i++){ if (tbl.containsKey(s.charAt(i))){ arr.push(s.charAt(i)); } else if(arr.empty() || tbl.get(arr.pop()) != s.charAt(i)){ return false; } } return arr.empty(); } public static void main(String[]args){ tbl=new HashMap<Character,Character>(); tbl.put('[',']'); tbl.put('{','}'); tbl.put('(',')'); Scanner sc =new Scanner(System.in); while(sc.hasNext()){ System.out.println(solve(sc.nextLine())); } } }

java 2d array 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

import java.util.Scanner; public class Solution { public static void main(String[] args) { Scanner scan = new Scanner(System.in); int arr[][] = new int[6][6]; for (int row = 0; row < 6; row++) { for (int col = 0; col < 6; col++) { arr[row][col] = scan.nextInt(); } } scan.close(); System.out.println(maxHourglass(arr)); } public static int maxHourglass(int [][] arr) { int max = Integer.MIN_VALUE; for (int row = 0; row < 4; row++) { for (int col = 0; col < 4; col++) { int sum = findSum(arr, row, col); max = Math.max(max, sum); } } return max; } private static int findSum(int [][] arr, int r, int c) { int sum = arr[r+0][c+0] + arr[r+0][c+1] + arr[r+0][c+2] + arr[r+1][c+1] + arr[r+2][c+0] + arr[r+2][c+1] + arr[r+2][c+2]; return sum; } }

prime checker - medium You are given a class Solution and its main method in the editor. Your task is to create a class Prime. The class Prime should contain a single method checkPrime. The locked code in the editor will call the checkPrime method with one or more integer arguments. You should write the checkPrime method in such a way that the code prints only the prime numbers. Please read the code given in the editor carefully. Also please do not use method overloading!

import java.util.regex.*; import static java.lang.System.in; class Prime { void checkPrime(int... numbers) { for (int num : numbers) { if (isPrime(num)) { System.out.print(num + " "); } } System.out.println(); } boolean isPrime(int n) { if (n < 2) { return false; } else if (n == 2) { // account for even numbers now, so that we can do i+=2 in loop below return true; } else if (n % 2 == 0) { // account for even numbers now, so that we can do i+=2 in loop below return false; } int sqrt = (int) Math.sqrt(n); for (int i = 3; i <= sqrt; i += 2) { // skips even numbers for faster results if (n % i == 0) { return false; } } return true; } }

Can you access? medium You are given a class Solution and an inner class Inner.Private. The main method of class Solution takes an integer as input. The powerof2 in class Inner.Private checks whether a number is a power of . You have to call the method powerof2 of the class Inner.Private from the main method of the class Solution.

o = new Inner().new Private(); System.out.println(num + " is " + ((Solution.Inner.Private) o).powerof2(num));

java output formatting - easy Sample Input java 100 cpp 65 python 50 Sample Output ================================ java 100 cpp 065 python 050 ================================

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 in = new Scanner(System.in); System.out.println("================================"); for(int i = 0; i < 3; i++){ String str = in.next(); int num = in.nextInt(); System.out.printf("%-14s %03d %n", str, num); } System.out.println("================================"); } }

java arraylist - easy 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 FormatThe first line has an integer . In each of the next lines there will be an integer denoting number of integers on that line and then there will be space-separated integers. In the next line there will be an integer denoting number of queries. Each query will consist of two integers and .

public class Solution { public static void main(String[] args) { Scanner scan = new Scanner(System.in); int n = scan.nextInt(); /* Save numbers in 2-D ArrayList */ ArrayList<ArrayList<Integer>> lists = new ArrayList<>(); for (int row = 0; row < n; row++) { int d = scan.nextInt(); ArrayList<Integer> list = new ArrayList<>(); for (int col = 0; col < d; col++) { list.add(scan.nextInt()); } lists.add(list); } /* Answer the queries */ int q = scan.nextInt(); for (int i = 0; i < q; i++) { int x = scan.nextInt(); int y = scan.nextInt(); ArrayList<Integer> list = lists.get(x-1); if (y <= list.size()) { System.out.println(list.get(y-1)); } else { System.out.println("ERROR!"); } } scan.close(); } }

java primality test A prime number is a natural number greater than whose only positive divisors are and itself. For example, the first six prime numbers are , , , , , and . Given a large integer, , use the Java BigInteger class' isProbablePrime method to determine and print whether it's prime or not prime.

public class Solution { public static void main(String[] args) throws IOException { Scanner scan = new Scanner(System.in); BigInteger n = scan.nextBigInteger(); scan.close(); System.out.println(n.isProbablePrime(10) ? "prime" : "not prime"); } }

stdin and stdout II - easy There are three lines of output: On the first line, print String: followed by the unaltered String read from stdin. On the second line, print Double: followed by the unaltered double read from stdin. On the third line, print Int: followed by the unaltered integer read from stdin. To make the problem easier, a portion of the code is already provided in the editor. Note: If you use the nextLine() method immediately following the nextInt() method, recall that nextInt() reads integer tokens; because of this, the last newline character for that line of integer input is still queued in the input buffer and the next nextLine() will be reading the remainder of the integer line (which is empty). Sample Input 42 3.1415 Welcome to HackerRank's Java tutorials! Sample Output String: Welcome to HackerRank's Java tutorials! Double: 3.1415 Int: 42

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 in = new Scanner(System.in); int a = in.nextInt(); double b = in.nextDouble(); in.nextLine(); String s = in.nextLine(); System.out.println("String: " + s); System.out.println("Double: " + b); System.out.println("Int: " + a); } }

java if/else - easy Given an integer, , perform the following conditional actions: If is n odd, print Weird If is even and in the inclusive range of 2 to 5, print Not Weird If is even and in the inclusive range of 5 to 20, print Weird If is even and greater than 20, print Not Weird Complete the stub code provided in your editor to print whether or not is weird.

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 in = new Scanner(System.in); int n = in.nextInt(); String ans = ""; if (n % 2 == 1){ System.out.println("Weird"); } else if (n >= 2 && n <= 5){ System.out.println("Not Weird"); } else if (n >= 6 && n <= 20) { System.out.println("Weird"); } else if (n > 20) { System.out.println("Not Weird"); } System.out.println(ans); } }

java 1D array (part 2) - medium Let's play a game on an array! You're standing at index of an -element array named . From some index (where ), you can perform one of the following moves: Move Backward: If cell exists and contains a , you can walk back to cell . Move Forward:If cell contains a zero, you can walk to cell .If cell contains a zero, you can jump to cell .If you're standing in cell or the value of , you can walk or jump off the end of the array and win the game. In other words, you can move from index to index , , or as long as the destination index is a cell containing a . If the destination index is greater than , you win the game. Sample Input STDIN Function ----- -------- 4 q = 4 (number of queries) 5 3 game[] size n = 5, leap = 3 (first query) 0 0 0 0 0 game = [0, 0, 0, 0, 0] 6 5 game[] size n = 6, leap = 5 (second query) 0 0 0 1 1 1 . . . 6 3 0 0 1 1 1 0 3 1 0 1 0 Sample Output YES YES NO NO

public static boolean canWin(int leap, int[] game) { // Return true if you can win the game; otherwise, return false. return solve(leap, game, 0); } private static boolean solve(int leap, int[] game, int i){ if (i >= game.length) { return true; } else if (i < 0 || game[i] == 1) { return false; } game[i] = 1; return solve(leap, game, i + leap) || solve(leap, game, i + 1) || solve(leap, game, i-1); }

javalist - easy 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

public static void main(String[] args) { Scanner cin=new Scanner(System.in); int n=cin.nextInt(); List l=new ArrayList(); for(int i=0;i<n;i++)l.add(cin.nextInt()); n=cin.nextInt(); for(int i=0;i<n;i++){ String s=cin.next(); if(s.equals("Insert")){ int x=cin.nextInt(),y=cin.nextInt(); l.add(x,y); }else{ int x=cin.nextInt(); l.remove(x); } } for(int i=0;i<l.size();i++)System.out.print(l.get(i)+" "); }

java 1d array (part 2) - medium

static boolean didWinGame(String[] gameArray,int jumpLength, int currentPos,int lastJumpPos) { boolean didWin = false; int range = currentPos; while(range < gameArray.length-1 && gameArray[range+1].equals("0")){ range++; } if(range == gameArray.length-1) return true; int lowRange = range; while(lowRange>lastJumpPos && gameArray[lowRange-1].equals("0") && (lowRange+jumpLength) > range+1 ){ lowRange--; } currentPos = lowRange; for(int i = currentPos;i<=range;i++){ if((i+jumpLength)<gameArray.length && gameArray[i+jumpLength].equals("0") && jumpLength!=0){ didWin = didWinGame(gameArray,jumpLength,i+jumpLength,i); } if(didWin || (i+jumpLength)>=gameArray.length || (i+1)>=gameArray.length){ didWin = true; break; } } return didWin; }


संबंधित स्टडी सेट्स

Finance 302 Chapter 8 Risk and Return

View Set

Study Island: Organism Interactions and Population Dynamics

View Set

Inquizitive chap. 3: Texas in The Federal Government

View Set

license quizlet knowledge test: beg-end of chp 4 https://www.michigan.gov/documents/sos/WEDMK_Chapter_Four_Traffic_Laws_613800_7.pdf --> the chp 4 pdf

View Set

BRM's (Biological Response Modifiers) used for RA

View Set