Problem

Imagine a row of n lights that can be turned on or off only under certain conditions, as f...

Imagine a row of n lights that can be turned on or off only under certain conditions, as follows. The first light can be turned on or off anytime. Each of the other lights can be turned on or off only when the preceding light is on and all other lights before it are off. If all the lights are on initially, how can you turn them off? For three lights numbered 1 to 3, you can take the following steps, where 1 is a light that is on and 0 is a light that is off:

1 1 1

All on initially

0 1 1

Turn off light 1

0 1 0

Turn off light 3

1 1 0

Turn on light 1

1 0 0

Turn off light 2

0 0 0

Turn off light 1

You can solve this problem in general by using mutual recursion, as follows:

Algorithm turnOff(n)// Turns off n lights that are initially on.if (n == 1)Turn off light 1else{  if (n > 2)  turnOff(n - 2)  Turn off light n  if (n > 2)  turnOn(n - 2)  turnOff(n - 1)}Algorithm turnOn(n)// Turns on n lights that are initially off.if (n == 1)Turn on light 1else{  turnOn(n - 1)  if (n > 2)  turnOff(n - 2)  Turn on light n  if (n > 2)  turnOn(n - 2)}

a. Implement these algorithms in Java. Use the results in a program to display directions to turn off n lights that initially are on.


b. What recurrence relation expresses the number of times that lights are switched on or off during the course of solving this problem for n lights?

Step-by-Step Solution

Request Professional Solution

Request Solution!

We need at least 10 more requests to produce the solution.

0 / 10 have requested this problem solution

The more requests, the faster the answer.

Request! (Login Required)


All students who have requested the solution will be notified once they are available.
Add your Solution
Textbook Solutions and Answers Search
Solutions For Problems in Chapter 7
ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT