There are many resources with regard to on the net try what he says adult dating recommendation for young or old which are readily available on the internet. Individuals that find these kinds of info with the Web can consider a huge variety of choices. Once people need selected their search alternative, they might next end up being guided of what to perform to identify a perfect star of the wedding. There are many choices for all those individuals in terms of finding the suitable special someone. There are several services that assist individuals meet up with the other person. This is known as internet dating or perhaps digital seeing. Internet dating features a number of actions and contains grow to be very popular due to this fact. In most cases, in addition, it involves the option of conntacting your lover and once an individual hopes to agree to a long marriage with all the particular person, they can use this particular provider. An enormous advantages that is which is available from this particular service plan is that those who would like to find brides from other countries could also utilize this system to identify a perfect match for themselves. By Net birdes-to-be, men and women can be in a position to search through a large number of user profiles create options swiftly. The selection procedure is manufactured simple for those that want to find wedding brides on their own. There are a number associated with web pages that provide a good number involving alternatives to the people who would like to locate their own best brides. A lot of people just who find wedding brides on the web and request his or her service providers ask for distinct sums. Various web sites own decent charges, while some need fairly high fees. Because a individual has started a marriage through an Web star of the event, the purchase price is usually really low. Typically, persons pay back monthly or even yearly subscription payment.

There are many resources with regard to on the net try what he says adult dating recommendation for young or old which are readily available on the internet. Individuals that find these kinds of info with the Web can consider a huge variety of choices. Once people need selected their search alternative, they might next end up being guided of what to perform to identify a perfect star of the wedding. There are many choices for all those individuals in terms of finding the suitable special someone.

There are several services that assist individuals meet up with the other person. This is known as internet dating or perhaps digital seeing. Internet dating features a number of actions and contains grow to be very popular due to this fact. In most cases, in addition, it involves the option of conntacting your lover and once an individual hopes to agree to a long marriage with all the particular person, they can use this particular provider. An enormous advantages that is which is available from this particular service plan is that those who would like to find brides from other countries could also utilize this system to identify a perfect match for themselves.

By Net birdes-to-be, men and women can be in a position to search through a large number of user profiles create options swiftly. The selection procedure is manufactured simple for those that want to find wedding brides on their own. There are a number associated with web pages that provide a good number involving alternatives to the people who would like to locate their own best brides. A lot of people just who find wedding brides on the web and request his or her service providers ask for distinct sums. Various web sites own decent charges, while some need fairly high fees. Because a individual has started a marriage through an Web star of the event, the purchase price is usually really low. Typically, persons pay back monthly or even yearly subscription payment.

There are numerous options designed for internet online dating information for men and women which have been readily available on the internet. People that get this sort of information with the Net consider a massive variety of choices. Once people include selected their own lookup choice, they may next end up being led about what to carry out to locate a perfect star of the event. There are several possibilities for people people when it comes to locating the ideal mate. There are several products of which help people meet one another. That is referred to as online dating services or perhaps online dating. Online dating consists of a lot of hobbies and it has turn out to be very popular consequently. In some instances, additionally, it incorporates the choice of communicating with your partner so when an individual dreams in order to commit to a long term partnership while using man or woman, they can use this particular provider. A huge edge that may be provided by this support is that folks that would like to get wedding brides from other countries could also employ this provider www.mybeautifulbride.net/rating/amolatina to find a perfect diamond necklace on their own. Via Web wedding brides, folks can now be in a position to read through many users and make alternatives rapidly. The selection process is manufactured possible for folks who wish to discover brides to be on their own. There are many associated with internet websites that offer a good number involving alternatives to the people who would like to discover the perfect birdes-to-be. A lot of people which find brides to be on the web and request their providers request varied portions. Numerous web sites contain fair costs, whilst others need relatively thousands of dollars15143. When a particular person is the romance with the Web woman, the purchase price is usually really low. Generally, individuals pay out monthly or yearly registration rate.

There are numerous options designed for internet online dating information for men and women which have been readily available on the internet. People that get this sort of information with the Net consider a massive variety of choices. Once people include selected their own lookup choice, they may next end up being led about what to carry out to locate a perfect star of the event. There are several possibilities for people people when it comes to locating the ideal mate.

