iT邦幫忙

第 12 屆 iThome 鐵人賽

DAY 20
1
自我挑戰組

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

見習村20 - Scramblies

20 - Scramblies

Don't say so much, just coding...

Instruction

Complete the function scramble(str1, str2) that returns true if a portion of str1 characters can be rearranged to match str2, otherwise returns false.

Notes:

  • Only lower case letters will be used (a-z). No punctuation or digits will be included.
  • Performance needs to be considered
  Input strings s1 and s2 are null terminated.

Examples

  scramble('rkqodlw', 'world') ==> True
  scramble('cedewaraaossoqqyt', 'codewars') ==> True
  scramble('katas', 'steak') ==> False

Ruby

Init

  def scramble(s1,s2)
    #your code here
  end

Sample Testing

  Test.assert_equals(scramble('rkqodlw','world'),true)
  Test.assert_equals(scramble('cedewaraaossoqqyt','codewars'),true)
  Test.assert_equals(scramble('katas','steak'),false)
  Test.assert_equals(scramble('scriptjava','javascript'),true)
  Test.assert_equals(scramble('scriptingjava','javascript'),true)

Javascript

Init

  function scramble(str1, str2) {
   //code me
  }

Sample Testing

  describe('Example Tests', function(){
    Test.assertEquals(scramble('rkqodlw','world'),true);
    Test.assertEquals(scramble('cedewaraaossoqqyt','codewars'),true);
    Test.assertEquals(scramble('katas','steak'),false);
    Test.assertEquals(scramble('scriptjava','javascript'),true);
    Test.assertEquals(scramble('scriptingjava','javascript'),true);
    Test.assertEquals(scramble('scriptsjava','javascripts'),true);
    Test.assertEquals(scramble('jscripts','javascript'),false);
    Test.assertEquals(scramble('aabbcamaomsccdd','commas'),true);
  });

Thinking

想法(1): 後者的值,跟前者比較時,要所有的字都有在前者且數量也要ㄧ樣
想法(2): 將後者的值透過 uniq 後,跑迴圈來比較 count 有無 小於等於 前者

https://ithelp.ithome.com.tw/upload/images/20201005/20120826IN9SHwnVlw.jpg
圖片來源:Unsplash Buse Doga Ay

Hint & Reference

Solution

Ruby

  # Solution 1
  def scramble(s1,s2)
    s3 = s1.split("")
    s2.split("").each do |x|
      s3.each_with_index{ |y,i| (s3.delete_at i ; break) if y == x }
    end
    s1.length - s2.length == s3.join.length ? true : false
  end
  
  # Solution 2
  def scramble(s1,s2)
    s2.chars.uniq.all?{ |x| s2.count(x) <= s1.count(x) }
  end

Javascript

  // Solution 1
  function scramble(str1, str2) {
    return [...str2].every(val => str2.split(val).length <= str1.split(val).length);
  }

上一篇
見習村19 - RGB To Hex Conversion
下一篇
見習村21 - Snail
系列文
見習村-30 Day CodeWars Challenge30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言