필터 지우기
필터 지우기

Debug of a very simple recursion problem

조회 수: 2 (최근 30일)
Meowooo
Meowooo 2017년 10월 21일
댓글: Walter Roberson 2017년 10월 21일
The idea of the problem is to reverse a character array using recursion.
1. Write a function called charReversal with the following function signature:
1 f u n c ti o n a r r a y 2 = c h a r R e v e r s al ( a r r a y 1 )
where array1 is the input character array, and array2 is the reversal of array1. For example, charReversal(’abcde’) should return ’edcba’.
My answer:
function array2 = charReversal(array1)
%arrary1 is the input character array
%arrary2 is the reversal of array1
if numel(array1)<2
array2 = array1;
else
array2 = reverse(array1);
end
Question: I don't know where to to put the base case, what the base case should be.
Thank you very much.

답변 (1개)

Walter Roberson
Walter Roberson 2017년 10월 21일
if numel(array1)<2
array2 = array1;
is already handling the base case. But the rest of your code needs to be developed to use recursion.
  댓글 수: 2
Meowooo
Meowooo 2017년 10월 21일
How could I add the recursion then? I thought it was in recursion already.
Walter Roberson
Walter Roberson 2017년 10월 21일
The function does not call itself, and does not call any function that calls the function, so No, it is not already recursive.
Hint:
What happens if you remove one character and reverse the rest, and then somehow combine the one removed character with what was returned from reversing the rest?

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Data Types에 대해 자세히 알아보기

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by