r - 设计一个函数来输出最小的多个获胜者

标签 r algorithm combinations combinatorics

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

我想设计一个函数/公式,它会产生数字的组合,其中 5 种冰淇淋口味中的 1 种可以以最小的复数获胜(所以,我猜在大多数情况下,是 1),并且有可能基于的最小数字关于调查中冰淇淋口味的数量。

因此,对于 5 种冰淇淋口味和 100 名受访者,我希望 R 生成一个向量(顺序并不重要):

[1] 21 20 20 20 19

因为 21 是 100 名受访者和 5 种口味中大多数冰淇淋口味获胜者可能的最小数字。 As a function it would need to deal with when numbers of choices don't neatly divide with the numeber of respondants as well.

所需输出
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

关于r - 设计一个函数来输出最小的多个获胜者,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59778361/

相关文章:

r - 在 tabItems Shiny 仪表板之间切换

r - 在一行中将多个对象从字符串转换为数字?

使用sparklyr滚动处理大数据

algorithm - 当给定节点的二叉树时,如何编写返回节点链表的递归函数?

java - 获取字符串或组合的所有可能排列,包括 Java 中的重复字符

r - 在 R 中使用 dplyr 选择不以字符串开头的列

c++ - 2 名知道最大步数的玩家团队

iterator - 从 Julia 中的向量生成所有无序对

python - python 中的重复组合,顺序很重要

algorithm - 如何计算期望值