iT邦幫忙

第 12 屆 iThome 鐵人賽

DAY 22
1
自我挑戰組

見習村-30 Day CodeWars Challenge系列 第 22

見習村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:

  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

  def permutations(string)
    #your code here
  end

Sample Testing

  #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

  function permutations(string) {
    //your code here
  }

Sample Testing

  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

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

Javascript

  // 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;
    }
  }

上一篇
見習村21 - Snail
下一篇
見習村23 - Number of Proper Fractions with Denominator d
系列文
見習村-30 Day CodeWars Challenge30

尚未有邦友留言

立即登入留言