jjzjj

c++ - 已婚人口的比例是多少?

coder 2024-02-22 原文

下面的问题是我在这个 wiki page 上遇到的一个问题.

Write a program to discover the answer to this puzzle:"Let's say men and women are paid equally (from the same uniform distribution). If women date randomly and marry the first man with a higher salary, what fraction of the population will get married?"

我的算法:

  1. 用随机薪水值填充两个数组(女性和男性)。

  2. 随机将一名女性与一名男性配对,然后比较薪水。如果是女的 工资低于男性,增加婚姻柜台。集双女 男性 isMarried 值为 true。

  3. 继续约会过程,直到未婚男性的最高工资为 低于未婚女性的最低工资。

这是我的实现:

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);


    srand(time(NULL));


    int min = 1;
    int max = 1000000;
    Male male[100];
    Female female[100];
    double count = 0;
    bool done = false;





    //Fill array of Females and Males with random salaries ranging from 1 to 10
    for(int i=0; i<100; i++){
        int output = min + (rand() % (int)(max - min + 1));
        male[i].salary = output;
    }
    for(int i=0; i<100; i++){
        int output = min + (rand() % (int)(max - min + 1));
        female[i].salary = output;
    }


    //Start dating
    //Keep dating until the maximum salary of males is lower than minimum salary of females

    do{
        random_shuffle(begin(male), end(male));               //Shuffle array of males
        random_shuffle(begin(female), end(female));           //Shuffle array of females


        for(int i=0; i<100; i++){                              //Compare a female and male from both arrays
            if(female[i].salary < male[i].salary)
                if(!female[i].isMarried && !male[i].isMarried){
                    count++;
                    female[i].isMarried = true;
                    male[i].isMarried = true;
                    cout << "Female salary: " << female[i].salary << endl;
                    cout << "Male salary: " << male[i].salary << endl;
                }
        }

        int maxMen = 0;
        for(int i=0; i<100; i++){
            if(male[i].salary > maxMen && !male[i].isMarried)
                maxMen = male[i].salary;
        }

        int minWomen = 1000000;
        for(int i=0; i<100; i++){
            if(female[i].salary < minWomen && !female[i].isMarried)
                minWomen = female[i].salary;
        }

        if(maxMen <= minWomen)
            done = true;


    }while(!done);


    cout << "Percentage: " << count/100;
    cout << endl;

    int unmarried = 0;
    cout << "Number of unmarried females: ";
    for(int i=0; i<100; i++)
        if(!female[i].isMarried)
            unmarried++;
    cout << unmarried << endl;

    unmarried = 0;
    cout << "Number of unmarried males: ";
    for(int i=0; i<100; i++)
        if(!male[i].isMarried)
            unmarried++;
    cout << unmarried << endl;

    cout << endl;




    return a.exec();
}

我在 Programmers.SE 上问过这个问题,显然,I should be getting 68% . 我得到的百分比值在 35% 到 40% 之间。我做错了什么?

最佳答案

1) 您的条件变量已初始化:

bool done=false;  

这可能会导致比计划更早退出循环,因为它仅在 maxMen < minWomen 时设置为可预测的值。 .

2) 您的结束条件设置不正确:

你只在maxMen < minWomen时完成了.但是如果 maxMen == minWomen没有女人会再结婚,所以你会有一个无限循环。如果你的工资规模很小,这种现象很可能发生。如果你从 1 到 1000,这种情况不太可能发生。但为了避免不可能的情况,将子句更改为:

    if (maxMen <= minWomen)   // no new wedding in sight
        done = true;

结合前面的问题,你的循环条件是错误的。你应该循环,只要它没有完成(如果 maxMen > minWomen,仍然有婚礼的可能)。所以改写为:

...
} while (! done);

结论

通过这 3 个更改,当我多次重新运行程序时,我得到的百分比从 55% 到 74%,大多数值在 65% 到 70% 之间。

其他建议

您应该避免硬编码数字。而不是 10 , 但更喜欢 max+1 .在开头定义const int N=100;并替换所有文字 100N .通过这种方式,可以更轻松地使用模拟参数(使用不同的薪水范围或更大的人口)。

您可以将模拟放在一个单独的函数中,将百分比作为值返回,然后在 main() 中多次运行模拟(100 次、1000 次?),计算百分比的平均值和标准差。这比手动运行和粗略估计提供更准确的结果。

如果您对模拟感兴趣,可能值得看看 <random> :它提供了大量的随机生成器和随机分布选择,比 rand() 强大得多。示例:

    mt19937 generator(time(NULL));  // mersene twister generator seeded with time 
    ...
    uniform_int_distribution<int> distribution(min, max);  // after declaration of your min and max
    ...
    male[i].salary = distribution(generator);   // and same for female 

顺便说一下,您可能对 std::count_if 感兴趣, std::min() std::max()这可以轻松地为您节省 for 循环的重复编码。

关于c++ - 已婚人口的比例是多少?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25477141/