There are several products of which help people meet one another. That is referred to as online dating services or perhaps online dating. Online dating consists of a lot of hobbies and it has turn out to be very popular consequently. In some instances, additionally, it incorporates the choice of communicating with your partner so when an individual dreams in order to commit to a long term partnership while using man or woman, they can use this particular provider. A huge edge that may be provided by this support is that folks that would like to get wedding brides from other countries could also employ this provider www.mybeautifulbride.net/rating/amolatina to find a perfect diamond necklace on their own.

Via Web wedding brides, folks can now be in a position to read through many users and make alternatives rapidly. The selection process is manufactured possible for folks who wish to discover brides to be on their own. There are many associated with internet websites that offer a good number involving alternatives to the people who would like to discover the perfect birdes-to-be. A lot of people which find brides to be on the web and request their providers request varied portions. Numerous web sites contain fair costs, whilst others need relatively thousands of dollars15143. When a particular person is the romance with the Web woman, the purchase price is usually really low. Generally, individuals pay out monthly or yearly registration rate.

A variety of sources with regard to web based https://mybeautifulbride.net/rating/love-swans dating advice for different persons which are easily accessible from the web. Those who search for this kind of information through the World wide web peruse a huge variety of alternatives. Household include chosen their particular research alternative, they could subsequently always be well guided of what you need to do to find a best bride-to-be. There are plenty of options available for the both males and females when it comes to how to find the most suitable lover. There are numerous solutions of which assist individuals meet up with the other person. This is referred to as online dating services or virtual going out with. Online dating has a many routines and has come to be very popular because of this. Often, in addition, it contains the option of communicating with your lover and once someone dreams to be able to agree to a long term connection while using person, useful to them this product. A large benefits that is certainly made available from this specific system is the fact folks who wish to find brides to be from a different nation may also utilize this company to identify a perfect match for themselves. By means of World wide web brides to be, persons can be allowed to read through a large number of single profiles and make selections rapidly. The selection procedure is produced simple for people who desire to get birdes-to-be on their own. There are many associated with sites which provide a good number regarding alternatives to people who would like to get their particular best birdes-to-be. Lots of people whom get brides to be on the internet and request their particular service providers command numerous quantities. Numerous websites possess reasonable costs, while some experience fairly high fees. If your individual has started a new romance using an Net woman, the cost is often suprisingly low. Usually, persons shell out monthly or yearly membership payment.

A variety of sources with regard to web based https://mybeautifulbride.net/rating/love-swans dating advice for different persons which are easily accessible from the web. Those who search for this kind of information through the World wide web peruse a huge variety of alternatives. Household include chosen their particular research alternative, they could subsequently always be well guided of what you need to do to find a best bride-to-be. There are plenty of options available for the both males and females when it comes to how to find the most suitable lover.

There are numerous solutions of which assist individuals meet up with the other person. This is referred to as online dating services or virtual going out with. Online dating has a many routines and has come to be very popular because of this. Often, in addition, it contains the option of communicating with your lover and once someone dreams to be able to agree to a long term connection while using person, useful to them this product. A large benefits that is certainly made available from this specific system is the fact folks who wish to find brides to be from a different nation may also utilize this company to identify a perfect match for themselves.

By means of World wide web brides to be, persons can be allowed to read through a large number of single profiles and make selections rapidly. The selection procedure is produced simple for people who desire to get birdes-to-be on their own. There are many associated with sites which provide a good number regarding alternatives to people who would like to get their particular best birdes-to-be. Lots of people whom get brides to be on the internet and request their particular service providers command numerous quantities. Numerous websites possess reasonable costs, while some experience fairly high fees. If your individual has started a new romance using an Net woman, the cost is often suprisingly low. Usually, persons shell out monthly or yearly membership payment.

There are various sources designed for on the net adult dating guidance for different persons which can be readily available on the internet. People who find such type of info from the Net can choose from a huge variety of options. Once people currently have chosen his or her research choice, they might subsequently become well guided about what for you to do to get yourself a ideal star of the event. There are lots of possibilities for people women and men in terms of picking out the ideally suited partner. There are many solutions of which assist individuals match each other. This can be called online dating services or virtual courting. Online dating sites has a large amount of exercises and it has turn out to be quite popular for that reason. In most cases, additionally, it comes with the choice of communicating with your partner so when a person needs to agree to a long romantic relationship considering the particular person, useful to them this particular program. A large gain which is offered by this specific product is the fact that those that would like to locate wedding brides from other countries may also make use of this support to find a perfect match on their own. By way of Web brides, people quickly competent to flick through numerous dating profiles and make alternatives rapidly. The selection procedure is created possible for those that would like to get brides for themselves. There are numerous associated with web sites offering a good number mybeautifulbride.net/mexican-brides involving choices to the people who wish to find their own best wedding brides. Lots of people who also locate brides to be online and get their particular service providers price varied amounts. Some web sites need sensible service fees, whilst others include relatively high fees. Because a particular person is a new relationship by having an Net star of the event, the cost is often really low. Generally, individuals give monthly or total registration cost.

