2017年6月26日月曜日

大学入試問題をモンテカルロで解く

情報処理の課題として、「大学入試問題をモンテカルロで解く」というのは面白いかと思い、こちらの問題について作成。しかし、これなら素直に数え上げた方が遥かに速い(汗)。


int a,b,c;
float n1=0;
float n2=0;
void setup(){
  size(1000,20);
}
void draw(){
   a=int(random(1,7));
   b=int(random(1,7));
   c=int(random(1,7));
   
   if(log(a+b)/log(0.25)>log(c)/log(0.5)) n1+=1;
   if((pow(2,a)+pow(2,b)+pow(2,c))%3==0) n2+=1;
   background(255);
   fill(0);
   text(str(frameCount),width*0.1,height/2);
   text(str(n1/frameCount),width*0.5,height/2);
   text(str(n2/frameCount),width*0.8,height/2);
}

数えた。コンピュータ便利。
int a, b, c;
float n1=0;
float n2=0;
float n=0;
size(1000, 20);
for (a=1; a<7; a+=1) {
  for (b=1; b<7; b+=1) {
    for (c=1; c<7; c+=1) {
      if (log(a+b)/log(0.25)>log(c)/log(0.5)) n1+=1;
      if ((pow(2, a)+pow(2, b)+pow(2, c))%3==0) n2+=1;
      n+=1;
    }
  }
}
background(255);
fill(0);
text(str(n), width*0.1, height/2);
text(str(n1/n), width*0.5, height/2);
text(str(n2/n), width*0.8, height/2);