Идея рекурсии состоит в том, чтобы использовать функцию для разбиения задачи на все более мелкие фрагменты до тех пор, пока эти фрагменты больше нельзя будет разделить.
В приведенном выше примере линейки вы можете думать об этом так...
Наименьший фрагмент будет наименьшим делением на линейке. В вашем случае это 1/16 дюйма. Затем вам нужно рекурсивно вызывать свою функцию, пока она не разделит линейку на куски размером 1/16 дюйма. Как только параметр длины в вызове drawRuler() равен 1/16 дюйма, проблема становится простой. Вам просто нужно нарисовать отметку правильной длины. Вы делаете это, решая, как нарисовать отметку на основе параметра длины в вызове вашей функции. Если длина равна 1/16, вы рисуете деление 1/16. Если длина составляет 1/2 дюйма, вы рисуете отметку в 1/2 дюйма и т. д.
Стек вызовов будет выглядеть примерно так...
drawRuler(0, 0, 10, 1) // draw a ruler at 0,0 with a length of 10 and a width of 1
drawRuler(0, 0, 5, 1) // draw the first half of the 10" ruler starting at 0
drawRuler(2.5, 0, 2.5, 1) // draw the first half of the 5" ruler starting at 0
// keep dividing the ruler until you reach the 1/16 size
// once you reach the one sixteenth size, draw the correct size tick mark for passed in length
drawRuler(2.5, 0, 2.5, 1) // draw the second half of the 5" ruler starting at 2.5
// same as above
drawRuler(5, 0, 5, 1) // draw the second half of the 10" ruler starting at 10
// same as above
Функция будет выглядеть примерно так...
drawRuler(x, y, length, width)
{
if (length > 1/16) then
drawRuler(x, y, length / 2, width) // draw the left side
drawRuler(x + (width * 1/2), y, length / 2, width) // draw the right side
end if;
// draw the tick mark here using Turtle Graphics. The length of the tick mark
// is based on the length parameter pass into the function.
// For example,
// if the length is 10 or any even inch mark the length would be very long
// if the length is 5.5 or any 1/2 inch value the length would be long
// if the length is 2.25 or any 1/4 inch value the length would be medium
// if the length is 0.125 or any 1/8 inch value the length would be medium-short
// if the length is 0.0625 or any 1/16 inch value then the length would be short
}
person
Jeremy Whitcher
schedule
26.10.2014