Popis problému
Celý popis zadania sa nacháza – Hackerrank.
Riešenie
Pre všetky riadky spočítaj výskyt tohto regulárneho výrazu:
\w+{substring}\w+
Vytvoril som riešenie v týchto programovacích jazykoch:
Všetky riešenia sú dostupné aj na mojom GitHub profile.
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 |
import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; public class FindSubstring { public static void main(String[] args) { Scanner stdin = new Scanner(System.in); int linesCount = Integer.parseInt(stdin.nextLine()); String[] lines = new String[linesCount]; for(int i = 0; i < linesCount; i++) { lines[i] = stdin.nextLine(); } int substringCount = Integer.parseInt(stdin.nextLine()); String[] substrings = new String[substringCount]; for(int i = 0; i < substringCount; i++) { substrings[i] = stdin.nextLine(); } for(int j = 0; j < substrings.length; j++) { int count = 0; String pattern = "\\w+" + substrings[j] + "\\w+"; for(int i = 0; i < lines.length; i++) { String line = lines[i]; Pattern p = Pattern.compile(pattern); Matcher m = p.matcher(line); while(m.find()) { m.group(); count++; } } System.out.println(count); } 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 |
'use strict'; const processData = input => { let inputLines = input.split('\n'); let linesLength = parseInt(inputLines[0]); let substrings = inputLines.slice(linesLength + 2); for(let j = 0; j < substrings.length; j++) { let count = 0; let pattern = "\\w+" + substrings[j] + "\\w+"; for(let i = 1; i <= linesLength; i++) { let line = inputLines[i]; let match = line.match(new RegExp(pattern, "g")); count += match ? match.length : 0; } console.log(count); } }; 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 7 8 9 10 11 12 13 14 15 16 17 18 19 |
import scala.io.Source object FindSubstring extends App { val inputLines = Source.stdin.getLines().toList val linesLength = inputLines(0).toInt val lines = inputLines.slice(1, linesLength + 1) val substrings = inputLines.slice(linesLength + 2, inputLines.length) val counts = substrings.map(findSubstring(lines, _)) println(counts.mkString("\n")) def findSubstring(lines: List[String], substring: String): Int = { lines.map(line => { val pattern = "\\w+" + substring + "\\w+" val matches = pattern.r.findAllMatchIn(line) matches.length }).sum } } |
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
lines_count = gets.chomp.to_i words = [] lines_count.times do line = gets.chomp w = line.split w.each { |a| words << a} end pattern_count = gets.chomp.to_i pattern_count.times do input = gets.chomp pattern = "[a-z_]+#{input}[a-z_]+" result = 0 words.each do |word| if word =~ /\w+#{input}\w+/ result += 1 end end puts result end |