見習村22 - Permutations

22 - Permutations

Don’t say so much, just coding…

Instruction

In this kata you have to create all permutations of an input string and remove duplicates, if present. This means, you have to shuffle all letters from the input in all possible orders.

Examples:

1
2
3
permutations('a'); # ['a']
permutations('ab'); # ['ab', 'ba']
permutations('aabb'); # ['aabb', 'abab', 'abba', 'baab', 'baba', 'bbaa']

The order of the permutations doesn’t matter.

Ruby

Init

1
2
3
def permutations(string)
#your code here
end

Sample Testing

1
2
3
#Test.assert_equals(permutations('a').sort, ['a']);
Test.assert_equals(permutations('ab').sort, ['ab', 'ba'])
Test.assert_equals(permutations('aabb').sort, ['aabb', 'abab', 'abba', 'baab', 'baba', 'bbaa'])

Javascript

Init

1
2
3
function permutations(string) {
//your code here
}

Sample Testing

1
2
3
4
5
6
7
describe('permutations', function() {
it('examples from description', function() {
Test.assertSimilar(permutations('a'), ['a']);
Test.assertSimilar(permutations('ab').sort(), ['ab', 'ba'].sort());
Test.assertSimilar(permutations('aabb').sort(), ['aabb', 'abab', 'abba', 'baab', 'baba', 'bbaa'].sort());
});
});

Thinking

想法(1): 字組的所有排列組合,發現 ruby 連這種東西都有,寫起來就是簡潔又快速,真的方便 ·__·

https://ithelp.ithome.com.tw/upload/images/20201007/20120826ivLm6ehvW5.jpg
圖片來源:Unsplash XPS

Hint & Reference

Solution

Ruby

1
2
3
4
# Solution 1
def permutations(string)
string.chars.permutation.map(&:join).uniq
end

Javascript

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// Solution 1
function permutations(string) {
if (string.length <= 1)
return [string];

var result = [];
for(var i = 0; i < string.length; i++){
result = result.concat(permutations(string.substring(0, i) + string.substring(i + 1)).map(function(e) {
return string[i] + e;
}).filter(function(e) {
return result.indexOf(e) === -1;
}));
}
return result;
}
}