设计一个函数来输出尽可能少的赢家

Designing a function to output the smallest plurality winner possible

我正在尝试设计一个 function/formula 给定两个整数变量,例如代表 5 和 100。第一个数字可以代表调查中的 5 种冰淇淋口味,然后100 被抽样的人数被问到他们最喜欢的冰淇淋。

我想设计一个 function/formula,它将产生数字组合,其中 5 种冰淇淋口味中的 1 种可以以最小的复数获胜(因此,我猜在大多数情况下,以 1 获胜),并根据调查中冰淇淋口味的数量尽可能少。

所以有 5 种冰淇淋口味和 100 位受访者,我希望 R 生成一个矢量(顺序并不重要):

[1] 21 20 20 20 19

因为在 100 名受访者和 5 种口味中,21 是大多数冰淇淋口味获胜者可能的最小数字。作为一项功能,它需要处理选择数量与受访者数量不一致的情况。

期望输出

combinations_function <- function(x, y) {
  ?????
}

combinations_function(5, 100)
[1] 21 20 20 20 19

combinations_function(5, 38)
[1] 9 8 7 7 7

combinations_function(7, 48)
[1] 8 7 7 7 7 6 6

我想我明白了:

smallest_margin <- function(choices, respondents)
{
    values = rep(respondents %/% choices, choices)
    remainder = respondents %% choices
    while(remainder != 0)
    {
      values[which.min(values)] <- values[which.min(values)] + 1
      remainder = remainder - 1
    }
    if(length(which(values == max(values))) > 1)
      values[which(values == max(values))[1:2]] <- 
      values[which(values == max(values))[1:2]] + c(-1, 1)
    return(sort(values))
}

smallest_margin(5, 100)
# [1] 19 20 20 20 21
smallest_margin(1, 100)
# [1] 100
smallest_margin(5, 99)
# [1] 19 19 20 20 21
smallest_margin(12, 758)
# [1] 63 63 63 63 63 63 63 63 63 63 63 65

这是一个 code-golfian 方法

f <- function(x,y) 
  rep(y%/%x, x) + ifelse(rep(y%%x>0, x), 
                         c(1^(1:(y%%x)), 0*((y%%x+1):x)), 0) + c((-1)^(0:1), 0*(3:x))

例子

f(5, 100)
# [1] 21 19 20 20 20
f(5, 38)
# [1] 9 7 8 7 7
f(5, 48)
# [1] 11  9 10  9  9
f(7, 48)
# [1] 8 6 7 7 7 7 6