[我正在尝试设计一个函数/公式,在其中给您两个整数变量,分别代表5和100。第一个数字可以代表调查中的5种冰淇淋口味,而100代表人数被抽样询问他们最喜欢的冰淇淋。
我想设计一个函数/公式,该函数/公式将产生这样的数字组合,其中5种冰淇淋口味中的1个可以赢得最小的复数(因此,我猜大多数情况下,可以赢得1个),并且数字最小可能基于调查中冰淇淋口味的数量。
因此,如果有5种冰淇淋口味和100名受访者,我希望R产生一个(顺序不是很重要的向量):
[1] 21 20 20 20 19
因为22种冰淇淋是大多数冰淇淋风味获奖者中100名受访者和5种口味中可能的最小数字。作为一项功能,当选择的数量与被调查者的数目也不能很好地划分时,就需要处理。
所需的输出
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
这里是代码高尔夫方法
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