找到随机的国家,但选择人口更多的国家的可能性应该更高 [英] find random country but probability of picking higher population country should be higher

查看:163
本文介绍了找到随机的国家,但选择人口更多的国家的可能性应该更高的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在处理以下面试问题:

I am working on below interview question:


如果您获得了国家/地区及其相应人口的清单,则
编写将返回随机国家/地区的函数,但是该国家/地区的
人口越高,则越有可能以
的随机性来选择它。

If you're given a list of countries and its corresponding population, write a function that will return a random country but the higher the population of the country, the more likely it is to be picked at random.

我想出了以下逻辑:


在列表中进行两次遍历。在第一个遍历中,对每个位置的所有
人口求和,以得出总人口TOTAL_POP。在
的第二次迭代中,针对TOTAL_POP计算每个位置的人口
的百分比。例如,如果位置A的人口为 a。
A的人口百分比为(a / TOTAL_POP)* 100。

Make two traversal on the list. In the first traversal, sum up all the population of every location to get the total population TOTAL_POP. In the second iteration, calculate % of each location's population against TOTAL_POP. For example, if location A has a popoulation 'a'. The percentage of population for A is (a/TOTAL_POP)*100.

让我们说,经过这些步骤,我们得到以下值。位置A
= 35%B = 22%C = 19%D = 20%E = 4%

Let's say, after these steps, we have the following values. Location A = 35% B = 22% C = 19% D = 20% E = 4%

请注意,百分比总计应为100。

Note that the percentages should add up to 100.

现在,随机生成1到100之间的数字'n'。

Now, randomly generate a number 'n' between 1 and 100.

如果1 <= n < = 35输出A 36< = n&=; 57输出B

if 1 <= n <=35 OUTPUT A 36 <= n <= 57 OUTPUT B

有没有更好的方法来解决此问题?算法或代码都可以。另外,如果我们要用Java实现此功能,那么在这里使用的最佳数据结构是什么?

Is there any better way to solve this problem? Algorithm or code anything is fine. Also if we are gonna implement this in Java then what is the best data structure to use here?

推荐答案

您可以使用 TreeMap 为此,它是O(log n)并具有方便的api。

You can use TreeMap for this, it is O(log n) and has a handy api. Something like:

TreeMap<Integer, Country> map = new TreeMap<>();
map.put(percentCountry1, country1);
map.put(percentCountry1 + percentCountry2, country2);
// ...

int random = (new Random()).nextInt(100);
Country country = map.ceilingEntry(random).getValue();

这篇关于找到随机的国家,但选择人口更多的国家的可能性应该更高的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