There are various sources designed for on the net adult dating guidance for different persons which can be readily available on the internet. People who find such type of info from the Net can choose from a huge variety of options. Once people currently have chosen his or her research choice, they might subsequently become well guided about what for you to do to get yourself a ideal star of the event. There are lots of possibilities for people women and men in terms of picking out the ideally suited partner.

There are many solutions of which assist individuals match each other. This can be called online dating services or virtual courting. Online dating sites has a large amount of exercises and it has turn out to be quite popular for that reason. In most cases, additionally, it comes with the choice of communicating with your partner so when a person needs to agree to a long romantic relationship considering the particular person, useful to them this particular program. A large gain which is offered by this specific product is the fact that those that would like to locate wedding brides from other countries may also make use of this support to find a perfect match on their own.

By way of Web brides, people quickly competent to flick through numerous dating profiles and make alternatives rapidly. The selection procedure is created possible for those that would like to get brides for themselves. There are numerous associated with web sites offering a good number mybeautifulbride.net/mexican-brides involving choices to the people who wish to find their own best wedding brides. Lots of people who also locate brides to be online and get their particular service providers price varied amounts. Some web sites need sensible service fees, whilst others include relatively high fees. Because a particular person is a new relationship by having an Net star of the event, the cost is often really low. Generally, individuals give monthly or total registration cost.

There are many options pertaining to on line online dating tips for men and women which can be readily available from the Internet. Folks that look for these kinds of information from the Internet consider a massive variety of choices. Household include selected the look for choice, they might afterward become guided on which to perform to locate a best woman. There are lots of possibilities for all those women and men when it comes to locating the suitable pal. There are many expert services that assist individuals fulfill each other. This is certainly known as online dating sites or digital internet dating. Online dating sites provides a large amount of pursuits and contains turn out to be very popular therefore. In some instances, additionally, it comprises of the choice of conntacting each other and once a person desires in order to agree to a long connection using the man or woman, they can use this kind of provider. An enormous gain which is proposed by this particular assistance is the fact those that want to find wedding brides from a different nation can also utilize this assistance to identify a perfect match for themselves. By means of Web wedding brides, men and women can now be competent to flick through many single profiles and make alternatives swiftly. The selection process is created simple for those who desire to locate wedding brides on their own. There are various regarding sites that offer many https://mybeautifulbride.net/rating/asian-melodies involving alternatives in people who would like to find the perfect brides to be. Many people who seem to find brides on the web and inquire their particular companies charge varied portions. Many web sites possess sensible costs, and some contain fairly high fees. If your particular person has started some sort of partnership through an Internet woman, the purchase price is often suprisingly low. Generally, folks fork out monthly or perhaps gross annual membership payment.

There are many options pertaining to on line online dating tips for men and women which can be readily available from the Internet. Folks that look for these kinds of information from the Internet consider a massive variety of choices. Household include selected the look for choice, they might afterward become guided on which to perform to locate a best woman. There are lots of possibilities for all those women and men when it comes to locating the suitable pal.

There are many expert services that assist individuals fulfill each other. This is certainly known as online dating sites or digital internet dating. Online dating sites provides a large amount of pursuits and contains turn out to be very popular therefore. In some instances, additionally, it comprises of the choice of conntacting each other and once a person desires in order to agree to a long connection using the man or woman, they can use this kind of provider. An enormous gain which is proposed by this particular assistance is the fact those that want to find wedding brides from a different nation can also utilize this assistance to identify a perfect match for themselves.

By means of Web wedding brides, men and women can now be competent to flick through many single profiles and make alternatives swiftly. The selection process is created simple for those who desire to locate wedding brides on their own. There are various regarding sites that offer many https://mybeautifulbride.net/rating/asian-melodies involving alternatives in people who would like to find the perfect brides to be. Many people who seem to find brides on the web and inquire their particular companies charge varied portions. Many web sites possess sensible costs, and some contain fairly high fees. If your particular person has started some sort of partnership through an Internet woman, the purchase price is often suprisingly low. Generally, folks fork out monthly or perhaps gross annual membership payment.

