betazold
Vi Veri Veniversum Vivus Vici
We can to implement this in Javasсript like:



  1. function printTree(t, index, r, delim) {
  2. var out = [],
  3. prefix, res;
  4. r = r || '';
  5. delim = delim || ' ';
  6. index = index || 0;
  7. if (index < t.length) {
  8. t = t.map(function(el) {
  9. return el instanceof Array ? el : [el];
  10. });
  11. prefix = r ? r + delim : '';
  12. for (var i = 0; i < t[index].length; i++) {
  13. if (t[index][i] instanceof Array) {
  14. res = printTree(t[index][i], 0, r, delim);
  15. } else {
  16. res = [prefix + t[index][i]];
  17. }
  18. for (var j = 0; j < res.length; j++) {
  19. out = out.concat(printTree(t, index + 1, res[j], delim));
  20. }
  21. }
  22. } else {
  23. return [r];
  24. }
  25. return out;
  26. }
  27. var tests = [
  28. [1, 2, 3],
  29. [1, [2, 3]],
  30. [
  31. [1, 2], 3
  32. ],
  33. [
  34. [1, 2],
  35. [3, 4]
  36. ],
  37. [
  38. [1, 2],
  39. [3, [4, 5], 6]
  40. ],
  41. [1, [2, [3, [4, 5]]]],
  42. [
  43. [1, 2],
  44. [
  45. [3, [4, 5, 6]], 7
  46. ]
  47. ],
  48. [
  49. [1, 2],
  50. [
  51. [3, [4, 5, 6]], 7
  52. ], 8
  53. ],
  54. [
  55. 1,
  56. [
  57. 2,
  58. [
  59. 3,
  60. [
  61. 4,
  62. [5, 6]
  63. ],
  64. 7
  65. ],
  66. 8
  67. ],
  68. 9
  69. ],
  70. [
  71. 1,
  72. [
  73. 2,
  74. [
  75. 3,
  76. [
  77. [
  78. 4,
  79. [5, 6]
  80. ]
  81. ],
  82. 7
  83. ],
  84. 8
  85. ],
  86. 9
  87. ]
  88. ];
  89. for (var i = 0; i < tests.length; i++) {
  90. print(printTree(tests[i]).join('\n'));
  91. print('\n')
  92. }




As you can see, on each iteration we "increment" accumulator with string, and returns whole string when recursion is over.







You can check it in action at: ideone.com/tP5KTC

@темы: JavaScript, algorithms, permutations