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.

这道题给了我们一个圆,包括中点位置和半径,让随机生成圆中的任意一个点。这里说明了圆上也当作是圆中,而且这里的随机意味着要等概率。思绪飘回了高中时代,努力搜索着那一丝丝残留的记忆,终于,博主把还给老师的知识又要了回来,圆的方程表示为 (x - a) ^ 2 + (y - b) ^ 2 = r ^ 2,这里的 (a, b) 是圆心位置,r为半径。那么如何生成圆中的任意位置呢,如果用这种方式来生成,先随机出一个x,随机出y的时候还要考虑其是否在圆中间,比较麻烦。继续回到高中时代,模糊的记忆中飘来了三个字,极坐标。是的,圆还可以用极坐标的形式来表示,只需随机出一个角度 theta,再随机出一个小于半径的长度,这样就可以得到圆中的坐标位置了,哦耶~ 先来生成 theta吧,由于一圈是 360 度,即 2pi,所以随机出一个 [0, 1] 中的小数,再乘以 2pi,就可以了。然后就是随机小于半径的长度,这里有个问题需要注意一下,这里并不是直接随机出一个 [0, 1] 中的小数再乘以半径r,而是要对随机出的 [0, 1] 中的小数取个平方根再乘以半径r。这是为啥呢,简单来说,是为了保证等概率。如果不用平方根的话,那么表示圆的时候 (len * cos(theta)) ^ 2 + (len * sin(theta) ^ 2,这里就相当于对随机出的 [0, 1] 中的小数平方了,那么其就不是等概率的了,因为两个小于1的小数相乘了,其会更加靠近0,这就是为啥要平方一下的原因。最后在求点位置的时候要加上圆心的偏移即可,参见代码如下:

解法一:

class Solution {
public:
Solution(double radius, double x_center, double y_center) {
r = radius; centerX = x_center; centerY = y_center;
} vector<double> randPoint() {
double theta = * M_PI * ((double)rand() / RAND_MAX);
double len = sqrt((double)rand() / RAND_MAX) * r;
return {centerX + len * cos(theta), centerY + len * sin(theta)};
} private:
double r, centerX, centerY;
};

我们也可以不用极坐标来做,由于之前刚做过 Implement Rand10() Using Rand7(),对其中的拒绝采样 Rejection Sampling 还有印象,所以也可以用其来做。这其实就是拒绝采样的经典应用,在一个正方形中有均匀分布的点,随机出其内切圆中的一个点,那么就是随机出x和y之后,然后算其平方和,如果小于等于r平方,说明其在圆内,可以返回其坐标,记得加上圆心偏移,否则重新进行采样。关于拒绝采样的方法可以参见博主之前那篇博客 Implement Rand10() Using Rand7(),参见代码如下:

解法二:

class Solution {
public:
Solution(double radius, double x_center, double y_center) {
r = radius; centerX = x_center; centerY = y_center;
} vector<double> randPoint() {
while (true) {
double x = ( * (double)rand() / RAND_MAX - 1.0) * r;
double y = ( * (double)rand() / RAND_MAX - 1.0) * r;
if (x * x + y * y <= r * r) return {centerX + x, centerY + y};
}
} private:
double r, centerX, centerY;
};

Github 同步地址:

https://github.com/grandyang/leetcode/issues/478

类似题目:

Implement Rand10() Using Rand7()

参考资料:

https://leetcode.com/problems/generate-random-point-in-a-circle/

https://leetcode.com/problems/generate-random-point-in-a-circle/discuss/154405/C%2B%2B-solution-polar-coordinates

https://leetcode.com/problems/generate-random-point-in-a-circle/discuss/169518/C%2B%2B-AC-solution-using-rejection-sampling

https://leetcode.com/problems/generate-random-point-in-a-circle/discuss/155650/Explanation-with-Graphs-why-using-Math.sqrt()

LeetCode All in One 题目讲解汇总(持续更新中...)

[LeetCode] Generate Random Point in a Circle 生成圆中的随机点的更多相关文章

  1. 【LeetCode】478. Generate Random Point in a Circle 解题报告(Python & C++)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 题目地址: https://leetcode.com/problems/generate ...

  2. [Swift]LeetCode478. 在圆内随机生成点 | Generate Random Point in a Circle

    Given the radius and x-y positions of the center of a circle, write a function randPoint which gener ...

  3. 478. Generate Random Point in a Circle

    1. 问题 给定一个圆的半径和圆心坐标,生成圆内点的坐标. 2. 思路 简单说 (1)在圆内随机取点不好做,但是如果画出这个圆的外接正方形,在正方形里面采样就好做了. (2)取两个random确定正方 ...

  4. [LeetCode] Random Point in Non-overlapping Rectangles 非重叠矩形中的随机点

    Given a list of non-overlapping axis-aligned rectangles rects, write a function pick which randomly ...

  5. [LeetCode] Generate Parentheses 生成括号

    Given n pairs of parentheses, write a function to generate all combinations of well-formed parenthes ...

  6. Leetcode之回溯法专题-22. 括号生成(Generate Parentheses)

    Leetcode之回溯法专题-22. 括号生成(Generate Parentheses) 给出 n 代表生成括号的对数,请你写出一个函数,使其能够生成所有可能的并且有效的括号组合. 例如,给出 n ...

  7. Java – Generate random integers in a rangejava获取某个范围内的一个随机数

    In this article, we will show you three ways to generate random integers in a range. java.util.Rando ...

  8. LeetCode All in One题解汇总(持续更新中...)

    突然很想刷刷题,LeetCode是一个不错的选择,忽略了输入输出,更好的突出了算法,省去了不少时间. dalao们发现了任何错误,或是代码无法通过,或是有更好的解法,或是有任何疑问和建议的话,可以在对 ...

  9. python生成数据库中所有表的DESC描述

    在数据库设计完成之后, 常常需要在 wiki 或其他文档中保存一份数据库中所有表的 desc 描述, 尤其是每个字段的含义和用途. 手动去生成自然是不可取的. 因此, 我编写了一个简单的 python ...

随机推荐

  1. JN_0005:PS改变图片指定内容颜色

    1,打开图片. 2,选择选区,抽取出独立图存 选中选区,按ctrl + alt + j ,抽取图层. 3,选中图层,再按住 ctrl,点击图层图标 的白色选区处,即可选中图层中的内容. 4,选中图层内 ...

  2. 第二十一节:ADO层次上的海量数据处理方案(SqlBulkCopy类插入和更新)

    一. 简介 1. 背景: 虽然前面EF的扩展插件Z.EntityFramework.Extensions,性能很快,而且也很方便,但是该插件要收费,使用免费版本的话,需要定期更新,如果不更新,将失效, ...

  3. .NET面试题系列(十七)前端面试

    JavaScript  js如何实现继承 CSS 行内元素和块状元素的区别   CSS让2个DIV在同一行显示的解决方法 在CSS中,div属于块级元素,每个块级元素默认占一行高度,一行内添加一个块级 ...

  4. [译]Ocelot - Load Balancer

    原文 可以对下游的服务进行负载均衡. 提供了下面几种负载均衡: LeastConnection - tracks which services are dealing with requests an ...

  5. Chrome firefox ie等浏览器空格&nbsp;宽度不一样

    用半角空格 或者全角空格   相当于半格中文字符的宽度, 相当于一个中文字符宽度. 注:在chrome中两个 占一个汉字的宽度;,而在IE.firefox中四个 才占一个汉字的宽度.

  6. tensorflow 模型保存和加载

    使用 tf.train.Saver 保存:tf.train.Saver.save(sess, save_path, global_step=None, latest_filename=None, me ...

  7. linux内存 free命令 buffer cache作用

    free命令用于查看linux内存使用情况 #free shared:用于进程之间相互共享数据. Used:已使用内存. total:内存总量. free:未使用的内存. available:开启一个 ...

  8. RT-SA-2019-007 Code Execution via Insecure Shell Functiongetopt_simple

    Advisory: Code Execution via Insecure Shell Function getopt_simple RedTeam Pentesting discovered tha ...

  9. IDEA 代码规范插件

    前言 在工作过程中,每个人的代码习惯都不同,在一起工作做同一个项目,如果按照自己的习惯来,有可能造成代码维护困难,开发进度缓慢等. 代码规范的重要性 谷歌发布的代码规范中指出,80% 的缺失是由 20 ...

  10. JS中some(),every(),forEach(),map(),filter()区别

    JS在1.6中为Array新增了几个方法map(),filter(),some(),every(),forEach(),也就是一共有这么多方法了. 刚开始接触这些倒也记得不是很清楚,在此纪录一下以加深 ...