There are numerous options for the purpose of via the internet online dating assistance for young or old which might be easily accessible from the Internet. People who find this sort of details through the Internet can choose from a big array of options. Once people possess picked the search option, they may consequently be guided of what for you to do to locate a ideal woman. There are plenty of possibilities for anyone males and females with regards to searching out the ideally suited pal. There are various services of which help people meet the other person. This is called online dating or perhaps virtual online dating. Online dating services includes a many activities and possesses come to be very popular due to this fact. In most cases, it also contains the choice of communicating with the other individual so when someone likes to be able to agree to a long term relationship while using the person, useful to them this specific services. A big benefit which is offered by this kind of provider is the fact that those who wish to find wedding brides from other countries may also use this program to locate a perfect diamond necklace for themselves. By Internet brides to be, men and women can be in a position to search through numerous information and make alternatives quickly. The selection procedure is made simple for people who wish to find birdes-to-be on their own. There are lots of web-sites that provide a good number https://mybeautifulbride.net/colombian-brides/ of options to people who would like to discover their particular ideal wedding brides. Many individuals who seem to find brides to be on the internet and demand his or her providers charge completely different volumes. Numerous internet sites possess practical fees, while others experience fairly high fees. If your individual is a partnership with an World wide web bride-to-be, the cost is often really low. In most cases, persons give a monthly or total annual membership cost.

There are numerous options for the purpose of via the internet online dating assistance for young or old which might be easily accessible from the Internet. People who find this sort of details through the Internet can choose from a big array of options. Once people possess picked the search option, they may consequently be guided of what for you to do to locate a ideal woman. There are plenty of possibilities for anyone males and females with regards to searching out the ideally suited pal.

There are various services of which help people meet the other person. This is called online dating or perhaps virtual online dating. Online dating services includes a many activities and possesses come to be very popular due to this fact. In most cases, it also contains the choice of communicating with the other individual so when someone likes to be able to agree to a long term relationship while using the person, useful to them this specific services. A big benefit which is offered by this kind of provider is the fact that those who wish to find wedding brides from other countries may also use this program to locate a perfect diamond necklace for themselves.

By Internet brides to be, men and women can be in a position to search through numerous information and make alternatives quickly. The selection procedure is made simple for people who wish to find birdes-to-be on their own. There are lots of web-sites that provide a good number https://mybeautifulbride.net/colombian-brides/ of options to people who would like to discover their particular ideal wedding brides. Many individuals who seem to find brides to be on the internet and demand his or her providers charge completely different volumes. Numerous internet sites possess practical fees, while others experience fairly high fees. If your individual is a partnership with an World wide web bride-to-be, the cost is often really low. In most cases, persons give a monthly or total annual membership cost.

There are several options meant for web based courting help and advice for men and women that happen to be readily available on the internet. Men and women that search for such a facts from the Web can consider a huge variety of options. Once people have got selected their own look for option, they may therefore be guided about what to accomplish to locate a best woman. There are several options available for these men and women in terms of picking out the ideally suited partner. There are several expertise of which assist individuals meet up with each other. This is called internet dating or even online online dating. Online dating sites requires a wide range of actions and contains come to be very popular for that reason. Often, in addition, it comprises the choice of conntacting the other individual when someone likes in order to commit to a long marriage when using the particular person, useful to them this company. An enormous advantage that is definitely made available from this specific product is that folks that want to find brides from a different nation may also employ this services https://mybeautifulbride.net/rating/victoria-hearts to get a perfect diamond necklace on their own. By way of Internet birdes-to-be, people can now be capable of flick through a lot of single profiles and make choices rapidly. The choice method is made easy for those who want to discover brides to be on their own. There are various involving websites that offer a good number associated with options in people who wish to find the ideal brides to be. Many individuals who seem to find brides online and submission their companies ask for varied sums. Some internet sites own practical service fees, although some experience fairly thousands of dollars15143. When a particular person is the romantic relationship having an World wide web star of the wedding, the cost is generally very low. In many instances, people give monthly or perhaps gross annual subscription payment.

