- 积分
- 14
- 注册时间
- 2009-5-7
- 仿真币
-
- 最后登录
- 1970-1-1
|
发表于 2010-3-26 13:18:51
|
显示全部楼层
来自 北京
- In[197]:= arr = Permutations[Range[2, 9], {5}];
- lena = Length@arr;
- brr = Table[FromDigits[arr[[k]]], {k, 1, lena}] + 10^5;
- For[j = 1, j <= lena, j++,
- If[Sort[IntegerDigits[2 brr[[j]]]] ==
- Sort[IntegerDigits[ brr[[j]]]] &&
- Sort[IntegerDigits[3 brr[[j]]]] ==
- Sort[IntegerDigits[ brr[[j]]]] &&
- Sort[IntegerDigits[4 brr[[j]]]] ==
- Sort[IntegerDigits[ brr[[j]]]] &&
- Sort[IntegerDigits[5 brr[[j]]]] ==
- Sort[IntegerDigits[ brr[[j]]]] &&
- Sort[IntegerDigits[6 brr[[j]]]] ==
- Sort[IntegerDigits[ brr[[j]]]], Print[ brr[[j]]];
- Break[]]] // Timing
- During evaluation of In[197]:= 142857
- Out[200]= {0.032, Null}
复制代码 看起来Catch和For的速度差不多啊.但是For有一个好处是,如果还有其它解,不用Break[]就能找的所有解了.而Catch只能找到1个解就跳出来了.这也是它比Select快的原因.Select是先找到所有满足条件的结果,再比较大小的.
下面通过找所有满足条件的解,比较For和Select的速度可知,两者的速度是在同一数量级呢,但是Select比较占内存的.- In[221]:= arr = Permutations[Range[2, 9], {5}];
- lena = Length@arr;
- brr = Table[FromDigits[arr[[k]]], {k, 1, lena}] + 10^5;
- Timing[Select[brr,
- Sort[IntegerDigits[#]] == Sort[IntegerDigits[2 #]] ==
- Sort[IntegerDigits[3 #]] == Sort[IntegerDigits[4 #]] ==
- Sort[IntegerDigits[5 #]] == Sort[IntegerDigits[6 #]] &]]
- Timing[For[j = 1, j <= lena, j++,
- If[Sort[IntegerDigits[2 brr[[j]]]] ==
- Sort[IntegerDigits[ brr[[j]]]] &&
- Sort[IntegerDigits[3 brr[[j]]]] ==
- Sort[IntegerDigits[ brr[[j]]]] &&
- Sort[IntegerDigits[4 brr[[j]]]] ==
- Sort[IntegerDigits[ brr[[j]]]] &&
- Sort[IntegerDigits[5 brr[[j]]]] ==
- Sort[IntegerDigits[ brr[[j]]]] &&
- Sort[IntegerDigits[6 brr[[j]]]] ==
- Sort[IntegerDigits[ brr[[j]]]], Print[ brr[[j]]]]]]
- Out[224]= {0.235, {142857}}
- During evaluation of In[221]:= 142857
- Out[225]= {0.109, Null}
复制代码 |
|