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) end
Sample Testing 1 2 3 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 ) { }
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 連這種東西都有,寫起來就是簡潔又快速,真的方便 ·__·
圖片來源:Unsplash XPS
Hint & Reference
Solution Ruby 1 2 3 4 def permutations (string) string.chars.permutation.map(&:join ).uniqend
Javascript 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 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; } }