There are several options meant for web based courting help and advice for men and women that happen to be readily available on the internet. Men and women that search for such a facts from the Web can consider a huge variety of options. Once people have got selected their own look for option, they may therefore be guided about what to accomplish to locate a best woman. There are several options available for these men and women in terms of picking out the ideally suited partner.

There are several expertise of which assist individuals meet up with each other. This is called internet dating or even online online dating. Online dating sites requires a wide range of actions and contains come to be very popular for that reason. Often, in addition, it comprises the choice of conntacting the other individual when someone likes in order to commit to a long marriage when using the particular person, useful to them this company. An enormous advantage that is definitely made available from this specific product is that folks that want to find brides from a different nation may also employ this services https://mybeautifulbride.net/rating/victoria-hearts to get a perfect diamond necklace on their own.

By way of Internet birdes-to-be, people can now be capable of flick through a lot of single profiles and make choices rapidly. The choice method is made easy for those who want to discover brides to be on their own. There are various involving websites that offer a good number associated with options in people who wish to find the ideal brides to be. Many individuals who seem to find brides online and submission their companies ask for varied sums. Some internet sites own practical service fees, although some experience fairly thousands of dollars15143. When a particular person is the romantic relationship having an World wide web star of the wedding, the cost is generally very low. In many instances, people give monthly or perhaps gross annual subscription payment.

There are various resources pertaining to internet online dating information for men and women which can be easily accessible from the Internet. Folks who look for this sort of facts throughout the Internet consider an enormous array of alternatives. Once people have chosen their very own research alternative, they might and then end up being led about what to do to get yourself a ideal bride-to-be. There are several choices for people individuals when it comes to choosing the preferred special someone. There are lots of expert services of which assist individuals fulfill one another. This really is referred to as online dating services or virtual going out with. Online dating comes with a large amount of routines and has turn out to be very popular therefore. Often, it also involves the option of chatting with each other and once an individual likes to invest in a long romantic relationship with all the man or woman, useful to them this particular support. A big benefits that is definitely provided by this specific service is the fact that folks that desire to discover wedding brides from other countries can also use this services to get yourself a perfect match on their own. By way of World wide web brides to be, individuals can now be allowed to search through numerous users and make selections quickly. The selection process is manufactured easy for people who would like to find wedding brides on their own. There are a number regarding web pages which provide a good number mybeautifulbride.net/rating/ associated with options in people who wish to locate all their ideal birdes-to-be. Many individuals whom get birdes-to-be on the web and require his or her service providers fee numerous sums. A few internet sites need realistic costs, while others include comparatively thousands of dollars15143. Because a man or woman has started some sort of romance using an Internet bride, the purchase price is often suprisingly low. In many instances, individuals pay monthly or total annual subscription cost.

There are various resources pertaining to internet online dating information for men and women which can be easily accessible from the Internet. Folks who look for this sort of facts throughout the Internet consider an enormous array of alternatives. Once people have chosen their very own research alternative, they might and then end up being led about what to do to get yourself a ideal bride-to-be. There are several choices for people individuals when it comes to choosing the preferred special someone.

There are lots of expert services of which assist individuals fulfill one another. This really is referred to as online dating services or virtual going out with. Online dating comes with a large amount of routines and has turn out to be very popular therefore. Often, it also involves the option of chatting with each other and once an individual likes to invest in a long romantic relationship with all the man or woman, useful to them this particular support. A big benefits that is definitely provided by this specific service is the fact that folks that desire to discover wedding brides from other countries can also use this services to get yourself a perfect match on their own.

By way of World wide web brides to be, individuals can now be allowed to search through numerous users and make selections quickly. The selection process is manufactured easy for people who would like to find wedding brides on their own. There are a number regarding web pages which provide a good number mybeautifulbride.net/rating/ associated with options in people who wish to locate all their ideal birdes-to-be. Many individuals whom get birdes-to-be on the web and require his or her service providers fee numerous sums. A few internet sites need realistic costs, while others include comparatively thousands of dollars15143. Because a man or woman has started some sort of romance using an Internet bride, the purchase price is often suprisingly low. In many instances, individuals pay monthly or total annual subscription cost.

挑战全网最通俗易懂三门问题解析

之前看综艺节目时候看到了主持人和嘉宾在玩抽奖,玩就是经典的三门问题,看弹幕里很多人讨论发现了解这个坑的人不多,所以我就讲解一下。

