這次改刷 Codewars LV6 題目
可以發現從 LV7 到 LV6 的難度是明顯提升
( 也是有較簡單的題目在LV6 )
不像前面 LV8 是帶你認識 Ruby 內建方法
LV7 題目則是方法的應用
到 LV6 之後,更多的考驗是思考邏輯
切入點不同時,解題方法也會不同
題目1:
#Find the missing letter
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'
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
題目2:
There is a queue for the self-checkout tills at the supermarket. Your task is write a function to calculate the total time required for all the customers to check out!
input
customers: an array of positive integers representing the queue. Each integer represents a customer, and its value is the amount of time they require to check out.
n: a positive integer, the number of checkout tills.
output
The function should return an integer, the total time required.
Important
Please look at the examples and clarifications below, to ensure you understand the task correctly :)
Examples
queue_time([5,3,4], 1)
# should return 12
# because when n=1, the total time is just the sum of the times
queue_time([10,2,3,3], 2)
# should return 10
# because here n=2 and the 2nd, 3rd, and 4th people in the
# queue finish before the 1st person has finished.
queue_time([2,3,10], 2)
# should return 12
def queue_time(customers, n)
#your code here
end
Test.describe("Basic tests") do
Test.assert_equals(queue_time([], 1), 0, "wrong answer for case with an empty queue")
Test.assert_equals(queue_time([5], 1), 5, "wrong answer for a single person in the queue")
Test.assert_equals(queue_time([2], 5), 2, "wrong answer for a single person in the queue")
Test.assert_equals(queue_time([1,2,3,4,5], 1), 15, "wrong answer for a single till")
Test.assert_equals(queue_time([1,2,3,4,5], 100), 5, "wrong answer for a case with a large number of tills")
Test.assert_equals(queue_time([2,2,3,3,4,4], 2), 9, "wrong answer for a case with two tills")
end
答案:
# 題目1
def find_missing_letter(arr)
([*arr.min..arr.max] - arr).join
end
# 題目2
def queue_time(customers, n)
tills = [0] * n
while customers.length > 0
min_index = tills.index(tills.min)
tills[min_index] += customers.shift
end
tills.max
end
本文同步發布於 小菜的 Blog https://riverye.com/