-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathGet_the_Middle_Character.R
56 lines (42 loc) · 1.1 KB
/
Get_the_Middle_Character.R
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
# You are going to be given a word. Your job is to return the middle character
# of the word. If the word's length is odd, return the middle character. If the
# word's length is even, return the middle 2 characters.
#
# Examples:
# getMiddle("test") should return "es"
#
# getMiddle("testing") should return "t"
#
# getMiddle("middle") should return "dd"
#
# getMiddle("A") should return "A"
# Solution: ----
# Sol 01
get_middle <- function(s){
n <- c((nchar(s) + 1) %/% 2, nchar(s) %/% 2 + 1)
substr(s, n[1], n[2])
}
# Sol 02
get_middle <- function(s){
if (nchar(s) == 1) {
return(s)
} else {
cmpl <- nchar(s)
if (cmpl %% 2 == 0) {
n <- c(cmpl / 2, cmpl / 2 + 1)
} else {
n <- c(cmpl / 2+1, cmpl / 2+1)
}
saida <- substr(s, n[1], n[2])
return(saida)
}
}
# Sample Tests: ----
library(testthat)
test_that("Sample Tests", {
expect_equal(get_middle("test"),"es")
expect_equal(get_middle("testing"),"t")
expect_equal(get_middle("middle"), "dd")
expect_equal(get_middle("A"), "A")
expect_equal(get_middle("of"), "of")
})