问题描述:舞台上有三个门,一个后面有汽车,另外两个什么都没有,主持人开天眼知道所以情况。叫观众上台选择一个门,然后主持人会打开一扇空的门,然后剩下两个门问观众要不要更换选择。

答案:一定要换,不换,中奖的概率就是1/3,换了中奖概率就变成2/3了。

网上的思路都是先假设开某个,然后算出概率,然后再开哪个再算概率,然后又是一顿穷举巴拉巴拉才得出结果。好像大学概率论老师也是这么教的,具体的我忘记了。

另一种思路只需要画几张图就能说清楚


将三个门分为两部分,用户选择的1号门是一部分,剩下的2,3是一部分,那么奖品在用户部分的概率是1/3,在剩下部分的概率是2/3,然后剩下的部分主持人还给排除了一个门,那么2/3概率全部由3号门承担。所以1号门和3号门选哪个显而易见。
同理可以延伸到四门问题八门问题百门问题。
下面看一下百门问题

百门问题有个很重要的条件必须要先声明,就是主持人是只开一扇门还是会开98扇留两个,这两个种概率差别很大,三门问题是因为只剩一个门能开了,不需要这个条件。
假设用户选择了2号门,奖品在50号门

开一扇门的情况:

2号门有奖概率是1/100 = 0.01,剩下99扇门里有奖概率是99/100,主持人排除掉一个错误选项后,98扇门分担99/100的概率,所以每个门中奖概率是(99/100)/98 = 0.010102041,这样用户换不换的概率差不多,换只能提高0.0001的概率。

开98扇门错误门的情况

当主持人从剩余的99扇门给你排除了98扇门后,剩的那一扇门中奖的概率就成了 99/100。这时候用户选择更换,能提高99倍中奖概率。这和三门问题一样,只不过样本变大后更能说明更换是正确的。

由这个思路继续延伸下去,可以算出N门问题,M个选项,主持人排除K个门等等概率,这我就不多算了。

大部分情况玩游戏主持人是不会给你打开这么多门排雷,只会打开一个,于是我写了一段代码模拟了一下N个门,1个奖项,主持人只打开一扇门的情况:

function test(door_number) {
    console.log(`${door_number}门问题`)
    let right_times = 0
    let wrong_times = 0
    for(let i = 0; i < 5000; i++){
        big_win(door_number,true)?++right_times:++wrong_times
    }
    console.log('=======选择换,中奖不中奖的概率===================')
    console.log(`选对概率是:${(right_times/50).toFixed(2)}%`)
    console.log(`选错概率是:${(wrong_times/50).toFixed(2)}%`)
    let right_times_2 = 0
    let wrong_times_2 = 0
    for(let i = 0; i < 5000; i++){
        big_win(door_number,false)?++right_times_2:++wrong_times_2
    }
    console.log('=======选择不换,中奖不中奖的概率===================')
    console.log(`选对概率是:${(right_times_2/50).toFixed(2)}%`)
    console.log(`选错概率是:${(wrong_times_2/50).toFixed(2)}%`)
}
const floor = Math.floor.bind(Math)
const random = Math.random.bind(Math)
function big_win(door_number, hasChange) {
    let list = []
    list.length = door_number
    // 1为有奖 0为没有奖
    list.fill(0)
    // 生成待选项,其中一个是有钱的
    let present_index = floor(random() * door_number)
    list[present_index] = 1
    // 模拟用户随机选择一个选项
    let user_choose_idx = floor(random() * door_number)
    //模拟主持人从余下的选项中揭晓一个错误的
    let host_choosen_idx = floor(random() * door_number)
    while (host_choosen_idx === user_choose_idx || host_choosen_idx === present_index) {
        host_choosen_idx = floor(random() * door_number)
    }
    if(hasChange){
        // 用户从余下的先选项里再抽一个
        let user_choose_idx_2 = floor(random() * door_number)
        while(user_choose_idx_2 === user_choose_idx || user_choose_idx_2 ===host_choosen_idx){
            user_choose_idx_2 = floor(random() * door_number)
        }
        if(list[user_choose_idx_2] === 1){
            return true
        }else{
            return false
        }
    }else{
        if(list[user_choose_idx] === 1){
            return true
        }else{
            return false
        }
    }
}

按上面的思路,四门问题获奖概率是3/8,五门问题是4/15,换和不换各模拟5000次
测试结果

模拟结果和预想结果一致。

