# How to make random music over a set scale!

So to begin this involves some minor music theory. In my program I chose to work with a D major scale.

Between any two of the same notes of different octaves(including the notes themselves), D and D for example, there are 13 half steps. (b = flat, and # = sharp) This can be shown as such:
D, D#, E, F, F#, G, G#, B, B#, A, C, C#, D
0,,,1,,,,2,,,3,,4, ,,5,,,,6,,,7,,,8,,,,9,,10,11,,12

To find some scales you can simply look them up online, or use the one I'm showing here!
So a D major scale consists of the following notes: D, E, F#, G, A, B, C#, D
What this means is that we do not want any of the other half steps, 1, 3, 6, 8, or 10.
In my code I did this through the use of a long if statement:

if pitch = 1 or pitch = 3 or pitch = 6 or pitch = 8 or pitch = 10 [ set pitch (pitch + 1) ]

This if statement ensures that if a pitch that we don't want is selected, we simply move it to one we do want.

The way I got down to only 12 numbers involves a somewhat complex math function called mod. What mod does is give the remainder when two numbers are divided. For example:

11 mod 2 would give us a result of 1, because 2 can only go into 11, five times, and this leaves us with a remainder of 1.
2 * 5 = 10
11 - 10 = 1

8 mod 3 would give us a result of 2, because 3 can only go into 8, 2 times, and this leaves us with a remainder of 2.
3 * 2 = 6
8 - 6 = 2

Now the way that I used this is that I took the pxcor of the turtles and did mod 13. I chose 13 because our remainder can only be up to 1 less than the number we choose, and since we want numbers 0 - 12, we need to choose the number one bigger than 12. In Net Logo the code is fairly simple:

let pitch pxcor mod 13

Then once we have the pitch, we use the if statement from before to filter out unwanted pitches:

let pitch pxcor mod 13
if pitch = 1 or pitch = 3 or pitch = 6 or pitch = 8 or pitch = 10 [ set pitch (pitch + 1) ]

And then you simply need to add your instrument making the note into the code!

let pitch pxcor mod 13
if pitch = 1 or pitch = 3 or pitch = 6 or pitch = 8 or pitch = 10 [ set pitch (pitch + 1) ]
sound:play-note instrument (60 + (pitch)) (100 + pycor) (.2)

Hope this helps!

+5

This is great, thanks!