检查列表是否包含零的最快方法

发布于 2024-12-22 17:38:43 字数 510 浏览 3 评论 0原文

在准备回答秘密圣诞老人 - 生成“有效”排列时,我遇到需要检查列表是否包含零。我想知道在 Mathematica 7 中执行此操作的最快方法是什么,重点是非负整数的简短列表。

使用 Min[list] === 0 是我发现的最快的,比 MemberQFreeQ 更快,但我希望有一个更快的方法,与下面的 BitXor 操作相当:

r = Range@9;
p = Permutations@r;

BitXor[r, #] & /@ p; // Timing
0 === Min[BitXor[r, #]] & /@ p; // Timing
{0.062, Null}
{0.452, Null}

While preparing an answer to Secret Santa - Generating 'valid' permutations I came across the need to check if a list contains zero. I am wondering what the fastest way to do this in Mathematica 7 is, with emphasis on a short list of non-negative integers.

Using Min[list] === 0 is the fastest I have found, faster than MemberQ or FreeQ, but I am hoping there is a faster way, on par with the BitXor operation below:

r = Range@9;
p = Permutations@r;

BitXor[r, #] & /@ p; // Timing
0 === Min[BitXor[r, #]] & /@ p; // Timing
{0.062, Null}
{0.452, Null}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

厌味 2024-12-29 17:38:43

问题中使用的 0 === Min 的减速似乎是对 Map 自动编译的干扰。分离这些步骤几乎提供了双重改进:

r = Range@9;
p = Permutations@r;

Min@# === 0 & /@ (BitXor[r, #] & /@ p); // Timing
{0.296, Null}

如果我接受结果为 (0|1) 并且如果我将列表作为一个处理,那么我可以使用以下命令:

Unitize[Times @@ BitXor[r, #] & /@ p]; // Timing
{0.156, Null}

It appears that part of the slowdown with 0 === Min as used in the question is interference with the autocompile of Map. Separating these steps provides nearly a twofold improvement:

r = Range@9;
p = Permutations@r;

Min@# === 0 & /@ (BitXor[r, #] & /@ p); // Timing
{0.296, Null}

If I accept a result as (0|1) and if I process the list as one then I can use this:

Unitize[Times @@ BitXor[r, #] & /@ p]; // Timing
{0.156, Null}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文