2017-02-02 3 views
3

私は数字があります。例えば、です。私はこのようなものを使用して5つの整数で、この数を分割したい:n桁の整数をappで割り算する関数。同じサイズ

foo <- function(x, n) rep(x/n, n) 
foo(10, 5) 
[1] 2 2 2 2 2 

xnのmutlipleなくなるまで、この作品:

この場合
foo(10, 3) 
[1] 3.333333 3.333333 3.333333 

私のような出力が好きwoud。

[1] 3 4 3 # the order doesn't matter. 

各整数の差は最小でなければなりません。したがって、この結果は、許可されていません。

[1] 2 5 3 

は、これまでのところ私は、これは常に正しいかどうかを確認します。この機能を使用しますが、いないよ:

foo <- function(x, n){ 
    res <- rep(x/n, n) 
    res <- floor(res) # rounding 
    Diff <- x-sum(res) # Difference of the sum to the input 
    gr <- sample(1:n, Diff) # select by chance as many values as `Diff` is 
    res[gr] <- res[gr]+1 # plus one 
    res 
    } 

答えて

1

あなたの機能が動作するはずですが、すべての異なる答えを与えます時間。また、ユークリッド部門を使って、floorDiffというmimcikを試してみてください。 Rで私が興味深い質問だと思ったので、簡単な解決策は

foo <- function(x,n) 
{ 
    res=numeric(n) 
    a=x%/%n # the quotient 
    b=x%%n # the remainder 
    res[1:n]=a # fill with the quotient 
    if(b>0){ 
    for(i in 1:b) 
     res[n-i+1]=res[n-i+1]+1 # add as many time a one in a cell as needed by the remainder 
    } 
    return(res) 
} 
+0

おかげで、ユークリッド除算が良い点である 'if'条件 –

+0

を追加しました。ありがとう。私は意図的に "by-cance-approach"を選択しました。 – Jimbou

1

この可能性があり%/%との商と%% との残りを取得します。私は残りの部分があなたが持っている(商+1)の数を示していることを理解しました。 >あなたが必要なので(7 )×2とのx(2 + 1)

7分の19 -

7分の17 = 2 + /7:たとえば、 = 2 + /7 - >あなたが必要とするので(7 )×2、よりエレガントな解決策を導くのx(2 + 1)

foo <- function(x,n){ 
    a = x%/%n # the quotient 
    b = x%%n # the remainder 
    return(c(rep(a,n-b),rep(a+1,b))) 
} 
1

この動作するはずです:それは良い点ですchinsoon12 @

foo <- function(x, n) rep(x%/%n, n) + sample(c(rep(1, x %% n), rep(0, n - x %% n)), n) 

foo(10, 5) 
[#1] 2 2 2 2 2 
foo(10, 3) 
#[1] 3 3 4 
関連する問題