GoalCompare two algorithms that make the same music and say which one is better.
New words
compare · to look at two things and say what is the same and what is differentefficient · using fewer steps or less time to do the same jobphrase · a short group of notes that is played more than once
Explanation
Two different algorithms can make exactly the same music. The rain tune has a phrase of three notes: G, E and C. It is played four times. Algorithm 1 writes out all twelve notes, so it has 14 steps. Algorithm 2 writes the phrase once and uses a repeat, so it has only 6 steps. Both play the same sounds for the same time. Algorithm 2 is better, because it is shorter, easier to read and easier to change. To change a note you change one block instead of four. Choose the loop to match the job: use repeat for a set number of times and forever for music that goes on until stopped.
Step
Instruction
1
Start program when the sprite is clicked
2
Play note 67 (G) for 0.5 beats
3
Play note 64 (E) for 0.5 beats
4
Play note 60 (C) for 1 beat
5
Repeat steps 2 to 4 three more times
6
Stop program
Worked examples
This is Algorithm 2 as a Scratch program. The phrase is written once inside a repeat (4) block. All four rounds sound the same.
Algorithm 1: every note written
Algorithm 2: with repeat
Steps
14
6
Notes played
12
12
Time
8 seconds
8 seconds
To change the first note
change 4 blocks
change 1 block
Compare the two algorithms for the rain tune.
Job
Best loop
play a jingle exactly 3 times
repeat (3)
play background music until the game is closed
forever
play a drum until a key is pressed
repeat until
The best loop depends on the job.
Class activity
Shorten it (with a friend): write a rhythm of 12 beats on paper as 12 separate steps, for example: tap, tap, clap, tap, tap, clap, tap, tap, clap, tap, tap, clap. Count the steps. Now write the same rhythm using one repeat. Count the steps again. Perform both versions. Do they sound the same? Which one is easier to read? Which one would be easier to change?
Practice
1
A tune plays the notes A, B and C one after another and does this 3 times. How many steps does the algorithm have a) with every note written out, b) with a repeat? Count the start and stop steps.
a) 11 steps: start, 9 notes and stop. b) 6 steps: start, 3 notes, the repeat step and stop.
2
Do these two programs sound the same? Which one is shorter?
They sound the same: C, D, C, D. Program Q is shorter because it uses a repeat.
3
Which loop fits best? a) play a jingle exactly 5 times, b) play music in the background until the game ends.
a) repeat (5), b) forever.
4
This algorithm should play D and F exactly 3 times, but it plays them 4 times. Which step must change and how?
Step
Instruction
1
Start program when the sprite is clicked
2
Play note 62 (D) for 1 beat
3
Play note 65 (F) for 1 beat
4
Repeat steps 2 to 3 three more times
5
Stop program
Step 4 must say “repeat steps 2 to 3 two more times”. Then D and F are played 3 times in all.