本文介绍了是否要求的qsort比较一致的或者我可以用它来洗牌?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

更新:请在不好的想法此文件。你没有得到对生活无任何事情,在这里肯定是明证。一个简单的想法变质了。这是肯定的东西但是从学习。

Update: Please file this under bad ideas. You don't get anything for free in life and here is certainly proof. A simple idea gone bad. It is definitely something to learn from however.

简化编程挑战。如果我传递50-50返回true或false为的qsort的比较函数的函数我认为我可以有效地不排序结构写3行code的数组。

Lazy programming challenge. If I pass a function that 50-50 returns true or false for the qsort's comparision function I think that I can effectively unsort an array of structures writing 3 lines of code.

int main ( int argc, char **argv)
{
    srand( time(NULL) );  /* 1 */
    ...
    /* qsort(....) */     /* 2 */
}

...

int comp_nums(const int *num1, const int *num2)
{
    float frand = 
          (float) (rand()) / ((float) (RAND_MAX+1.0));  /* 3 */

    if (frand >= 0.5f)
         return GREATER_THAN;
    return LESS_THAN;
}

我要寻找任何陷阱?是否有可能在更少的行通过交换或这是我得到的3个非平凡行最干净?

Any pitfalls I need to look for? Is it possible in fewer lines through swapping or is this the cleanest I get for 3 non trivial lines?

推荐答案

坏主意。我的意思是非常糟糕的。

Bad idea. I mean really bad.

您的解决方案提供了一个未predictable 的结果,而不是一个随机的结果,是一个的区别。你有什么用随机比较的的qsort会做没有真正的想法,所有的组合是否同样有可能。这是一个洗牌的最重要标准:所有的组合都必须同样可能。偏颇的结果等于大麻烦。有没有办法去证明,在你的榜样。

Your solution gives an unpredictable result, not a random result and there is a big difference. You have no real idea of what a qsort with a random comparison will do and whether all combinations are equally likely. This is the most important criterion for a shuffle: all combinations must be equally likely. Biased results equal big trouble. There's no way to prove that in your example.

您应该实现(或称为克努特洗牌)。

You should implement the Fisher-Yates shuffle (otherwise known as the Knuth shuffle).

这篇关于是否要求的qsort比较一致的或者我可以用它来洗牌?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-26 21:17