打印所需数量的倒置星型图案

倒置星型图案包括给定行数的星号;每一行星号数量均减少一个,直到最后一行只剩一个星号;每五个星号更换为 # (参见图片):

****#*
****#
****
***
**
*

提示用户输入星型图案的数量,然后为每个图案输入其宽度,宽度与高度相同。然后输出所需尺寸的图案数。

点赞
用户6632736
用户6632736

直到“不使用变量作为限制”的部分得到澄清,它就是这样的:

-- 本地化需要多次调用的函数,以提高性能。
local floor = math.floor
local len, sub, rep = string.len, string.sub, string.rep
local insert, concat = table.insert, table.concat

local function pattern (size, template)
    -- 重复模板,直到覆盖所需大小并切除不需要的部分:
    local line = sub(rep(template, floor(size / len(template)) + 1), 1, size)
    local lines = {}
    while (len(line) > 0) do
        insert(lines, line)
        line = sub(line, 1, -2) -- 切除最后一个字符。
    end
    return concat(lines, '\n')
end

io.write('你想要几个倒置的星型图案?')
local no = tonumber(io.read()) or 0
local patterns = {}

for i = 1, no do
    io.write('第 ' .. tostring(i) .. ' 个图案有多少行?')
    patterns[i] = pattern(tonumber(io.read()) or 0, '****#')
end

print(concat(patterns, '\n'))

请注意,星形图案的行和它们本身的模式都存储为表,在完整后使用table.concat 进行连接,而不是在任何迭代中使用..添加字符串。这样做会更快,因为在 Lua 中,每次串联都会重新分配字符串。

这是pattern函数的另一种实现:

local function pattern(size, template)
    local length = len(template)
    local rows = {}
    for i = size, 1, -1 do
        -- 重复模板,直到覆盖 i 并切掉不需要的部分:
        insert(rows, sub(rep(template, floor(i / length) + 1), 1, i))
    end
    return concat(rows, '\n')
end

这是另一种实现,其中模式行被缓存,可能会加速程序:

local cache = {}
local function pattern(size, template)
    local length = len(template)
    local rows = {}
    for i = size, 1, -1 do
        -- 重复模板,直到覆盖 i 并切掉不需要的部分。
        -- 还进行缓存。
        cache[i] = cache[i] or sub(rep(template, floor(i / length) + 1), 1, i)
        insert(rows, cache[i])
    end
    return concat(rows, '\n')
end
2020-10-08 09:33:02