Black and White Ball mantra
There is no end to learning, innovation, and transcendence.
Introduction
This is my question in the beauty of programming. I feel that I have my own ideas and I have not carefully read the solution in the book.
Question
Ideas
I once saw that this problem was solved by recursive functions. Of course, I would not write code using recursive methods. I like non-recursive methods, and I love stacks, instead of recursion, it shows my capabilities. Later I found many overlapping sub-problems. Isn't this a typical DP? OMG ..... Dp [I] [j] stores the probability that the number of black balls is j and the number of white balls is (I + 1-j.
Lab
The black ball is 10, the white ball is 10, and the probability is 1.
If both the black and white balls are 100, the probability is 1.
Code
Test. cpp
// problem is the black-white ball#include
using namespace std;// solution to the questiondouble white_black_ball( int w,int b );// get two black possibledouble Same_Black(int w,int b);// get two white possibledouble Same_White(int w,int b);// get two different ball possibledouble Different_ball(int w,int b);// main functionint main(){cout<
= 2 )dp[i][j] += double(Same_White(now_w,now_b) * ( dp[i-1][now_b+1])) ;if( now_b >= 2 )dp[i][j] += double(Same_Black(now_w,now_b) * (dp[i-1][now_b-1]));if( now_w >= 1 && now_b >= 1 )dp[i][j] += double(Different_ball(now_w,now_b) * (dp[i-1][now_b-1]));}for(int i = 0;i
= 2)return double (b*(b-1)) / double((w+b)*(w+b-1));else return 0;}// get two white possibledouble Same_White(int w,int b){if( w < 0 || b < 0 )return -1 ;if(w >= 2)return double ( w * (w-1) ) / double ( (w+b) * (w+b-1) );else return 0;}// get two different balldouble Different_ball(int w,int b){if( w < 0 || b < 0 )return -1 ;if( w>0 && b>0 )return 2.0 * double ( b * w )/ double( (w+b) * (b+w-1) );else return 0;}