Popis problému
Celý popis zadania sa nacháza – Hackerrank.
Riešenie
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 36 37 38 39 40 41 |
import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Scanner; public class BuildingList { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int testCases = Integer.parseInt(scanner.next()); for (int i = 0; i < testCases; i++) { int length = Integer.parseInt(scanner.next()); String input = scanner.next(); List<String> result = new ArrayList<String>(); combine(result, input, 0, ""); Collections.sort(result); for (String s : result) { System.out.println(s); } } scanner.close(); } private static void combine(List<String> result, String input, int start, String actual) { for (int i = start; i < input.length(); i++) { String out = actual; actual += input.charAt(i); result.add(actual); if(i < input.length()) { combine(result, input, i + 1, out); } } } } |
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 31 32 |
'use strict'; var combine = (result, input, start, actual) => { for(let i = start; i < input.length; i++) { let out = actual; actual += input.charAt(i); result.push(actual); if(i < input.length) { combine(result, input, i + 1, out); } } }; const processData = input => { let lines = input.split('\n'); let index = 1; for(let i = 0; i < parseInt(lines[0]); i++) { let length = parseInt(lines[index++]); let input = lines[index++]; let result = []; combine(result, input, 0, ''); result.sort((a, b) => a.localeCompare(b)); console.log(result.join('\n')); } }; process.stdin.resume(); process.stdin.setEncoding("ascii"); var _input = ""; process.stdin.on("data", input => _input += input); process.stdin.on("end", () => processData(_input)); |
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
def combine(result, input, start, actual) for i in start...input.length do out = actual actual += input[i] result << actual if i < input.length combine(result, input, i + 1, out); end end end test_cases = gets.chomp.to_i test_cases.times do length = gets.strip.chomp.to_i input = gets.strip.chomp.to_s result = [] combine(result, input, 0, '') result.sort! {|a, b| a <=> b} puts result.join("\n") end |