nodejs实现远程桌面监控

描述

最近使用node实现了一个远程桌面监控的应用,分为服务端和客户端,客户端可以实时监控服务端的桌面,并且可以通过鼠标和键盘来控制服务端的桌面。

这里因为我是用的同一台电脑,所以监控画面是这样的,当然使用两台电脑一个跑客户端,一个跑服务端才有意义。

原理

其实这个应用的功能主要分为两部分,一是实现监控,即在客户端可以看到服务端的桌面,这部分功能是通过定时截图来实现的,比如服务端一秒截几次图,然后通过socketio发送到客户端,客户端通过改变img的src来实现一帧帧的显示最新的图片,这样就能看到动态的桌面了。监控就是这样实现的。

另一个功能是控制,即客户端对监控画面的操作,包括鼠标和键盘的操作都可以在服务端的桌面真正的生效,这部分功能的实现是在electron的应用中监听了所有的鼠标和键盘事件,比如keydown、keyup、keypress,mousedown、mouseup、mousemove、click等,然后通过socketio把事件传递到服务端,服务端通过 robot-js来执行不同的事件,这样就能使得客户端的事件在服务端触发了。

实现

原理讲完,我们来具体实现一下(源码链接在这)。

实现socket通信

首先,服务端和客户端分别引入socket.iosocket.io-client, 分别初始化

服务端:

const app = new Koa();
const server = http.createServer(app.callback());
createSocketIO(server);

app.use((ctx): void => {
    ctx.body = 'please connect use socket';
});

server.listen(port, (): void => {
    console.log('server started at http://localhost:' + port);
});
//createSocketIO
const io = socketIO(server, {
        pingInterval: 10000,
        pingTimeout: 5000,
        cookie: false
    });

