Prev: solar module simulation
Next: Results not repeatable for sum() function on fixed / deterministic vector
From: Nick Garoufalis on 5 Apr 2010 16:58 I need to check whether a word is a palindrome or not using recursion. this is what i have so far: function result = isPalindrome(string) size = length(string); if length(string) == 1 || isempty(string) result = 'true'; elseif string(1) == string(size) string(1) = []; string(size-1) = []; result = isPalindrom(string); else result = 'false'; end end it gets caught up at the recursion part where i plug the string back in. Thanks for the help
From: Steven Lord on 5 Apr 2010 17:56
"Nick Garoufalis" <Nickg5859(a)gmail.com> wrote in message news:hpdiss$7b5$1(a)fred.mathworks.com... >I need to check whether a word is a palindrome or not using recursion. this >is what i have so far: > > function result = isPalindrome(string) > > size = length(string); There's no need to shadow the SIZE function with a variable like this. > if length(string) == 1 || isempty(string) I would use ISSCALAR here instead of checking LENGTH, personally. > result = 'true'; Do you mean to return a string here, or do you want to return a logical value? If the latter, use: result = true; > elseif string(1) == string(size) Use END to refer to the last element of the string: elseif string(1) == string(end) > string(1) = []; > string(size-1) = []; > result = isPalindrom(string); You don't need to delete the elements from string; just pass in a substring. result = isPalindrome(string(2:end-1)); [Exercise: prove that string(2:end-1)) will not error.] I also assume the "isPalindrom" was a typo in your newsgroup posting, not in the actual code? > else > result = 'false'; Same comment as above -- result = false; > end > end > > it gets caught up at the recursion part where i plug the string back in. > Thanks for the help If the comments above don't resolve the problem, you should clarify what you mean by "it gets caught up". -- Steve Lord slord(a)mathworks.com comp.soft-sys.matlab (CSSM) FAQ: http://matlabwiki.mathworks.com/MATLAB_FAQ |