Hi, sorry if this is trivial, but I am writing a function that gives directions on how to solve the Tower of Hanoi given d discs, and I can't quite seem to figure out how to produce a single 2D char array that contains all the instructions for solving the game on separate lines. The output I am looking for looks like this:
instruction =
'Move one disk from peg 1 to peg 2'
'Move one disk from peg 1 to peg 3'
'Move one disk from peg 2 to peg 3'
My code looks like this and produces the instructions on separate output statements only if I omit a semicolon at the end of the sprintf line:
function instruction = hanoi(d, origin, inter, target)
if d == 1
instruction = sprintf('Move one disk from peg %s to peg %s', origin, target)
else
hanoi(d-1, origin, target, inter);
hanoi(1, origin, inter, target);
hanoi(d-1, inter, origin, target);
end
end
My idea was to concatenate each line, but it doesn't seem possible without resetting what's contained in the variable instruction.
Thank you in advance.
EDIT for solution I ended up figuring out:
function instruction = hanoi(d, origin, inter, target)
if d == 1
instruction = sprintf('Move one disk from peg %s to peg %s', origin, target);
else
instruction = hanoi(d-1, origin, target, inter);
instruction = [instruction; hanoi(1, origin, inter, target)];
instruction = [instruction; hanoi(d-1, inter, origin, target)];
end
end
4 件のコメント
Stephen Cobeldick (view profile)
Direct link to this comment
https://ch.mathworks.com/matlabcentral/answers/490044-how-can-i-make-my-output-into-a-2d-char-array-instead-of-separate-answers#comment_774656
Rena Berman (view profile)
Direct link to this comment
https://ch.mathworks.com/matlabcentral/answers/490044-how-can-i-make-my-output-into-a-2d-char-array-instead-of-separate-answers#comment_777412
Rena Berman (view profile)
Direct link to this comment
https://ch.mathworks.com/matlabcentral/answers/490044-how-can-i-make-my-output-into-a-2d-char-array-instead-of-separate-answers#comment_777415
Rena Berman (view profile)
Direct link to this comment
https://ch.mathworks.com/matlabcentral/answers/490044-how-can-i-make-my-output-into-a-2d-char-array-instead-of-separate-answers#comment_777416
サインイン to comment.