Hackerrank – Problem Statement
A description of the problem can be found on Hackerrank.
Solution
I calculated time in the cycle when counter value is 1
:
last_time_next_cycle = actual_cycle_time + 2 * (last_time_actual_cycle - last_time_previous_cycle).
The difference in seconds between cycle 0 and cycle 1 is 3
, which is always like that.
For a given time I calculate its cycle end time. I calculate a difference between given time and calculated cycle end time. Do +1
. It is the counter result value.
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 |
import java.util.*; public class StrangeCounter { public static void main(String[] args) { Scanner stdin = new Scanner(System.in); long t = stdin.nextLong(); long cycleEndTime = cycleEnd(t, 0, 3); long timeDiff = cycleEndTime - t; long finalValue = timeDiff + 1; System.out.println(finalValue); stdin.close(); } private static long cycleEnd(long time, long start, long step) { if(start > time) { return start; } return cycleEnd(time, start + step, step * 2); } } |
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 t = parseInt(input); const cycleEndTime = cycleEnd(t, 0, 3); const timeDiff = cycleEndTime - t; const finalValue = timeDiff + 1; console.log(finalValue); }; const cycleEnd = (time, start, step) => { if(start > time) { return start; } return cycleEnd(time, start + step, step * 2); }; 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 18 |
object StrangeCounter extends App { val sc = new java.util.Scanner (System.in) val t = sc.nextLong() val cycle = Math.sqrt((t.toDouble / 3).ceil).ceil.toLong val cycleEndTime = cycleEnd(t, 0, 3) val timeDiff = cycleEndTime - t val finalValue = timeDiff + 1 println(finalValue) def cycleEnd(time: Long, start: Long, step: Long): Long = { if(start > time) { return start } cycleEnd(time, start + step, step * 2) } } |
Ruby
1 2 3 4 5 6 7 8 9 10 |
def cycle_end(time, start, step) return start if(start > time) cycle_end(time, start + step, step * 2) end t = gets.to_i cycle_end_time = cycle_end(t, 0, 3) time_diff = cycle_end_time - t final_value = time_diff + 1 puts final_value |