我决定尝试在Lua中重新创建一个排序算法,只是为了好玩。它适用于某些值,但是在具有重复数字的较大值中,它不能正常工作。我想知道为什么会这样。
这里是代码(我添加了评论以便于查看):
numbers = "9876554321" -- Number to sort, I will refer to this as the "string to sort"
length = tonumber(string.len(numbers)) -- The length of the string to sort
changes = 1 -- The next few lines are just variables
totalchanges = 0
iterations = 0
newNumbers = numbers
print("")
while changes ~= 0 do -- This repeats until the number of changes equals zero
iterations = iterations + 1 -- This variable doesn't do anything for the code, it's only used at the end
changes = 0
print(newNumbers)
x = 1 -- More variables
y = 0
z = 0
w = false
while x < length do -- While the x variable is less than the length of the string to sort, repeat this code
y = tonumber(string.sub(newNumbers, x, x)) -- The 'x'th place in the string
z = tonumber(string.sub(newNumbers, x + 1, x + 1)) -- The 'x + 1'th place in the string
w = y > z -- If the 'x'th place is larger than the 'x + 1'th place, this value is set to true
print(y) -- Print statements
print(z)
print(w)
if w == true then -- Checks if y > z is true
newNumbers = string.gsub(newNumbers, tostring(z), tostring(y), 1) -- The next two lines swap around the numbers if y > z
newNumbers = string.gsub(newNumbers, tostring(y), tostring(z), 1)
changes = changes + 1 -- Increases the number of changes
end
print("")
x = x + 1 -- Increases the x value, this lets the code know where to check in the string
end
totalchanges = totalchanges + changes -- This variable is like the iterations variable, it's only used for the last print statements
end
print("") -- These last print statements are just showing information about the sort
print("Sorting complete!")
print("Original string: " .. tostring(numbers))
print("Sorted string: " .. tostring(newNumbers))
print("Total changes made: " .. tostring(totalchanges))
print("Total iterations used: " .. tostring(iterations))
有谁知道问题是什么?
答案 0 :(得分:0)
newNumbers = string.gsub(newNumbers, tostring(z), tostring(y), 1)
newNumbers = string.gsub(newNumbers, tostring(y), tostring(z), 1)
这两行在很多层面都是错误的。
我们只从其中一个开始:假设z == 5
,并在您的示例代码中有5
个,每个 {{序列中的1}}将变为5
,而不仅仅是您尝试交换的那个。
接下来是一个更明显的问题,即您首先将所有y
转换为z
s,然后将所有y
转换为y
s。这里的问题是你也变成z
你刚刚变成z
的{{1}},所以基本上
y
和不
y
即使情况并非如此,也不要将字符串用于那种东西。 Lua中的字符串与通常的字符串有点不同 1 。将字符串转换成序列,用它做一些事情,最后将它连接成一个字符串,你会好得多。
另请注意,您可以直接比较两个字符,Lua会按字典顺序对它们进行比较,因此无需aaaayzaa -> aaaayyaa -> aaaazzaa
所有内容。 aaaayzaa -> aaaazyaa
就像tostring()
一样。
1 Lua Performance Tips by Roberto Ierusalimschy, page 22 "About Strings"