Problem Statement
A description of the problem can be found on Hackerrank.
Solution
Count of all routes as multiplication of routes between towns.
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 |
import java.util.Scanner; public class ConnectingTowns { public static void main(String[] args) { Scanner stdin = new Scanner(System.in); int cases = stdin.nextInt(); for(int i = 0; i < cases; i++) { int l = stdin.nextInt(); int routes = 1; for(int j = 0; j < l - 1; j++) { routes *= stdin.nextInt(); routes %= 1234567; } System.out.println(routes); } 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 |
function processData(input) { var lines = input.split('\n'); var n = parseInt(lines[0]); var index = 2; for(var i = 0; i < n; i++) { var arr = lines[index].split(" ").map(i => parseInt(i)); var routes = 1; for(var j = 0; j < arr.length; j++) { routes *= arr[j]; routes %= 1234567; } console.log(routes); index += 2; } } 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 |
import scala.io.Source object ConnectingTowns extends App { val lines = Source.stdin.getLines().drop(1) val routesArray = lines.toList.filter(_.contains(" ")) val routes = routesArray.map(_.split(" ").map(_.toLong).foldLeft(1L)(_ * _ % 1234567)) println(routes.mkString("\n")) } |
Ruby
1 2 3 4 5 6 7 8 9 10 11 |
cases = gets.chomp.to_i cases.times do result = 1 towns = gets.chomp.to_i routes = gets.chomp.split.map { |e| e.to_i } for i in 0..towns - 2 do result *= routes[i] result %= 1234567 end puts result end |