带有Ada递归的图钉(金字塔形)

问题描述 投票:1回答:1

我知道,通过提出我最精巧的工作来期望有人来救我,这正在推动社区的善意,但我简直别无选择,没有损失。在过去的几周中,我研究了数据包,文件,类型,标志和框,但是我没有涉及很多递归。特别是不使用递归绘制。我的考试大约需要一个星期,我希望这是足够的时间来重复和学习一些简单的递归技巧,例如画保龄球或其他图案:

I I I I I
 I I I I
  I I I
   I I
    I
n = 5

我的递归问题是我不太了解它。您应该如何使用递归来解决类似这样的问题?

我最近来的是

I I I
I I
I
n = 3

并且正在使用

with Ada.Text_IO; use Ada.Text_IO;
with Ada.Integer_Text_IO; use Ada.Integer_Text_IO;

procedure pyramidchaser is

   subtype X_Type is Integer range 0..30;
   X: X_Type;

   procedure Numbergrabber (X : out Integer) is
   begin

      Put("Enter a number: ");
      Get(X);
      Skip_Line;
   end Numbergrabber;


   procedure PrintSpaces(I, N: in Integer) is
   begin
      if I>=N then
     return;

      end if;

      Put(" ");

      PrintSpaces(I + 1, N);
   end Printspaces;




   procedure PrintPins(i, n: in Integer) is
   begin
      if i >= n then 
     return;
      end if;

    Put('I');
    Put(' '); 

    PrintPins(i + 1, n);
    end Printpins;




   function Pins (X : in Integer) return Integer is

      Printed : Integer;

   begin

      Printed:= 0;
      if X > 0 then
     PrintPins(0, X);
     PrintSpaces(0, X);
     New_Line; 

     Printed := X + Pins(X-1);
      end if;
      return Printed;

   end Pins;

   Bowlingpins : Integer;

begin

   Numbergrabber(X);
   Bowlingpins:= Pins(X);

end pyramidchaser;


但是我投入了一笔总和,我真的不需要仅仅开始递归部分,除了似乎需要在那里,我真的不知道为什么要这样做。我尝试了完全不同的任务中的代码,这就是为什么它看起来像它那样。我知道mod 2会给我太多新行,但这至少是找到金字塔高度的一种方法。我了解真正的方法与N + 1类似,因为在不断发展的金字塔的每一步中都需要新的生产线,但我不知道如何实现。

我不希望有人提供完整的代码,但我希望有人可以在寻找解决方案的方式上为我提供[[如何思考的线索。

我仍然可以通过考试而不将递归作为其通常的2个作业,其中一个是递归,一个不是递归,但您需要通过其中一项,但是鉴于我有一段时间,我认为Id给了机会。

一如既往,非常感谢任何打架的人!

recursion drawing pyramid ada
1个回答
1
投票
我不使用Ada编程(对我来说似乎很奇怪,帕斯卡,但您的Pins函数中存在明显的算法问题。

[基本上,如果要打印一个底数为N的金字塔,直到底数为1的最底部,则需要执行类似的操作(对代码进行粗略的Pascalization表示抱歉)。

procedure PrintPins(i, n: Integer) begin if i >= n then return; Ada.Text_IO.Put('I'); // Print pin Ada.Text_IO.Put(' '); // Print space PrintPins(i + 1, n); // Next iteration end; function Pins(x, indent: Integer): Integer printed: Integer; begin printed := 0; if x > 0 then PrintSpaces(indent); // Print indentation pretty much using the same artificial approach as by printing pins PrintPins(0, x); (*Print new line here*) (*Now go down the next level and print another row*) printed := x + Pins(x - 1, indent + 1); end; return printed; end

P.S。您不需要特定的功能即可在此处计算打印的针数。它只是范围1..N的高斯序列和,由N(N + 1)/ 2给出
© www.soinside.com 2019 - 2024. All rights reserved.