iT邦幫忙

第 12 屆 iT 邦幫忙鐵人賽

DAY 3
1
自我挑戰組

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

見習村03 - Highest Scoring Word

03 - Highest Scoring Word

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

Instruction

Given a string of words, you need to find the highest scoring word.

Each letter of a word scores points according to its position in the alphabet: a = 1, b = 2, c = 3 etc.

You need to return the highest scoring word as a string.

If two words score the same, return the word that appears earliest in the original string.

All letters will be lowercase and all inputs will be valid.

Ruby

Init

  def high(x)
    # Code here
  end

Sample Testing

  describe "Basic Tests" do
    it "should pass basic tests" do
      Test.assert_equals(high('man i need a taxi up to ubud'), 'taxi')
      Test.assert_equals(high('what time are we climbing up the volcano'), 'volcano')
      Test.assert_equals(high('take me to semynak'), 'semynak')
      Test.assert_equals(high('aaa b'), 'aaa')
    end
  end

Javascript

Init

  function high(x){
    // Code here
  }

Sample Testing

  Test.describe("Example tests",_=>{
  Test.assertEquals(high('man i need a taxi up to ubud'), 'taxi');
  Test.assertEquals(high('what time are we climbing up the volcano'), 'volcano'); 
  Test.assertEquals(high('take me to semynak'), 'semynak');  
  });

Thinking

想法(1): 輸入的英文句子,可以先將每個字切開分群
想法(2): 再將每個群計算 ord 然後計算該群單詞 ord 總和

https://ithelp.ithome.com.tw/upload/images/20200918/2012082665vk5r7ygL.jpg
圖片來源:Unsplash Matt Ragland

Hint & Reference

Solution

Ruby

  # Solution 1
  def high(x)
    x.split.max_by{ |x| x.chars.map{ |c| c.ord - 96}.sum }
  end

Javascript

  // Solution 1
  function high(x){
    let max = x.split(' ').map( 
      (s) => [...s].reduce(
        (sum, s) => sum + s.charCodeAt() - 96, 0
      )
    )
    
    return x.split(' ')[max.indexOf(Math.max(...max))];
  }

上一篇
見習村02 - Unique In Order
下一篇
見習村04 - Bit Counting
系列文
見習村-30 Day CodeWars Challenge30

尚未有邦友留言

立即登入留言