[新手上路]批处理新手入门导读[视频教程]批处理基础视频教程[视频教程]VBS基础视频教程[批处理精品]批处理版照片整理器
[批处理精品]纯批处理备份&还原驱动[批处理精品]CMD命令50条不能说的秘密[在线下载]第三方命令行工具[在线帮助]VBScript / JScript 在线参考
返回列表 发帖
  1. $a = [System.Collections.Stack]::new()
  2. function cr($n, $s, $a) {if($a.count -eq $n){return $a.toarray() -join ''}for($i=0;$i -lt $s.length;$i++){$a.push($s[$i]);cr $n $s $a;$a.pop()|out-null}}
  3. 1..3 | %{$a.clear();cr $_ "asdfg" $a}
复制代码

TOP

本帖最后由 wanghan519 于 2023-9-11 06:21 编辑

又试了一下,5楼因为递归次数较多就很慢,动态规划是算法上空间换时间的优化,确实快!
试了栈改成字符串操作并不改变速度,倒是因为把递归里的一层for循环展开导致递归次数变多,浪费的时间更多,结合官方文档说调用函数的成本高昂,调用函数是直接for循环耗时的20倍以上,所以暂时结论是powershell不适合写递归。。。
5楼的算法,用awk运行需要4秒(0-9选6个以内),而python里用itertools.product(s, repeat=n)只需要1秒多。。。
  1. function combr(n, s, i) {
  2.     if (length(s)==n) {
  3.         print s
  4.         return
  5.     }
  6.     for (i=1;i<=length($0);i++) {
  7.         s = s substr($0, i, 1)
  8.         combr(n, s)
  9.         s = substr(s, 1, length(s) - 1)
  10.     }
  11. }
复制代码

TOP

试了一下官方的测试,powershell里调用函数的开销似乎格外大,所以暂时认为powershell不适合写递归吧。。。
要么4楼那样优化算法,要么用别的语言写递归
  1. $ranGen = New-Object System.Random
  2. $RepeatCount = 10000
  3. 'Wrapped in a function = {0}ms' -f (Measure-Command -Expression {
  4.     function Get-RandNum_Core {
  5.         param ($ranGen)
  6.         $ranGen.Next()
  7.     }
  8.     for ($i = 0; $i -lt $RepeatCount; $i++) {
  9.         $Null = Get-RandNum_Core $ranGen
  10.     }
  11. }).TotalMilliseconds
  12. 'For-loop in a function = {0}ms' -f (Measure-Command -Expression {
  13.     function Get-RandNum_All {
  14.         param ($ranGen)
  15.         for ($i = 0; $i -lt $RepeatCount; $i++) {
  16.             $Null = $ranGen.Next()
  17.         }
  18.     }
  19.     Get-RandNum_All $ranGen
  20. }).TotalMilliseconds
复制代码

TOP

返回列表