一個序列(例如 c(1,2,3,4))幾乎是遞增的,當我們可以從序列中洗掉一個元素并得到一個嚴格遞增的序列(即 a0 < a1 < ... < an)時。我試圖找到一種方法來檢查一個序列是否幾乎在增加。如果是,我想回傳 TRUE;如果不是我想輸出 FALSE。我已經做到了這一點:
solution <- function(sequence) {
sequence1 <- unlist(sequence)
if (length(sequence1) == 1) {
next
}
count <- 0
for (i in (length(sequence1) - 1)) {
if (sequence1[i 1] > sequence1[i]) {
next
} else if (((sequence1[i 2] > sequence1[i]) & count == 0) & i !=
length(sequence1)-1) {
sequence1 <- sequence1[- (i 1)]
count <- count 1
} else if ((sequence1[i 1] > sequence1[i - 1]) & count == 0 & i != 1) {
sequence1 <- sequence1[-i]
count <- count 1
} else {
return(FALSE)
}
}
return(TRUE)
}
我使用了 unlist() 因為 codesignal 出于某種原因不接受您在函式中參考函式引數。這適用于某些序列:solution(c(4,1,5)) 正確回傳 TRUE。它對其他人不起作用:solution(c(1, 1, 1, 2, 3)) 錯誤地回傳 TRUE。solution(c(2,1,2,1)) 正確回傳 FALSE,但 solution(c(1,2,1,2)) 錯誤回傳 TRUE。我已經失去了對正在發生的事情的控制。我想知道是否有人可以發現任何東西?
澄清:我的代碼的基本思想是遍歷序列并為每個元素檢查其右鄰居是否是更大的數字。如果不是,那么我們有兩個選擇:擺脫 i 或擺脫 i 1,所以我依次檢查它們。由于我們只能進行一項更改,因此我添加了如果 count 為 1,則我們跳過完成的條件。另外,如果索引為 1 則無法檢查 i-1,如果索引為長度(序列)-1 則無法檢查 i 2,因此我添加了這些條件以確保如果合適,我的代碼會跳到另一個選項。
uj5u.com熱心網友回復:
這是一個適合我的解決方案。這個想法是diff(x)每一步向下都有負面因素x。例如,min(diff(x))為正,如果x為嚴格遞增。如果diff(x)[i] <= 0僅針對一個索引i,我們必須檢查洗掉x[i]或洗掉是否x[i 1]會使序列嚴格增加。以下函式通過了我嘗試的所有測驗:
check_almost <- function(x) {
if (length(x) < 2) {
return(TRUE)
}
d <- diff(x)
i <- which(d <= 0)
if (length(i) == 0) {
return(TRUE) # strictly increasing
} else if (length(i) > 1) {
return(FALSE)
}
return(i == 1 || # we can remove x[1]
i == length(d) || # we can remove x[length(x)]
d[i-1] d[i] > 0 || # we can remove x[i]
d[i] d[i 1] > 0) # we can remove x[i 1]
}
uj5u.com熱心網友回復:
這是一個帶有diff和的函式rle。
solution <- function(x) {
d <- c(TRUE, diff(x))
if(length(which(d <= 0)) > 2L) return(FALSE)
y <- x[-which.min(d > 0)]
all(rle(y)$lengths == 1L)
}
x0 <- 1:4
x1 <- c(4,1,5)
x2 <- c(1, 1, 1, 2, 3)
x3 <- c(2,1,2,1)
x4 <- c(1,2,1,2)
x_list <- mget(ls(pattern = "^x"))
sapply(x_list, solution)
#> x0 x1 x2 x3 x4
#> TRUE TRUE FALSE FALSE FALSE
由reprex 包于 2022-03-21 創建(v2.0.1)
uj5u.com熱心網友回復:
你讓這種方式變得比它需要的更難。你可以這樣做:
check_almost <- function(vec) sum(!(vec[-1] > head(cummax(vec), -1))) < 2
并在一些例子上進行測驗:
almost1 <- c(1, 2, 3, 2, 5)
almost2 <- c(1, 2, 3, 2, 5)
not_almost1 <- c(1, 0, 2, 0, 5)
not_almost2 <- c(1, 2, 1, 0, 4)
check_almost(almost1)
#> [1] TRUE
check_almost(almost2)
#> [1] TRUE
check_almost(not_almost1)
#> [1] FALSE
check_almost(not_almost2)
#> [1] FALSE
并以 Rui 為例:
x0 <- 1:4
x1 <- c(4,1,5)
x2 <- c(1, 1, 1, 2, 3)
x3 <- c(2,1,2,1)
x4 <- c(1,2,1,2)
x_list <- mget(ls(pattern = "^x"))
sapply(x_list, check_almost)
#> x0 x1 x2 x3 x4
#> TRUE TRUE FALSE FALSE FALSE
在 jochen 的例子中:
check_almost(c(4, 3, 2, 1))
#> [1] FALSE
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/447090.html
下一篇:for回圈未在零引數上執行
