【算法】給定能隨機生成整數1到5的函數,寫出能隨機生成整數1到7的函數

聽說還是什麼牛逼公司的面試題

A<-sample(1:5,7,replace = TRUE)
B<-sum(A) %/% 7+1


#使用R語言編寫,循環比較費時
c<- 0
for (i in 1:10000){
a<- sample(1:5,7,replace=T)

#b<-a[1]+a[2]+a[3]+a[4]+a[5]+a[6]+a[7]
b<-sum(a)
c[i]<- b%%7+1
i<- i+1
}
table(c)
#向量法,比較省時間
n<-10000000 #一千萬還是比較快能算出來的
j<-0
a<- sample(1:5,n,replace=T)
b<- sample(1:5,n,replace=T)
c<- sample(1:5,n,replace=T)
d<- sample(1:5,n,replace=T)
e<- sample(1:5,n,replace=T)
f<- sample(1:5,n,replace=T)
g<- sample(1:5,n,replace=T)

h<-a+b+c+d+e+f+g
j<-h%%7+1
table(j)

就醬

本人覺得這種方法還能用於遊戲物品的掉落

n<-10000000 #一千萬還是比較快能算出來的
j<-0
a<- sample(1:5,n,replace=T)
b<- sample(1:5,n,replace=T)
c<- sample(1:5,n,replace=T)
d<- sample(1:5,n,replace=T)
e<- sample(1:5,n,replace=T)

h<-a+b+c+d+e
table(h)
prop.table(table(h))*100
> prop.table(table(h))*100
h
       5        6        7        8        9       10       11 
 0.03180  0.15856  0.47532  1.11812  2.23843  3.86980  5.91648 
      12       13       14       15       16       17       18 
 8.15523 10.25177 11.66650 12.19767 11.68735 10.25112  8.15653 
      19       20       21       22       23       24       25 
 5.92546  3.86763  2.24009  1.11897  0.47912  0.16183  0.03222 
這裏,我們可以設置當h爲哪一個值域區間的時候掉落什麼物品,當然這裏的1:5這些數字是可以變更的,也不用非得都是一樣的。這裏僅僅提供一個想法,以供相關人員參考。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章