io.on('connect', (socket): void => {
    socket.emit('msg', 'connected');
}

客户端:

var socket = this.socket = io('http://' + this.ip + ':3000')
socket.on('msg', (msg) => {
  console.log(msg)
})
socket.on('error', (err) => {
  alert('出错了' + err)
})

这样,服务端和客户端就通过socketio建立了链接。

实现桌面监控

之后我们首先要在服务端来截图,使用screenshot-desktop这个包

const screenshot = require('screenshot-desktop')

const SCREENSHOT_INTERVAL = 500;

export const createScreenshot = (): Promise<[string, Buffer]> => {
    return screenshot({format: 'png'}).then((img): [string, Buffer] => {
        return [ img.toString('base64'), img];
    }).catch((err): {} => {
        console.log('截图失败', err);
        return err;
    })
}

export const startScreenshotTimer = (callback): {} => {
    return setInterval((): void => {
        createScreenshot().then(([imgStr, img]): void => {
            callback(['data:image/png;base64,' + imgStr, img]);
        })
    }, SCREENSHOT_INTERVAL)
}

然后通过socketio的emit来传到客户端:

startScreenshotTimer(([imgStr, img]): void => {
    io.sockets.emit('screenshot', imgStr);
});

客户端收到图片后,设置到img的src上(这里是base64的图片url):

 <img 
    class="screenshot" 
    :src="screenshot"
/>
data () {
  return {
    screenshot: ''
  }
}
socket.on('screenshot', (data) => {
  this.screenshot = data
})

其实这样就已经实现了桌面监控了,有兴趣的同学可以照着这个思路实现看看,并不是很麻烦。

当然这样的方案是有问题的,因为我们需要知道服务端桌面尺寸的大小,然后根据这个来调整客户端显示的图片尺寸。

实现这个细节是使用的get-pixels这个库,可以读取本地图片文件的宽度高度等信息,所以我先把图片写入本地,然后又读取出来,这样获取到的屏幕尺寸。

interface ScreenSize {
    width: number;
    height: number;
}

function getScreenSize(img): Promise<ScreenSize> {
    const imgPath = path.resolve(process.cwd(), './tmp.png');
    fs.writeFileSync(imgPath, img);
    return new Promise((resolve): void => {
        getPixels(imgPath, function(err, pixels): void {
            if(err) {
                console.log("Bad image path")
                return
            }
            resolve({
                width: pixels.shape[0],
                height: pixels.shape[1]
            });
        });
    })
}

然后通过socektio传递给客户端

getScreenSize(img).then(({ width, height}) => {
    io.sockets.emit('screensize', {
        width,
        height
    })
});

客户端收到之后调整图片大小就可以了

<img 
    class="screenshot" 
    :src="screenshot"
    :style="screenshotStyle"
/>
data () {
  return {
    screenshot: '',
    screenshotStyle: '',
  }
}
socket.on('screensize', (screensize) => {
  this.screenshotStyle = {'width': screensize.width + 'px', 'height': screensize.height + 'px'}
})

至此已经实现了桌面监控,并且图片尺寸和服务端屏幕的尺寸是一致的。

这里还有一个细节,就是获取到的图片大小是物理像素,而客户端设置的px是设备无关像素,也就是要除以dpr才是px的值。这里需要获取dpr,因为目前只是在mac下用,所以直接除以2了。

实现远程控制

代码写到这里,客户端的electron应用中已经可以实时显示服务端的桌面了。(当然像输入ip的弹框,以及electron-vue和typescript等和主要逻辑无关的细节就不展开了。)

接下来我们要实现远程控制,也就是监听事件,传递事件,执行事件这几部分。

首先我们定义一下传递的事件的格式:

interface MouseEvent {
    type: string;
    buttonType: string;
    x: number;
    y: number;
}

interface KeyboardEvent {
    type: string;
    keyCode: number;
    keyName: string;
}

鼠标事件MouseEvent,type为鼠标事件的类型,具体的值包括mousedown、mouseup、mousemove、click、dblclick,buttonType指的是鼠标的左键还是右键,值为 left 或 right,x和y是具体的坐标。

键盘事件KeyboardEvent,type为键盘事件的类型,具体的值包括keydown、keyup、keypress,keyCode为键盘码,keyName为键的名字。

接下来我们要在客户端监听事件:

<img 
    class="screenshot" 
    :src="screenshot"
    :style="screenshotStyle"
    @mousedown="handleMouseEvent"
    @mousemove="handleMouseEvent" 
    @mouseup="handleMouseEvent"
    @click="handleMouseEvent"
    @dblclick="handleMouseEvent"   
/>
window.onkeypress = window.onkeyup = window.onkeydown = this.handleKeyboardEvent

通过socekt把事件传递到服务端

  handleKeyboardEvent (e) {
    this.socket && this.socket.emit('userevent', {
      type: 'keyboard',
      event: {
        type: e.type,
        keyName: e.key,
        keyCode: e.keyCode
      }
    })
  },
  handleMouseEvent (e) {
    this.socket && this.socket.emit('userevent', {
      type: 'mouse',
      event: {
        type: e.type,
        buttonType: e.buttons === 2 ? 'right' : 'left',
        x: e.clientX,
        y: e.clientY
      }
    })
  },

然后在服务端把事件取出来执行,执行事件使用的是robot-js


const { Mouse, Point, Keyboard } = require('robot-js'); interface MouseEvent { type: string; buttonType: string; x: number; y: number; } interface KeyboardEvent { type: string; keyCode: number; keyName: string; } export default class EventExecuter { public mouse; public keyboard; public constructor(){ this.mouse = new Mouse(); this.keyboard = new Keyboard(); } public executeKeyboardEvent(event: KeyboardEvent): void { switch(event.type) { case 'keydown': this.keyboard.press(event.keyCode); break; case 'keyup': this.keyboard.release(event.keyCode); break; case 'keypress': this.keyboard.click(event.keyCode); break; default: break; } } public executeMouseEvent(event): void { Mouse.setPos(new Point(event.x, event.y)); const button = event.buttonType === 'left' ? 0 : 2 switch(event.type) { case 'mousedown': this.mouse.press(button); break; case 'mousemove': break; case 'mouseup': this.mouse.release(button); break; case 'click': this.mouse.click(button); break; case 'dblclick': this.mouse.click(button); this.mouse.click(button); break; default: break; } } public exectue(eventInfo): void { console.log(eventInfo); switch (eventInfo.type) { case 'keyboard': this.executeKeyboardEvent(eventInfo.event); break; case 'mouse': this.executeMouseEvent(eventInfo.event); break; default: break; } } }

至此,桌面监控和远程控制的客户端还有服务端的部分,以及两端的通信都已经实现了。思路其实并不麻烦,但细节还是很多的。有兴趣的同学可以把代码下下来跑跑试试,或者按着这个思路自己实现一遍,还是挺好玩的。

源码链接

remote-monitor-server

remote-monitor-client