-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathanagrams.js
More file actions
33 lines (29 loc) · 852 Bytes
/
anagrams.js
File metadata and controls
33 lines (29 loc) · 852 Bytes
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
/**
* Given a single input string, write a function that outputs an array of
strings with every possible combination of letters.
* At first, don't worry about repeated (duplicate) strings.
* What time complexity is your solution?
* Extra credit: De-duplicate your return array without using uniq().
* example usage:
* var anagrams = allAnagrams('abc');
* console.log(anagrams); // [ 'abc', 'acb', 'bac', 'bca', 'cab', 'cba' ]
*/
function swap (arr, a, b) {
var temp = arr[a];
arr[a] = arr[b];
arr[b] = temp;
return arr;
}
function allAnagrams (str) {
var result = new Array();
str=str.split("");
for (var i = 0; i < str.length; i++) {
for (var j = 0; j < str.length; j++) {
var element = swap(str, i, j).join("");
if(!result.includes(element)){
result.push(element)
}
}
}
return result;
}