c_cpp 以递归方式做河内塔问题的基准.n = 20来自维基百科的伪代码:https://zh.wikipedia.org/wiki/汉诺塔

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了c_cpp 以递归方式做河内塔问题的基准.n = 20来自维基百科的伪代码:https://zh.wikipedia.org/wiki/汉诺塔相关的知识,希望对你有一定的参考价值。

#!/usr/bin/env ruby
# Usage: ./xtime.rb commands
def mem(pid); `ps p #{pid} -o rss`.split.last.to_i; end
t = Time.now
pid = Process.spawn(*ARGV.to_a)
mm = 0

Thread.new do
  mm = mem(pid)
  while true
    sleep 0.3
    m = mem(pid)
    mm = m if m > mm
  end
end

Process.waitall
STDERR.puts "%.2fs, %.1fMb" % [Time.now - t, mm / 1024.0]
# ruby 2.2.1p85 (2015-02-26 revision 49769) [x86_64-linux]
# 6.52s, 7.0Mb
def hannoi(n, from, buffer, to)
        if (n == 1)
                puts "Move disk #{n} from #{from} to #{to}"
        else
                hannoi(n-1, from, to, buffer)
                puts "Move disk #{n} from #{from} to #{to}"
                hannoi(n-1, buffer, from, to)
        end
end

hannoi(20, 'A', 'B', 'C')
// go version go1.2.1 linux/amd64
// 3.73s, 0.7Mb
// notice that this program takes two cores of CPU to excute
package main

import "fmt"

func hannoi(n int, from rune, buffer rune, to rune) {
        if n == 1 {
                fmt.Printf("Move disk %d from %c to %c\n", n, from, to)
        } else {
                hannoi(n-1, from, to, buffer)
                fmt.Printf("Move disk %d from %c to %c\n", n, from, to)
                hannoi(n-1, buffer, from, to)
        }
}

func main() {
        hannoi(20, 'A', 'B', 'C')
}

# Crystal 0.9.1 [b3b1223] (Fri Oct 30 03:48:35 UTC 2015)
# 4.70s, 1.3Mb
def hannoi(n, from, buffer, to)
        if (n == 1)
                puts "Move disk #{n} from #{from} to #{to}"
        else
                hannoi(n-1, from, to, buffer)
                puts "Move disk #{n} from #{from} to #{to}"
                hannoi(n-1, buffer, from, to)
        end
end

hannoi(20, 'A', 'B', 'C')
/* Compile with: clang++ -Ofast */
/* Ubuntu clang version 3.4-1ubuntu3 (tags/RELEASE_34/final) (based on LLVM 3.4) */
/* 5.70s, 1.0Mb */
#include <iostream>
#include <cstdio>
using namespace std;

void hannoi (int n, char from, char buffer, char to)
{
        if (n == 1)
        {
                cout << "Move disk " << n << " from " << from << " to " << to << endl;
        }
        else
        {
                hannoi (n-1, from, to, buffer);
                cout << "Move disk " << n << " from " << from << " to " << to << endl;
                hannoi (n-1, buffer, from, to);
        }
}

int main()
{
        hannoi (20, 'A', 'B', 'C');
        return 0;
}

以上是关于c_cpp 以递归方式做河内塔问题的基准.n = 20来自维基百科的伪代码:https://zh.wikipedia.org/wiki/汉诺塔的主要内容,如果未能解决你的问题,请参考以下文章

python 数据结构 递归经典实例 汉诺塔(河内之塔)

c_cpp 河内塔

河内塔与 K 钉

河内的线性塔

河内塔 C++(使用递归)

河内塔 - 如何不跳过每次递归的挂钩