开心消消乐 - 基于R
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了开心消消乐 - 基于R相关的知识,希望对你有一定的参考价值。
1 #let‘s begin, generate a sample with 5 kinds of animals 2 begin=sample(1:5,100,replace = TRUE) 3 4 #generate n random numbers come from 5 categories 5 r=function(n){ 6 r=sample(1:5,n,replace = TRUE) 7 } 8 9 #define play styles 10 play.row=function(data){ 11 #count how many times been eliminated 12 count.row=0 13 for (i in 1:nrow(data)){ 14 for (j in 1:(ncol(data)-2)){ 15 while (data[i,j]==data[i,j+1] & data[i,j+1]==data[i,j+2]) { 16 count.row=count.row+1 17 if (j==1) { 18 data[i,1:(j+2)]=c(r(3)) 19 } 20 else if (j>1) { 21 data[i,1:(j+2)]=c(r(3),data[i,1:(j-1)]) 22 } 23 } 24 } 25 } 26 return (list(data,count.row)) 27 } 28 29 play.col=function(data){ 30 #count how many times been eliminated 31 count.col=0 32 for (j in 1:ncol(data)){ 33 for (i in 1:(nrow(data)-2)){ 34 while (data[i,j]==data[i+1,j] & data[i+1,j]==data[i+2,j]){ 35 count.col=count.col+1 36 if (i==1){ 37 data[1:(i+2),j]=c(r(3)) 38 } 39 else if (i>1){ 40 data[1:(i+2),j]=c(r(3),data[1:(i-1),j]) 41 } 42 } 43 } 44 } 45 return (list(data,count.col)) 46 } 47 48 #make a move 49 move=function(data,i,j,k){ 50 if( (i <=nrow(data)) & 51 (j <=ncol(data)) ){ 52 if (k=="row"){ 53 tmp=data[i,j] 54 data[i,j]=data[i,j+1] 55 data[i,j+1]=tmp 56 } 57 else if (k=="col"){ 58 tmp=data[i,j] 59 data[i,j]=data[i+1,j] 60 data[i+1,j]=tmp 61 } 62 else print("Error in move!") 63 64 } 65 if ((i >nrow(data)) | 66 (j >ncol(data)) ){ 67 print ("Out of Bound Error !") 68 } 69 return(data) 70 } 71 72 #choose the best move 73 best.move=function(data){ 74 choice=matrix(nrow=nrow(data)-1,ncol=ncol(data)-1) 75 for (i in 1:(nrow(data)-1)){ 76 for (j in 1:(ncol(data)-1)){ 77 for (k in c("row","col")) { 78 choice[i,j]=as.numeric(play.col(move(data,i,j,k))[2])+as.numeric(play.row(move(data,i,j,k))[2]) 79 } 80 } 81 } 82 print(choice) 83 } 84 85 86 #start to play 87 origin=matrix(ncol=10,nrow=10,data=begin) 88 #eliminate with original style 89 clean=data.frame(play.col(data.frame(play.row(origin)[1]))[1]) 90 #try to make a best move 91 best.move(clean) 92 #in this case, we can find the best move is row=4 and col=5. but it depends on the random numbers when eliminating them. 93 #so we can take this as a reference. 94 new=move(clean,4,5,"row") 95 #eliminate numbers again... 96 new.origin=data.frame(play.col(data.frame(play.row(new)[1]))[1]) 97 #and then play again... 98 99 #BTW, if there is no way to eliminate any numbers in making one step, just reorder the matrix.. 100 if ((play.col(new.origin)[2]==0) & 101 (play.row(new.origin)[2]==0)) { 102 tmp=c() 103 for (p in (1:nrow(new.origin))){ 104 for (q in (1:ncol(new.origin))){ 105 tmp=c(tmp,new.origin[p,q]) 106 } 107 } 108 reorder.origin=matrix(ncol=10,nrow=10,data=tmp) 109 } 110 111 #afterall, it can not be stopped..
消消乐基本版...欢迎拍砖
以上是关于开心消消乐 - 基于R的主要内容,如果未能解决你的问题,请参考以下文章