iT邦幫忙

第 12 屆 iThome 鐵人賽

DAY 14
1

14 - Simple Pig Latin

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

Instruction

Move the first letter of each word to the end of it, then add "ay" to the end of the word. Leave punctuation marks untouched.

Examples

  pig_it('Pig latin is cool') # igPay atinlay siay oolcay
  pig_it('Hello world !')     # elloHay orldway !

Ruby

Init

  def pig_it text
    # ...
  end

Sample Testing

  Test.assert_equals(pig_it('Pig latin is cool'),'igPay atinlay siay oolcay')
  Test.assert_equals(pig_it('This is my string'),'hisTay siay ymay tringsay');

Javascript

Init

  function pigIt(str){
    //Code here
  }

Sample Testing

  Test.assertEquals(pigIt('Pig latin is cool'),'igPay atinlay siay oolcay')
  Test.assertEquals(pigIt('This is my string'),'hisTay siay ymay tringsay')

Thinking

想法(1): 第一個想法就是 regex 直接切兩群,然後把第一群接到第二群後面再加上 ay 的字
想法(2): 不過畢竟 regex 如果像我ㄧ樣爛,就想說可以繞開看看,把第一個字組在 slice 掉第一個字後,然後再加上 ay 也是可以(傳入值有可能有驚嘆號!問號?

https://ithelp.ithome.com.tw/upload/images/20200929/201208261punaj8vOx.jpg
圖片來源:Unsplash Glenn Carstens-Peters

Hint & Reference

Solution

Ruby

  # Solution 1
  def pig_it text
    text.gsub(/(\w)(\w+)*/, '\2\1ay')
  end

Javascript

  // Solution 1
  function pigIt(str){
    let Array = [];
    let split = str.split(' ');
    for (i = 0; i < split.length; i++) {
      if (split[i] != '?' && split[i] != '!') {
        Array.push(split[i].slice(1) + split[i].charAt(0) + 'ay');
      } else {
        Array.push(split[i]);
      }
    }
    return Array.join(' ');
  }

上一篇
見習村13 - int32 to IPv4
下一篇
見習村15 - Directions Reduction
系列文
見習村-30 Day CodeWars Challenge30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言