forked from aishraj/JavaScript-Interview-Questions
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path008.js
More file actions
95 lines (83 loc) · 1.56 KB
/
008.js
File metadata and controls
95 lines (83 loc) · 1.56 KB
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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
/*
* <!--
* This program is distributed under
* the terms of the MIT license.
* Please see the LICENSE file for details.
* -->
*/
/*
* Implement a routine that prints all possible combinations of a string,
* starting from 1 character length to the length of the string.
*/
/*____________________________________________________________________________*/
/**
* @function {public static} combine
*
* Prints all possible combinations of a given `String`.
*
* @param {String} str - the `String` to combine.
*/
function combine(str) {
var length = str.length;
var input = str.split('');
var output = [];
doCombine(input, output, length, 0, 0);
}
/**
* @function {public static} doCombine
*
* Recursively combines the given input.
*
* @param {Array} input - the input `String`
* @param {Array} output - the output buffer.
* @param {Integer} length - the length of the `String`.
* @param {Integer} level - recursion depth
* @param {Integer} start - starting index
*/
function doCombine(input, output, length, level, start) {
var i = 0;
for (var i = start; i < length; i++) {
output.push(input[i]);
console.log(output.join(''));
if (i < length - 1) {
doCombine(input, output, length, level+1, i+1);
}
output.length = output.length - 1;
}
}
/*____________________________________________________________________________*/
combine('SF_CA');
/*
Output: ($ /usr/bin/node 008.js)
S
SF
SF_
SF_C
SF_CA
SF_A
SFC
SFCA
SFA
S_
S_C
S_CA
S_A
SC
SCA
SA
F
F_
F_C
F_CA
F_A
FC
FCA
FA
_
_C
_CA
_A
C
CA
A
*/