We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
Great solution! To understand why these formulas work, I think it is easiest to solve the problem graphically. Draw a line from (0, c) to (c, 0). This is your boundary of x + y <= c. Now, on top of this you are going to draw various rectangles to represent the two uniform variables [0, a], [0, b] along each axis. Take the first case of a > c and b > c. Here you have a rectangle ab with a triangle in the lower left corner from (0, c) to (c, 0). You only want this triangle in the lower left corner since these are your allowed values of x + y <= c. The area of this triangle = 1/2 * base * height = 0.5 * c^2. The area of the rectangle is ab. The odds of landing in the "allowed" triangle are therefore 0.5 * c^2 / ab. You need to rationalize this so that the numerator and denominator are integers, so c^2 / 2ab. This gives the first case "if a >= c and b >= c" in the logic above. The rest are similar, draw pictures to find the "allowed" region within the square.
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Random number generator
You are viewing a single comment's thread. Return to all comments →
Great solution! To understand why these formulas work, I think it is easiest to solve the problem graphically. Draw a line from (0, c) to (c, 0). This is your boundary of x + y <= c. Now, on top of this you are going to draw various rectangles to represent the two uniform variables [0, a], [0, b] along each axis. Take the first case of a > c and b > c. Here you have a rectangle ab with a triangle in the lower left corner from (0, c) to (c, 0). You only want this triangle in the lower left corner since these are your allowed values of x + y <= c. The area of this triangle = 1/2 * base * height = 0.5 * c^2. The area of the rectangle is ab. The odds of landing in the "allowed" triangle are therefore 0.5 * c^2 / ab. You need to rationalize this so that the numerator and denominator are integers, so c^2 / 2ab. This gives the first case "if a >= c and b >= c" in the logic above. The rest are similar, draw pictures to find the "allowed" region within the square.