Hardware Reference
In-Depth Information
Using Algorithms
You don't always need to write brand new lines of code to add functionality to your
programs. You can use built-in algorithms instead, as in this code:
play_pattern [60,72,65,80].sort
This code is an example of a sorting algorithm you can use in Sonic Pi. When the pro-
gram is run, the algorithm will sort the numbers in the list into ascending order from
lowest to highest.
You can also use .reverse to reverse the numbers in a list and .shuffle to ran-
domly shuffle the numbers in a list as shown in the following code:
3.times do
if rand < 0.5
play_pattern [60,62,65]
else
play_pattern [60,62,65].reverse
end
sleep 1
end
In this code, shown in the Sonic Pi interface in Figure 7-11, .reverse has been used
inside a conditional, so that if the random value returned by rand is less than 0.5
then the notes 60, 62 and 65 will play in order. If any other value is returned then the
notes will be played in reverse.
An algorithm is a set of rules to be followed to calculate or solve a problem.
Common algorithms are those used for sorting information or data, as can be
seen by the sorting algorithm animations at www.sorting-algorithms.com .
Rather than writing a sequence of code to sort the MIDI notes that you used in a
list in Sonic Pi, for example, you could use an existing sorting algorithm, .sort .
Running Two Scripts at the Same Time
Electronic synthesized music usually has a repeating beat that you can nod your head
or dance along to, with a tuneful melody playing at the same time. This is similar to the
way pianists typically play with two hands on a piano. One hand plays one set of notes
of a song, usually in a lower octave, while the other hand plays a different set of notes.
Search WWH ::




Custom Search