Don't say so much, just coding...
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:
permutations('a'); # ['a']
permutations('ab'); # ['ab', 'ba']
permutations('aabb'); # ['aabb', 'abab', 'abba', 'baab', 'baba', 'bbaa']
The order of the permutations doesn't matter.
def permutations(string)
#your code here
end
#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'])
function permutations(string) {
//your code here
}
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());
});
});
想法(1): 字組的所有排列組合,發現 ruby 連這種東西都有,寫起來就是簡潔又快速,真的方便 ·__·
圖片來源:Unsplash XPS
# Solution 1
def permutations(string)
string.chars.permutation.map(&:join).uniq
end
// 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;
}
}