zoukankan      html  css  js  c++  java
  • 0478. Generate Random Point in a Circle (M)

    Generate Random Point in a Circle (M)

    题目

    Given the radius and x-y positions of the center of a circle, write a function randPoint which generates a uniform random point in the circle.

    Note:

    1. input and output values are in floating-point.
    2. radius and x-y position of the center of the circle is passed into the class constructor.
    3. a point on the circumference of the circle is considered to be in the circle.
    4. randPoint returns a size 2 array containing x-position and y-position of the random point, in that order.

    Example 1:

    Input: 
    ["Solution","randPoint","randPoint","randPoint"]
    [[1,0,0],[],[],[]]
    Output: [null,[-0.72939,-0.65505],[-0.78502,-0.28626],[-0.83119,-0.19803]]
    

    Example 2:

    Input: 
    ["Solution","randPoint","randPoint","randPoint"]
    [[10,5,-7.5],[],[],[]]
    Output: [null,[11.52438,-8.33273],[2.46992,-16.21705],[11.13430,-12.42337]]
    

    Explanation of Input Syntax:

    The input is two lists: the subroutines called and their arguments. Solution's constructor has three arguments, the radius, x-position of the center, and y-position of the center of the circle. randPoint has no arguments. Arguments are always wrapped with a list, even if there aren't any.


    题意

    在圆内随机生成一个点。

    思路

    极坐标容易处理:生成一个随机的角度rad,一个随机的长度len,len在0-radius之间,那么得到的随机点就是(len*cos(rad) + x, len*sin(rad) + y)。问题在于如果len直接由radius乘一个0-1的随机数random生成,最后得到的结果并不是对于面积等概率的。举个例子,如果要在半径为R的圆中取一点,使该点正好在半径为R/2的同心圆中,概率为1/4而不是1/2。因此应当先对random去平方根,再与半径相乘来得到len值。


    代码实现

    Java

    class Solution {
        private double r, x, y;
        private Random random;
    
        public Solution(double radius, double x_center, double y_center) {
            r = radius;
            x = x_center;
            y = y_center;
            random = new Random();
        }
    
        public double[] randPoint() {
            double len = Math.sqrt(random.nextDouble()) * r;
            double rad = random.nextDouble() * Math.PI * 2;
            return new double[]{len * Math.cos(rad) + x, len * Math.sin(rad) + y};
        }
    }
    
  • 相关阅读:
    IT经典书籍——Head First系列【推荐】
    IT经典书籍——Head First系列【推荐】
    使用JSP实现用户登录
    使用JSP实现用户登录
    【知乎精选】如何面试一个产品经理?如何判断一个产品经理是否是一个很牛的产品经理?
    淘宝API总结
    「用户标签」在数据库设计时应该如何存储?
    【爬虫集合】抖音API分析
    商业架构体系
    短视频带货
  • 原文地址:https://www.cnblogs.com/mapoos/p/14550308.html
Copyright © 2011-2022 走看看