有关c++ - 已婚人口的比例是多少?的更多相关文章

  1. ruby-on-rails - 如何优雅地重启 thin + nginx? - 2

    我的瘦服务器配置了nginx,我的ROR应用程序正在它们上运行。在我发布代码更新时运行thinrestart会给我的应用程序带来一些停机时间。我试图弄清楚如何优雅地重启正在运行的Thin实例,但找不到好的解决方案。有没有人能做到这一点? 最佳答案 #Restartjustthethinserverdescribedbythatconfigsudothin-C/etc/thin/mysite.ymlrestartNginx将继续运行并代理请求。如果您将Nginx设置为使用多个上游服务器,例如server{listen80;server

  2. ruby - 可以通过多少种方法将方法添加到 ruby​​ 对象? - 2

    当谈到运行时自省(introspection)和动态代码生成时,我认为ruby​​没有任何竞争对手,可能除了一些lisp方言。前几天,我正在做一些代码练习来探索ruby​​的动态功能,我开始想知道如何向现有对象添加方法。以下是我能想到的3种方法:obj=Object.new#addamethoddirectlydefobj.new_method...end#addamethodindirectlywiththesingletonclassclass这只是冰山一角,因为我还没有探索instance_eval、module_eval和define_method的各种组合。是否有在线/离线资

  3. ruby - 使用 `+=` 和 `send` 方法 - 2

    如何将send与+=一起使用?a=20;a.send"+=",10undefinedmethod`+='for20:Fixnuma=20;a+=10=>30 最佳答案 恐怕你不能。+=不是方法,而是语法糖。参见http://www.ruby-doc.org/docs/ProgrammingRuby/html/tut_expressions.html它说Incommonwithmanyotherlanguages,Rubyhasasyntacticshortcut:a=a+2maybewrittenasa+=2.你能做的最好的事情是:

  4. ruby - 如何计算 Liquid 中的变量 +1 - 2

    我对如何计算通过{%assignvar=0%}赋值的变量加一完全感到困惑。这应该是最简单的任务。到目前为止,这是我尝试过的:{%assignamount=0%}{%forvariantinproduct.variants%}{%assignamount=amount+1%}{%endfor%}Amount:{{amount}}结果总是0。也许我忽略了一些明显的东西。也许有更好的方法。我想要存档的只是获取运行的迭代次数。 最佳答案 因为{{incrementamount}}将输出您的变量值并且不会影响{%assign%}定义的变量,我

  5. ruby - 使用 Ruby,计算 n x m 数组的每一列中有多少个 true 的简单方法是什么? - 2

    给定一个nxmbool数组:[[true,true,false],[false,true,true],[false,true,true]]有什么简单的方法可以返回“该列中有多少个true?”结果应该是[1,3,2] 最佳答案 使用转置得到一个数组,其中每个子数组代表一列,然后将每一列映射到其中的true数:arr.transpose.map{|subarr|subarr.count(true)}这是一个带有inject的版本,应该在1.8.6上运行,没有任何依赖:arr.transpose.map{|subarr|subarr.in

  6. arrays - Ruby 数组 += vs 推送 - 2

    我有一个数组数组,想将元素附加到子数组。+=做我想做的,但我想了解为什么push不做。我期望的行为(并与+=一起工作):b=Array.new(3,[])b[0]+=["apple"]b[1]+=["orange"]b[2]+=["frog"]b=>[["苹果"],["橙子"],["Frog"]]通过推送,我将推送的元素附加到每个子数组(为什么?):a=Array.new(3,[])a[0].push("apple")a[1].push("orange")a[2].push("frog")a=>[[“苹果”、“橙子”、“Frog”]、[“苹果”、“橙子”、“Frog”]、[“苹果”、“

  7. += 的 Ruby 方法 - 2

    有没有办法让Ruby能够做这样的事情?classPlane@moved=0@x=0defx+=(v)#thisiserror@x+=v@moved+=1enddefto_s"moved#{@moved}times,currentxis#{@x}"endendplane=Plane.newplane.x+=5plane.x+=10putsplane.to_s#moved2times,currentxis15 最佳答案 您不能在Ruby中覆盖复合赋值运算符。任务在内部处理。您应该覆盖+,而不是+=。plane.a+=b与plane.a=

  8. ruby - Sinatra + Heroku + Datamapper 使用 dm-sqlite-adapter 部署问题 - 2

    出于某种原因,heroku尝试要求dm-sqlite-adapter,即使它应该在这里使用Postgres。请注意,这发生在我打开任何URL时-而不是在gitpush本身期间。我构建了一个默认的Facebook应用程序。gem文件:source:gemcuttergem"foreman"gem"sinatra"gem"mogli"gem"json"gem"httparty"gem"thin"gem"data_mapper"gem"heroku"group:productiondogem"pg"gem"dm-postgres-adapter"endgroup:development,:t

  9. ruby - Ruby 中字符串运算符 + 和 << 的区别 - 2

    我是Ruby和这个网站的新手。下面两个函数是不同的,一个在函数外修改变量,一个不修改。defm1(x)x我想确保我理解正确-当调用m1时,对str的引用被复制并传递给将其视为x的函数。运算符当调用m2时,对str的引用被复制并传递给将其视为x的函数。运算符+创建一个新字符串,赋值x=x+"4"只是将x重定向到新字符串,而原始str变量保持不变。对吧?谢谢 最佳答案 String#+::str+other_str→new_strConcatenation—ReturnsanewStringcontainingother_strconc

  10. ruby - rails 3.2.2(或 3.2.1)+ Postgresql 9.1.3 + Ubuntu 11.10 连接错误 - 2

    我正在使用PostgreSQL9.1.3(x86_64-pc-linux-gnu上的PostgreSQL9.1.3,由gcc-4.6.real(Ubuntu/Linaro4.6.1-9ubuntu3)4.6.1,64位编译)和在ubuntu11.10上运行3.2.2或3.2.1。现在,我可以使用以下命令连接PostgreSQLsupostgres输入密码我可以看到postgres=#我将以下详细信息放在我的config/database.yml中并执行“railsdb”,它工作正常。开发:adapter:postgresqlencoding:utf8reconnect:falsedat

随机推荐