Hackerrank – Problem Statement
Solution
k
problems, or less if chapter ends. Start counting chapter problems from 1
. Check if page contains problem with same number.
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 19 20 21 22 23 24 25 26 |
import java.util.*; public class LisasWorkbook { public static void main(String[] args) { Scanner stdin = new Scanner(System.in); int n = stdin.nextInt(); int k = stdin.nextInt(); int page = 1; int specialProblems = 0; for(int i = 0; i < n; i++) { int problemsPerChapter = stdin.nextInt(); for(int p = 1; p <= problemsPerChapter; p++) { if(p == page) { specialProblems++; } if((p != problemsPerChapter) && (p % k == 0)) { page++; } } page++; } System.out.println(specialProblems); 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 27 28 29 30 31 |
'use strict'; const processData = input => { const lines = input.split('\n'); const arr = lines[0].split(/\s+/).map(i => parseInt(i)); const n = arr[0]; const k = arr[1]; const problemsPerChapter = lines[1].split(/\s+/).map(i => parseInt(i)); let specialProblems = 0; let page = 1; for(let i = 0; i < n; i++) { const problems = problemsPerChapter[i]; for(let p = 1; p <= problems; p++) { if(p === page) { specialProblems++; } if(p !== problems && p % k === 0) { page++; } } page++; } console.log(specialProblems); }; 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 20 |
import scala.io.Source object LisasWorkbook extends App { val lines = Source.stdin.getLines().toList val line1 = lines.head val line2 = lines.tail.head val arr = line1.split(" ").map(_.toInt) val chapters = arr(0) val problemsPerPage = arr(1) val chapterProblems = line2.split(" ").map(_.toInt) val pages = chapterProblems.flatMap(problems => (1 to problems).grouped(problemsPerPage).map(_.toList)).toList val specialProblems = (1 to pages.length).count(pageNum => isPageWithSpecialProblem(pages(pageNum - 1), pageNum)) println(specialProblems) def isPageWithSpecialProblem(page: List[Int], pageNum: Int): Boolean = { page.contains(pageNum) } } |
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
(n, k) = gets.split.map {|i| i.to_i} problems_per_chapter = gets.split.map {|i| i.to_i} page = 1 special_problems = 0 n.times do |i| problems = problems_per_chapter[i] for p in 1..problems special_problems += 1 if p == page page += 1 if p != problems && p % k == 0 end page += 1 end puts special_problems |