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

1
2
3
4
5
['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

1
2
3
def find_missing_letter(arr)
#your code here
end

Sample Testing

1
2
3
4
5
6
7
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

1
2
3
function findMissingLetter(array){
return ' ';
}

Sample Testing

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

Thinking

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

Hint & Reference

Solution

Ruby

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
# 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

1
2
3
4
5
6
7
8
9
// 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);
}
}
}