Problem Statement
A description of the problem can be found on Hackerrank.
Solution
Make a height
and initialize its value as 1
. For each input number: if it is even double the height
if it odd add 1
to height
.
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 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 |