Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- function comb(string $input): array
- {
- $pad = [
- 2 => ['a', 'b', 'c'],
- 3 => ['d', 'e', 'f'],
- 4 => ['g', 'h', 'i'],
- 5 => ['j', 'k', 'l'],
- 6 => ['m', 'n', 'o'],
- 7 => ['p', 'q', 'r', 's'],
- 8 => ['t', 'u', 'v'],
- 9 => ['w', 'x', 'y', 'z'],
- 0 => [' '],
- 1 => ['']
- ];
- $numbers = [];
- $arr = array_map('intval', str_split(intval($input)));
- for ($i = 0; $i < count($arr); $i++) {
- $numbers [] = $pad[$arr[$i]];
- }
- return $numbers;
- }
- function combinations($numbers, $i = 0) : array
- {
- // termination condition
- if (!isset($numbers[$i])) {
- return [];
- }
- // if we reached the last element of the array -> start next array
- if ($i == count($numbers) - 1) {
- return $numbers[$i];
- }
- // recursive call to get combinations from subsequent arrays
- $tmp = combinations($numbers, $i + 1);
- $result = [];
- // concat each array from tmp with each element from $numbers[$i]
- foreach ($numbers[$i] as $v) {
- foreach ($tmp as $t) {
- $result[] = is_array($t) ? array_merge([$v], $t) : [$v, $t];
- }
- }
- return $result;
- }
- function printResults(array $combinations)
- {
- foreach ($combinations as $combination) {
- printf(implode('', $combination) . "\n");
- }
- }
- $numbers = comb('12345');
- printResults(combinations($numbers));
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement