Hackerrank – Problem Statement
A description of the problem can be found on Hackerrank.
Solution
The length of a given word repeated could be too much to be able to calculate the result before the time limit. We need to simplify our solution.
We have a given string – s
. Count only "a"
characters in the given string – c
Get the length of the result string (given on second line) – n
Find how many times is s
in first n
characters. – t = n / length(s)
There is a rest of the characters in n
-charactede string – rest = n - t * length(s)
Find how many "a"
s are in the rest of the string – r
.
The result is total number of "a"
s:
c * t + r
I created solution in:
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.*; public class RepeatedString { public static void main(String[] args) { Scanner stdin = new Scanner(System.in); String s = stdin.nextLine(); long n = Long.parseLong(stdin.nextLine()); long as = s.chars().filter(c -> c == 'a').count(); long times = n / s.length(); long rest = n % s.length(); long totalAs = times * as + s.substring(0, (int) rest).chars().filter(c -> c == 'a').count(); System.out.println(totalAs); 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 |
'use strict'; const processData = input => { const lines = input.split('\n'); const s = lines[0]; const n = parseInt(lines[1]); const as = s.split("").filter(c => c === "a").length; const times = parseInt(n / s.length); const rest = n % s.length; const totalAs = times * as + s.slice(0, rest).split("").filter(c => c === "a").length; console.log(totalAs); }; process.stdin.resume(); process.stdin.setEncoding("ascii"); let _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 |
import scala.io.Source object RepeatedString extends App { val lines = Source.stdin.getLines().toList val string = lines.head val letters = lines(1).toLong val as = string.count(_ == 'a') val times = letters / string.length val rest = letters % string.length val totalAs = times * as + string.substring(0, rest.toInt).count(_ == 'a') println(totalAs) } |
Ruby
1 2 3 4 5 6 7 8 9 |
s = gets.strip n = gets.strip.to_i as = s.count("a") times = n / s.size rest = n % s.size totalAs = times * as + s.slice(0, rest).count("a") puts totalAs |