Popis problému
Celý popis zadania sa nacháza – Hackerrank.
Riešenie
Vytvoril som premennú height
a inicializoval hodnotu na 1
.
Pre každé zadané číslo: ak je párne, vynásob height
dvomi; ak je nepárne, tak pripočítaj 1
ku height
.
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.Scanner; public class UtopianTree { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int testCases = scanner.nextInt(); for (int i = 0; i < testCases; i++) { int cycles = scanner.nextInt(); System.out.println(utopianTree(cycles)); } scanner.close(); } private static int utopianTree(int cycles) { int height = 1; for (int i = 0; i < cycles; i++) { if(i % 2 == 0) { height *= 2; } else { height += 1; } } return height; } } |
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 |
function processData(input) { var numbers = input.split("\n").map(function(i) {return parseInt(i); }); var index = 0; var tests = numbers[index++]; for(var i = 0; i < tests; i++) { var cycles = numbers[index++]; console.log(tree(0, cycles, 1)); } } function tree(actual, cycles, height) { if(actual == cycles) { return height } if(actual % 2 == 0) return tree(actual + 1, cycles, height * 2) return tree(actual + 1, cycles, height + 1) } process.stdin.resume(); process.stdin.setEncoding("ascii"); _input = ""; process.stdin.on("data", function (input) { _input += input; }); process.stdin.on("end", function () { processData(_input); }); |
Scala
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
import scala.io.Source object UtopianTree extends App { val nums = Source.stdin.getLines().toList.tail.map(_.toInt) nums.foreach(i => println(tree(0, i, 1))) def tree(actualCycle: Int, cycles: Int, height: Int): Int = { if(actualCycle == cycles) { return height } if(actualCycle % 2 == 0) tree(actualCycle + 1, cycles, height * 2) else tree(actualCycle + 1, cycles, height + 1) } } |
Ruby
1 2 3 4 5 6 7 8 9 10 11 |
def tree(actualCycle, cycles, height) return height if(actualCycle == cycles) return tree(actualCycle + 1, cycles, height * 2) if(actualCycle % 2 == 0) tree(actualCycle + 1, cycles, height + 1) end tests = gets.to_i tests.times do cycles = gets.to_i puts tree(0, cycles, 1) end |