Don't say so much, just coding...
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!
def find_missing_letter(arr)
#your code here
end
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
function findMissingLetter(array){
return ' ';
}
describe("KataTests", function(){
it("exampleTests", function(){
Test.assertEquals(findMissingLetter(['a','b','c','d','f']), 'e');
Test.assertEquals(findMissingLetter(['O','Q','R','S']), 'P');
});
});
想法(1): 後面的英文字要是前一個英文字的下一個,不是的話,則回傳下一個英文字
想法(2): 可以用 ord
來完成,但其實有更快的方法,值得好好想一下...
# 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
// 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);
}
}
}