1
一個矩陣一定條件給定尺寸和M
N
的矩陣, 我們要填充的整數值在每一行中(> = 0) 使得其總計爲一定值。灌裝中的R
注意的M
和N
尺寸是預先計算使用 某些式,以便它是保證匹配 給出的期望的條件的填充(即sum_val
下文)。
這兩個例子
#sum_val <-2
#m<-6
#n<-3
# the value of "sum_val" may vary
# and 'm' 'n' also change depends on it
# First are initialized using 0
#mat <- matrix(0,nrow=m,ncol=n);
# Below results are hand coded:
[,1] [,2] [,3]
[1,] 1 1 0 # Sum of each rows here is equal to 'sum_val = 2'
[2,] 1 0 1
[3,] 0 1 1
[4,] 2 0 0
[5,] 0 2 0
[6,] 0 0 2
又如:
> sum_val<-2;
#m<-15
#n<-5
#mat <- matrix(0,nrow=m,ncol=n);
# Below results are hand coded:
[,1] [,2] [,3] [,4] [,5]
[1,] 1 1 0 0 0 # rows also sums up to 2
[2,] 1 0 1 0 0
[3,] 1 0 0 1 0
[4,] 1 0 0 0 1
[5,] 0 1 0 0 1
[6,] 0 0 1 0 1
[7,] 0 0 0 1 1
[8,] 0 1 0 1 0
[9,] 0 1 1 0 0
[10,] 0 0 1 1 0
[11,] 2 0 0 0 0
[12,] 0 2 0 0 0
[13,] 0 0 2 0 0
[14,] 0 0 0 2 0
[15,] 0 0 0 0 2
我卡具有以下循環:
> for (ri in 1:m) {
+ for (ci in 1:n) {
+
+
+ # Not sure how to proceed from here
+ if(ci==2) {
+ mat[ri,ci] <- 1;
+ }
+ }
+ }
什麼是解決這個問題的最好方法?