你必須很努力

連續刷題看 7 分鐘能刷幾題 Codewars

2019/09/18
字數統計: 439閱讀時間: 2 min

連刷 9 天後,目前對 Codewars LV7 題目能比較快解出題目
試著挑戰在短時間內 (5 分鐘左右)
看能刷幾題,同時講解如何刷題


題目(Two to One)

1
Take 2 strings s1 and s2 including only letters from ato z. Return a new sorted string, the longest possible, containing distinct letters, each taken only once - coming from s1 or s2.

1
2
3
4
5
6
7
8
9
10
11
def longest(a1, a2)
# your code
end

Test.describe("longest") do
Test.it("Basic tests") do
Test.assert_equals(longest("aretheyhere", "yestheyarehere"), "aehrsty")
Test.assert_equals(longest("loopingisfunbutdangerous", "lessdangerousthancoding"), "abcdefghilnoprstu")
Test.assert_equals(longest("inmanylanguages", "theresapairoffunctions"), "acefghilmnoprstuy")
end
end

題目(Ones and Zeros)

1
2
Given an array of ones and zeroes, convert the equivalent binary value to an integer.
Eg: [0, 0, 0, 1] is treated as 0001 which is the binary representation of 1.

1
2
3
4
5
6
7
8
9
10
def binary_array_to_number(arr)
# your code here
end

Test.describe("Example tests") do
Test.assert_equals(binary_array_to_number([0,0,0,1]), 1)
Test.assert_equals(binary_array_to_number([0,0,1,0]), 2)
Test.assert_equals(binary_array_to_number([1,1,1,1]), 15)
Test.assert_equals(binary_array_to_number([0,1,1,0]), 6)
end

題目(Square Every Digit)

1
2
3
Welcome. In this kata, you are asked to square every digit of a number.
For example, if we run 9119 through the function, 811181 will come out, because 92 is 81 and 12 is 1.
Note: The function accepts an integer and returns an integer

1
2
3
4
5
6
7
8
9
def square_digits num
# code goes here
end

Test.assert_equals(square_digits(3212), 9414)
Test.assert_equals(square_digits(2112), 4114)
Test.assert_equals(square_digits(1111), 1111)
Test.assert_equals(square_digits(1234321), 14916941)
Test.assert_equals(square_digits(0), 0)

題目(Odd or Even?)

1
2
3
Given an array of numbers (a list in groovy), determine whether the sum of all of the numbers is odd or even.
Give your answer in string format as 'odd' or 'even'.
If the input array is empty consider it as: [0] (array with a zero).

1
2
3
4
5
6
7
8
9
10
11
def odd_or_even(array)
#your code here
end

describe "Basic tests" do
Test.assert_equals(odd_or_even([0]), "even")
Test.assert_equals(odd_or_even([1]), "odd")
Test.assert_equals(odd_or_even([]), "even")
Test.assert_equals(odd_or_even([-1023, 1, -2]), "even")
Test.assert_equals(odd_or_even([-1023, -1, 3]), "odd")
end


影片解題:


答案:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# Two to One
def longest(a1, a2)
(a1.chars + a2.chars).sort.uniq.join
end


# Ones and Zeros
def binary_array_to_number(arr)
arr.join.to_i(2)
end


# Square Every Digit
def square_digits num
num.to_s.chars.map{ |x| x.to_i.pow(2) }.join.to_i
end


# Odd or Even?
def odd_or_even(array)
return "odd" if array.sum.odd?
"even"
end

本文同步發布於 小菜的 Blog https://riverye.com/

原文連結:https://riverye.com/2019/09/18/連續刷題看-7-分鐘能刷幾題-Codewars/

發表日期:2019-09-18

更新日期:2022-12-21

CATALOG