(It is my first time doing recursive functions, so it may look a bit bad)
As title says, it isn’t working. I mean, it does but it prints things from arrays infinitely, can someone help me?
local word = {"kayak", "madam", "apple", "a"}
local function isPal(i)
for _,v in ipairs(word) do
for index = i, #word do
if string.sub(v, 1, 1) == string.sub(v, -1, -1) and string.len(v) >= 2 then
isPal(i + 1)
print(v)
end
end
end
end
isPal(1)
local words = { "hello", "world", "madam", "kayak", "A man, a plan, a canal – Panama", "Eva, can I see bees in a cave?" }
local function isPalindrome(word: string)
local word = string.lower(string.gsub(word, "[^%w+]", ""))
return not (not (string.reverse(word) == word))
end
for _, word in words do
print(`{word} is{if isPalindrome(word) then "" else " not"} a palindrome!`)
end
You’ve got a lot of problems in here. Why do you have so many for loops? Figure out why you need so many. If you’re iterating through recursion, you shouldn’t need any for loops.
I suspect he wants you to recurse over letter positions rather than over the list.
i.e. we recurse over kayak:
is first letter k equal to last letter k? If so, recurse on the input minus the first and last letter, aya.
is first letter a == last letter a? If so, recurse on the input minus the first and last letter, y.
The resulting length is 1, so just return true.
If all of these recursive steps return true, it’s a palindrome.
It’s not actually slow and, if used right, it’s not actually stupid.
Why are you looping through all the words in a recursive function? It will cause the function to go again through all the words again after it gets called by itself.
Why are you comparing only the first and last character not using the i in the string.sub?
local function isPalindrome(str)
if #str < 2 then
return true -- Less than 2 characters, so has to be true
elseif string.sub(str, 1, 1) == string.sub(str, -1, -1) then -- If front == last
return isPalindrome(string.sub(str, 2, -2)) -- Call with removed front and last
else
return false -- front and last characters are different
end
end
-- This function ignores everything that isn't in the alphabet (like punctuation)
-- It also lowers it all so it's not case sensitive
local function isPalindrome_lowered_lettersOnly(str)
return isPalindrome((string.gsub(string.lower(str), "[^abcdefghijklmnopqrstuvwxyz]", "")))
end
local tests = { "hello", "world", "madam", "kayak", "A man, a plan, a canal – Panama", "Eva, can I see bees in a cave?" }
for _, str in tests do
print(str, ":", isPalindrome_lowered_lettersOnly(str))
end
Iterative functions are way faster than recursive ones though
About looping, I have no idea why. I am not such a good guy to know that. It didn’t work, so I asked.
About second question, I compared only first and last letter, becasue on my first thought it looked like palindrome words have only first and last letter the same, but didnt’t think 2nd and 2nd from last must have the same letter too.