Advertisement
Guest User

Untitled

a guest
Sep 19th, 2017
67
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.39 KB | None | 0 0
  1. <?php
  2.  
  3. function comb(string $input): array
  4. {
  5. $pad = [
  6. 2 => ['a', 'b', 'c'],
  7. 3 => ['d', 'e', 'f'],
  8. 4 => ['g', 'h', 'i'],
  9. 5 => ['j', 'k', 'l'],
  10. 6 => ['m', 'n', 'o'],
  11. 7 => ['p', 'q', 'r', 's'],
  12. 8 => ['t', 'u', 'v'],
  13. 9 => ['w', 'x', 'y', 'z'],
  14. 0 => [' '],
  15. 1 => ['']
  16.  
  17. ];
  18.  
  19. $numbers = [];
  20. $arr = array_map('intval', str_split(intval($input)));
  21.  
  22. for ($i = 0; $i < count($arr); $i++) {
  23.  
  24. $numbers [] = $pad[$arr[$i]];
  25. }
  26.  
  27. return $numbers;
  28. }
  29.  
  30. function combinations($numbers, $i = 0) : array
  31. {
  32. // termination condition
  33. if (!isset($numbers[$i])) {
  34. return [];
  35. }
  36.  
  37. // if we reached the last element of the array -> start next array
  38. if ($i == count($numbers) - 1) {
  39. return $numbers[$i];
  40. }
  41.  
  42. // recursive call to get combinations from subsequent arrays
  43. $tmp = combinations($numbers, $i + 1);
  44.  
  45. $result = [];
  46.  
  47. // concat each array from tmp with each element from $numbers[$i]
  48. foreach ($numbers[$i] as $v) {
  49. foreach ($tmp as $t) {
  50. $result[] = is_array($t) ? array_merge([$v], $t) : [$v, $t];
  51. }
  52. }
  53.  
  54. return $result;
  55. }
  56.  
  57.  
  58. function printResults(array $combinations)
  59. {
  60. foreach ($combinations as $combination) {
  61. printf(implode('', $combination) . "\n");
  62. }
  63. }
  64.  
  65. $numbers = comb('12345');
  66.  
  67. printResults(combinations($numbers));
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement