Hackerrank – Problem Statement
A description of the problem can be found on Hackerrank.
Solution
(((sweets % prisoners) + startId) % prisoners) - 1
Modulo finds the id of prisoner who gets the last poisoned candy after all circles distribution. Since the starting id S
is not from first prisoner we make an offset. Do modulo again because there are cases when sum of last prisoner and the offset is greater then count of all prisoners.
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 27 |
import java.util.*; public class SaveThePrisoner { public static void main(String[] args) { Scanner stdin = new Scanner(System.in); int tests = Integer.parseInt(stdin.nextLine()); for(int i = 0; i < tests; i++) { System.out.println(savedPrisoner(stdin.nextLine())); } stdin.close(); } private static long savedPrisoner(String line) { String[] numbers = line.split(" "); long prisoners = Long.valueOf(numbers[0]); long sweets = Long.valueOf(numbers[1]); long startId = Long.valueOf(numbers[2]); long saved = (((sweets % prisoners) + startId) % prisoners) - 1; if (saved == 0) { return prisoners; } else { return saved; } } } |
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 |
'use strict'; const processData = input => { const lines = input.split('\n'); for(let i = 1; i < lines.length; i++) { console.log(savedPrisoner(lines[i])); } }; const savedPrisoner = (line) => { const numbers = line.split(" ").map(i => parseInt(i)); const prisoners = numbers[0]; const sweets = numbers[1]; const startId = numbers[2]; const saved = (((sweets % prisoners) + startId) % prisoners) - 1; if (saved == 0) { return prisoners; } else { return saved; } }; 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 14 15 16 17 |
object SaveThePrisoner extends App { val lines = Source.stdin.getLines().toList val statements = lines.tail val savedPrisoners = statements.map(savedPrisoner) println(savedPrisoners.mkString("\n")) def savedPrisoner(line: String): Long = { val numbers = line.split(" ").map(_.toLong) val prisoners = numbers(0) val sweets = numbers(1) val startId = numbers(2) val saved = (((sweets % prisoners) + startId) % prisoners) - 1 if (saved == 0) prisoners else saved } } |
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
def saved_prisoner(line) numbers = line.split(" ").map {|i| i.to_i} prisoners = numbers[0] sweets = numbers[1] startId = numbers[2] saved = (((sweets % prisoners) + startId) % prisoners) - 1; return prisoners if (saved == 0) saved end n = gets.to_i n.times do puts saved_prisoner(gets) end |