iT邦幫忙

第 12 屆 iT 邦幫忙鐵人賽

DAY 28
1
自我挑戰組

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

見習村28 - Find the missing letter

28 - Find the missing letter

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

Instruction

Write a method that takes an array of consecutive (increasing) letters as input and that returns the missing letter in the array.

You will always get an valid array. And it will be always exactly one letter be missing. The length of the array will always be at least 2.
The array will always contain letters in only one case.

Example:

['a','b','c','d','f'] -> 'e' ['O','Q','R','S'] -> 'P'

["a","b","c","d","f"] -> "e"
["O","Q","R","S"] -> "P"
(Use the English alphabet with 26 letters!)

Have fun coding it and please don't forget to vote and rank this kata! :-)

I have also created other katas. Take a look if you enjoyed this kata!

Ruby

Init

  def find_missing_letter(arr)
    #your code here
  end

Sample Testing

 Test.describe("Basic tests") do
    Test.assert_equals(find_missing_letter(["a","b","c","d","f"]), "e")
    Test.assert_equals(find_missing_letter(["O","Q","R","S"]), "P")
    Test.assert_equals(find_missing_letter(["b","d"]), "c")
    Test.assert_equals(find_missing_letter(["a","b","d"]), "c")
    Test.assert_equals(find_missing_letter(["b","d","e"]), "c")
  end

Javascript

Init

  function findMissingLetter(array){
    return ' ';
  }

Sample Testing

  describe("KataTests", function(){
    it("exampleTests", function(){
      Test.assertEquals(findMissingLetter(['a','b','c','d','f']), 'e');
      Test.assertEquals(findMissingLetter(['O','Q','R','S']), 'P');
    });
  });

Thinking

想法(1): 後面的英文字要是前一個英文字的下一個,不是的話,則回傳下一個英文字
想法(2): 可以用 ord 來完成,但其實有更快的方法,值得好好想一下...

https://ithelp.ithome.com.tw/upload/images/20201013/20120826HwX3ZSzM9n.jpg
圖片來源:Unsplash Emile Perron

Hint & Reference

Solution

Ruby

  # Solution 1
  def find_missing_letter(arr)
    (arr.length - 1).times{ |num| return (arr[num].ord + 1).chr if arr[num].ord + 1 != arr[num + 1].ord }
    return nil
  end
  
  # Solution 2
  def find_missing_letter(arr)
    arr[0...-1].each_with_index{ |num, index| return num.next if num.next != arr[index + 1] }
    return nil
  end
  
  # Solution 3
  def find_missing_letter(arr)
    ((arr.first..arr.last).to_a - arr).first
  end

Javascript

  // Solution 1
  function findMissingLetter(array) {
    var string = array.join('');
    for(var i = 0; i < string.length; i++) {
      if(string.charCodeAt(i + 1) - string.charCodeAt(i) != 1){
        return String.fromCharCode(string.charCodeAt(i) + 1);
      }
    }
  }

上一篇
見習村27 - First non-repeating character
下一篇
見習村29 - Sum of Intervals
系列文
見習村-30 Day CodeWars Challenge30

尚未有邦友留言

立即登入留言