Problem Statement
A description of the problem can be found on Hackerrank.
Solution
Sort the array descending. Take N
from the input.
For each element e
substract N - e
. That means that there is only N - e
combinations to choose these two cards. After substraction decrement N
and select the next element. All card combinations are multiplication of all N - e
substractions. If at least N - e
is lower than 0
the result is automatically 0
. Don’t forget modulo 1 000 000 007
.
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 PickingCards { public static void main(String[] args) { Scanner stdin = new Scanner(System.in); int tests = stdin.nextInt(); for(int i = 0; i < tests; i++) { int length = stdin.nextInt(); long[] arr = new long[length]; for(int j = 0; j < arr.length; j++) { arr[j] = stdin.nextLong(); } Arrays.sort(arr); long result = 1; for (int j = arr.length - 1; j >= 0; j--) { long diff = length - arr[j]; if (diff < 0) diff = 0; result *= diff; result %= 1000000007; length -= 1; } System.out.println(result); } 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 27 |
'use strict'; const processData = input => { let lines = input.split("\n"); let tests = parseInt(lines[0]); let index = 1; for (let i = 0; i < tests; i++) { let length = parseInt(lines[index++]); let arr = lines[index++].split(" ").map(i => parseInt(i)).sort((a, b) => a - b); let result = 1; for (let j = arr.length - 1; j >= 0; j--) { let diff = length - arr[j]; if (diff < 0) diff = 0; result *= diff; result %= 1000000007; length -= 1; } console.log(result); } }; process.stdin.resume(); process.stdin.setEncoding("ascii"); var _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 19 20 21 22 23 24 25 |
import scala.io.Source object PickingCards extends App { val lines = Source.stdin.getLines() val cards = lines.drop(1).filter(_.contains(" ")) cards.foreach(line => { println(pickingCombinations(line)) }) def pickingCombinations(s: String): Long = { val arr = s.split(" ").map(_.toLong).sorted val arrLength = arr.length picks(arr, arrLength, 1) } def picks(list: Array[Long], l: Int, combinations: Long): Long = { if(l == 0) { return combinations } val diff = l - list(l - 1) val normalizedDiff = if (diff > 0) diff else 0 val newCombinations = (combinations * normalizedDiff) % 1000000007 picks(list, l - 1, newCombinations) } } |
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
test_cases = gets.chomp.to_i test_cases.times do array_length = gets.chomp.to_i array = gets.chomp.split.map { |e| e.to_i } array.sort! { |i,j| j <=> i } result = 1 array.each do |element| diff = array_length - element diff = 0 if diff < 0 result *= diff result %= 1000000007 array_length -= 1 end puts result end |