【问题标题】:Generating star pattern in LUA在 LUA 中生成星形图案
【发布时间】:2020-10-19 12:08:05
【问题描述】:

我是 LUA 编程新手。我无法在下面解决这个问题。

给定一个数字N生成一个星形图案,使得第一行有N 星,而在随后的行中星数减少1。

生成的模式应该有N 行。在每一行中,每五个星号 (*) 被一个哈希 (#) 替换。每行都应包含所需数量的星号 (*) 和井号 (#)。

Sample input and output, where the first line is the number of test cases

这是我尝试过的......而且我无法继续前进

function generatePattern()
  n = tonumber(io.read())
  i = n
  while(i >= 1)
  do
    j = 1
    while(j<=i)
    do
      if(j<=i)
      then 
          if(j%5 == 0)
          then 
             print("#");
          else
             print("*");
          end
        print(" ");
      end
      j = j+1;
    end
    print("\n");
    i = i-1;
  end
end

tc = tonumber(io.read())
for i=1,tc
do
   generatePattern()
end

【问题讨论】:

  • 欢迎来到 SO。输出或错误是什么?你被困在哪里了?
  • 我明白了,但是所有的星星都在换行符中一个接一个地打印出来。我想知道如何在同一行打印以获得上述模式

标签: lua


【解决方案1】:

首先,只是没有哈希的星星。这部分很简单:

local function pattern(n)
  for i=n,1,-1 do
    print(string.rep("*", i))
  end
end

要将每个第 5 个星号替换为一个哈希,您可以使用以下替换扩展表达式:

local function pattern(n)
  for i=n,1,-1 do
    print((string.rep("*", i):gsub("(%*%*%*%*)%*", "%1#")))
  end
end

模式中的星号需要用% 转义,因为* 在Lua 模式中具有特殊含义。

请注意,string.gsub 返回 2 个值,但可以通过添加一组额外的括号将它们截断为一个值,从而导致看起来有些尴尬的 print((..)) 形式。

【讨论】:

    【解决方案2】:

    根据 Lua 版本,元方法 __index 持有 rep 用于重复...

    --- Lua 5.3
    n=10
    asterisk='*'
    print(asterisk:rep(n))
    -- puts out: **********
    

    【讨论】:

      【解决方案3】:
      #! /usr/bin/env lua
      
      for n = arg[1],  1,  -1 do
          local char = ''
          while #char < n do
              if #char %5 == 4 then char = char ..'#'
              else char = char ..'*'
              end  --  mod 5
          end  --  #char
          print( char )
      end  --  arg[1]
      

      chmod +x asterisk.lua
      ./asterisk.lua 15

      【讨论】:

        【解决方案4】:

        请不要遵循这个答案,因为它是糟糕的编码风格!我会删除它,但不会让我这样做。查看评论和其他答案以获得更好的解决方案。


        我的 Lua 打印为每个打印输出添加换行符,因此我将字符串中的每个字符连接起来,然后打印连接的字符串。

        function generatePattern()
          n = tonumber(io.read())
          i = n    
          while(i >= 1)
              do
                ouput = ""
                j = 1
                while(j<=i)
                do
                      if(j%5 == 0)
                      then 
                         ouput=ouput .. "#";
                      else
                         ouput=ouput .. "*";
                      end
                  j = j+1;
                end
                print(ouput);
                i = i-1;
              end
        end
        

        此外,此代码只是您的最小转换,以提供正确的输出。有很多不同的方法可以解决这个任务,有些方法比其他方法更快或更直观。

        【讨论】:

        • 在循环中连接字符串在 Lua 中被认为是糟糕的风格,因为它的性能很差。尽可能使用table.concatstring.repstring.gsub。另外,避免使用全局变量。他们很糟糕。
        猜你喜欢
        • 2018-09-30
        • 2020-12-15
        • 2014-05-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-09-10
        • 1970-01-01
        相关资源
        最近更新 更多