Расчет 4 или n Сумма в R - PullRequest
1 голос
/ 14 июня 2019

Я пытаюсь практиковать проблемы LeetCode для интервью Data Scientist в R, и один из вопросов, с которыми я столкнулся, это foursum . Чтобы решить эту проблему, я пытаюсь сгенерировать все четыре различных комбинации и вычислить сумму с помощью функции apply. Есть ли лучший способ оптимизировать его в R без использования combn?

GetFourSumCombinations <- function(TestVector,Target){
  CombinationPairs = combn(TestVector, 4)  ## Get all the combinations
  SumOfAllCombinations = apply(CombinationPairs, 2, sum)
  TargetElements = which(SumOfAllCombinations == Target)
  return(CombinationPairs[,TargetElements])
}
## OutPut:
TestVector = c(1, 0, -1, 0, -2, 2), Target = 0
GetFourSumCombinations(TestVector,0)
     [,1] [,2] [,3]
[1,]    1    1    0
[2,]    0   -1    0
[3,]   -1   -2   -2
[4,]    0    2    2

Ответы [ 2 ]

3 голосов
/ 14 июня 2019

Вот немного более короткая версия

GetFourSumCombinations <- function(TestVector,Target){
   vals <- combn(TestVector, 4)
   vals[, colSums(vals) == Target]
}

GetFourSumCombinations(TestVector, Target)

#     [,1] [,2] [,3]
#[1,]    1    1    0
#[2,]    0   -1    0
#[3,]   -1   -2   -2
#[4,]    0    2    2

data

TestVector <- c(1, 0, -1, 0, -2, 2)
Target = 0
2 голосов
/ 14 июня 2019

Запустите combn, преобразуйте это в data.frame и затем Filter из желаемых столбцов.Он состоит из одной строки и не имеет подписки.

target4 <- function(x, target = 0) {
  Filter(function(x) sum(x) == target, as.data.frame(combn(x, 4)))
}

TestVector <- c(1, 0, -1, 0, -2, 2)
target4(TestVector)

, что дает:

  V1 V9 V14
1  1  1   0
2  0 -1   0
3 -1 -2  -2
4  0  2   2

2) Дольше, но не использует combn.

target4a <- function(x, target = 0) {
  g <- do.call("expand.grid", rep(list(seq_along(x)), 4))
  ok <- apply(g, 1, function(x) all(diff(x) > 0))
  g2 <- apply(g[ok, ], 1, function(ix) x[ix])
  g2[, colSums(g2) == target]
}

target4a(TestVector)

3) или, возможно, разбить (2) на пользовательские комбинации и (1).

combn4 <- function(x) {
  g <- do.call("expand.grid", rep(list(seq_along(x)), 4))
  ok <- apply(g, 1, function(x) all(diff(x) > 0))
  apply(g[ok, ], 1, function(ix) x[ix])
}

target4b <- function(x, target = 0) {
  Filter(function(x) sum(x) == target, as.data.frame(combn4(x)))
}

target4b(TestVector)
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...