Hackerrank – Detect HTML Tags
Problem Statement A description of the problem can be found on Hackerrank. Solution Parse all tags by regex pattern
Problem Statement A description of the problem can be found on Hackerrank. Solution Parse all tags by regex pattern
Problem Statement A description of the problem can be found on Hackerrank. Solution Parse all tags with attributes. Then parse only tags and attributes. Group attributes by tag name. Sort grouped tags and accordingly attributes. I created solution in: Java Scala All solutions are also available on my GitHub. Java
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 |
import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Scanner; import java.util.Set; import java.util.TreeMap; import java.util.TreeSet; import java.util.regex.Matcher; import java.util.regex.Pattern; public class DetectHtmlAttributes { private static final String REGEX = "<[a-z0-9]+(\\s+[a-z]+=[\\\"\\'][a-zA-Z\\[\\]\\-\\/\\\\:\\.\\s_\\?!\\d;\\(\\),#@\\{\\}=%\\&\\|\\+\\*]*[\\\"\\'])*(\\s+/)?>"; public static void main(String[] args) { Scanner scanner = new Scanner(System.in); Pattern regex = Pattern.compile(REGEX); int tests = Integer.parseInt(scanner.nextLine()); List<String> tagsWithAttributes = new ArrayList<>(); for(int i = 0; i < tests; i++) { String line = scanner.nextLine(); Matcher matcher = regex.matcher(line); while(matcher.find()) { tagsWithAttributes.add(matcher.group()); } } Map<String, Set<String>> map = new TreeMap<>(); for(String tagAtt : tagsWithAttributes) { Pattern tagPattern = Pattern.compile("<[a-z0-9]+"); Matcher tagMatcher = tagPattern.matcher(tagAtt); String tag = null; Set<String> attributes = new TreeSet<>(); if(tagMatcher.find()) { tag = tagMatcher.group().replace("<", ""); } Pattern attPattern = Pattern .compile("[a-z]+=[\\\"\\'][a-zA-Z\\[\\]\\-\\/\\\\:\\.\\s_\\?!\\d;\\(\\),#@\\{\\}=%\\&\\|\\+\\*]*[\\\"\\']"); Matcher attMatcher = attPattern.matcher(tagAtt); while(attMatcher.find()) { attributes .add(attMatcher .group() .trim() .replaceAll( "=[\\\"\\'][a-zA-Z\\[\\]\\-\\/\\\\:\\.\\s_\\?!\\d;\\(\\),#@\\{\\}=%\\&\\|\\+\\*]*[\\\"\\']", "")); } Set<String> mapSet = map.get(tag); if(mapSet != null && !mapSet.isEmpty()) { mapSet.addAll(attributes); map.put(tag, mapSet); } else { map.put(tag, attributes); } } StringBuilder sb = new StringBuilder(); for(String tag : map.keySet()) { sb.append(tag); sb.append(":"); for(String attribute : map.get(tag)) { sb.append(attribute); sb.append(","); } if(!map.get(tag).isEmpty()) { sb.deleteCharAt(sb.length() - 1); } System.out.println(sb); sb.delete(0, sb.length()); } scanner.close(); } } |
Scala
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 |
import scala.io.Source import scala.collection.mutable.Map object DetectHtmlAttributes extends App { private[this] val TAG_WITH_ATTRIBUTE_REGEX = "<[a-z0-9]+(\\s+[a-z]+=[\\\"\\'][a-zA-Z\\[\\]\\-\\/\\\\:\\.\\s_\\?!\\d;\\(\\),#@\\{\\}=%\\&\\|\\+\\*]*[\\\"\\'])*(\\s+/)?>".r private[this] val TAG_NAME_REGEX = "<[a-z0-9]+".r private[this] val ATTRIBUTE_REGEX = "[a-z]+=[\\\"\\'][a-zA-Z\\[\\]\\-\\/\\\\:\\.\\s_\\?!\\d;\\(\\),#@\\{\\}=%\\&\\|\\+\\*]*[\\\"\\']".r private[this] val ATTRIBUTE_VALUE_PATTERN = "=[\\\"\\'][a-zA-Z\\[\\]\\-\\/\\\\:\\.\\s_\\?!\\d;\\(\\),#@\\{\\}=%\\&\\|\\+\\*]*[\\\"\\']" val lines = Source.stdin.getLines().drop(1).toList val tagsWithAttributes = lines.map(findTagsWithAttributes).flatten val tagNames = tagsWithAttributes.map(parseTagName).flatten val attributes = tagsWithAttributes.map(parseAttributes) val tagGroups = groupAttributesByTags() createOutput() def findTagsWithAttributes(line: String): List[String] = { TAG_WITH_ATTRIBUTE_REGEX.findAllMatchIn(line).map(_.toString()).toList } def parseTagName(tag: String): List[String] = { TAG_NAME_REGEX.findAllMatchIn(tag).map(_.toString).map(_.replace("<", "")).toList } def parseAttributes(tag: String): List[String] = { ATTRIBUTE_REGEX.findAllMatchIn(tag).map(_.toString) .map(_.replaceAll(ATTRIBUTE_VALUE_PATTERN, "")).toList } def groupAttributesByTags(): Map[String, List[String]] = { val tagGroups: Map[String, List[String]] = Map.empty tagNames.indices.foreach(i => { val tag = tagNames(i) val attributeList = attributes(i) val actualAttributes = tagGroups.getOrElse(tag, Nil) tagGroups.put(tag, attributeList:::actualAttributes) }) tagGroups } def createOutput(): Unit = { val sortedKeys = tagGroups.keys.toList.sorted sortedKeys.foreach(tag => { val sortedAttributes = tagGroups.get(tag).get.distinct.sorted println(tag + ":" + sortedAttributes.mkString(",")) }) } } |
Problem Statement A description of the problem can be found on Hackerrank. Solution Count of all routes as multiplication of routes between towns. I created solution in: Java JavaScript Scala Ruby All solutions are also available on my GitHub. Java
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
import java.util.Scanner; public class ConnectingTowns { public static void main(String[] args) { Scanner stdin = new Scanner(System.in); int cases = stdin.nextInt(); for(int i = 0; i < cases; i++) { int l = stdin.nextInt(); int routes = 1; for(int j = 0; j < l - 1; j++) { routes *= stdin.nextInt(); routes %= 1234567; } System.out.println(routes); } stdin.close(); } } |
JavaScript
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
function processData(input) { var lines = input.split('\n'); var n = parseInt(lines[0]); var index = 2; for(var i = 0; i < n; i++) { var arr = lines[index].split(" ").map(i => parseInt(i)); var routes = 1; for(var j = 0; j < arr.length; j++) { routes *= arr[j]; routes %= 1234567; } console.log(routes); index += 2; } } process.stdin.resume(); process.stdin.setEncoding("ascii"); _input = ""; process.stdin.on("data", function (input) { _input += input; }); process.stdin.on("end", function () { processData(_input); }); |
Scala
|
1 2 3 4 5 6 7 8 |
import scala.io.Source object ConnectingTowns extends App { val lines = Source.stdin.getLines().drop(1) val routesArray = lines.toList.filter(_.contains(" ")) val routes = routesArray.map(_.split(" ").map(_.toLong).foldLeft(1L)(_ * _ % 1234567)) println(routes.mkString("\n")) } |
Ruby
|
1 2 3 4 5 6 7 8 9 10 11 |
cases = gets.chomp.to_i cases.times do result = 1 towns = gets.chomp.to_i routes = gets.chomp.split.map { |e| e.to_i } for i in 0..towns - 2 do result *= routes[i] result %= 1234567 end puts result end |
Problem Statement A description of the problem can be found on Hackerrank. Solution I used Euclid’s algorithm for computing Greatest Common Divisor. I created solution in: Scala All solutions are also available on my GitHub. Scala
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
object ComputingGcd { def gcd(x: Int, y: Int): Int = { if(y == 0) x else gcd(y, x % y) } /**This part handles the input/output. Do not change or modify it **/ def acceptInputAndComputeGCD(pair:List[Int]) = { println(gcd(pair.head,pair.reverse.head)) } def main(args: Array[String]) { /** The part relates to the input/output. Do not change or modify it **/ acceptInputAndComputeGCD(readLine().trim().split(" ").map(x=>x.toInt).toList) } } |
Problem Statement A description of the problem can be found on Hackerrank. Solution The implementation according to Longest Common Subsequence Problem. Ruby solutions is implemented with the same algorithm as Java solution. One hackerrank test with Ruby solution failed on timeout. I created solution in: Java Ruby All solutions are also available on my GitHub. […]
Problem Statement A description of the problem can be found on Hackerrank. Solution Sort the input array ascending. For element at index i do difference with element at index i+1. Find the minimum difference. Check all elements and find all pair that have this minimum difference. Print found elements ascending. I created solution in: Java […]
Problem Statement A description of the problem can be found on Hackerrank. Solution I created solution in: Java JavaScript Ruby All solutions are also available on my GitHub. Java
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 |
import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Scanner; public class BuildingList { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int testCases = Integer.parseInt(scanner.next()); for (int i = 0; i < testCases; i++) { int length = Integer.parseInt(scanner.next()); String input = scanner.next(); List<String> result = new ArrayList<String>(); combine(result, input, 0, ""); Collections.sort(result); for (String s : result) { System.out.println(s); } } scanner.close(); } private static void combine(List<String> result, String input, int start, String actual) { for (int i = start; i < input.length(); i++) { String out = actual; actual += input.charAt(i); result.add(actual); if(i < input.length()) { combine(result, input, i + 1, out); } } } } |
JavaScript
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
'use strict'; var combine = (result, input, start, actual) => { for(let i = start; i < input.length; i++) { let out = actual; actual += input.charAt(i); result.push(actual); if(i < input.length) { combine(result, input, i + 1, out); } } }; const processData = input => { let lines = input.split('\n'); let index = 1; for(let i = 0; i < parseInt(lines[0]); i++) { let length = parseInt(lines[index++]); let input = lines[index++]; let result = []; combine(result, input, 0, ''); result.sort((a, b) => a.localeCompare(b)); console.log(result.join('\n')); } }; process.stdin.resume(); process.stdin.setEncoding("ascii"); var _input = ""; process.stdin.on("data", input => _input += input); process.stdin.on("end", () => processData(_input)); |
Ruby
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
def combine(result, input, start, actual) for i in start...input.length do out = actual actual += input[i] result << actual if i < input.length combine(result, input, i + 1, out); end end end test_cases = gets.chomp.to_i test_cases.times do length = gets.strip.chomp.to_i input = gets.strip.chomp.to_s result = [] combine(result, input, 0, '') result.sort! {|a, b| a <=> b} puts result.join("\n") end |
Problem Statement A description of the problem can be found on Hackerrank. Solution Sum all elements. The result is sum / 2. I created solution in: Java JavaScript Scala Ruby All solutions are also available on my GitHub. Java
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
import java.util.*; public class BdayGift { public static void main(String[] args) { Scanner stdin = new Scanner(System.in); int tests = stdin.nextInt(); long sum = 0; for(int i = 0; i < tests; i++) { sum += stdin.nextInt(); } System.out.format("%.1f", (double) sum / 2); stdin.close(); } } |
JavaScript
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
'use strict'; var _ = require('lodash'); const processData = input => { let arr = input.split('\n').slice(1).map(i => parseInt(i)) let sum = _.sum(arr); console.log((sum / 2) + (sum % 2 == 0 ? '.0' : '')); }; process.stdin.resume(); process.stdin.setEncoding("ascii"); var _input = ""; process.stdin.on("data", input => _input += input); process.stdin.on("end", () => processData(_input)); |
Scala
|
1 2 3 4 5 6 |
import scala.io.Source object BdayGift extends App { val lines = Source.stdin.getLines().drop(1).map(_.toLong) printf("%.1f", lines.sum.toDouble / 2) } |
Ruby
|
1 2 3 4 5 6 7 8 |
balls = gets.chomp.to_i expected_num = 0 balls.times do input = gets.chomp.to_i expected_num += input end expected_num /= 2.0 puts "#{format('%.1f', expected_num)}" |
Problem Statement A description of the problem can be found on Hackerrank. Solution Divide the input string into two halves. Count all common character in the halves. A result is difference between length of the one half and count of the common characters. Different solution deletes common characters from the second half. The result is […]
Problem Statement A description of the problem can be found on Hackerrank. Solution Iterate through all string characters. If actual character i is different then character i-1 then use character i for next comparison. If they are not equal increment a deletion counter. Print the value of the counter. I created solution in: Java JavaScript […]