Beautiful black and white ball in the programming of interview questions

Source: Internet
Author: User

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;}
     
    
   


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.