Thursday, February 28, 2019

Something about pitches

Something About Pitches

CS50's problem set 3 was music-themed. The program played the pitches described in a .txt file. In that file a combination of letters (A-G) and numbers (2-5) was used to describe the frequencies in musical notes. But honestly I am not much of a music connoisseur. It goes not much beyond recognizing the latest songs that were played way to much on the radio lately. I don't know much of the concept "music".

So apparently, the very first step in learning anything about music is involves learning to recognize the relation between pitches. I found this app that plays some music for like 2 seconds and then plays a single pitch. The app insist it should be possible to recognize that single pitch after hearing the music for 2 seconds as "reference". In the very first level in this app, it only plays 4 pitches, C4 D4 E4 and F4.

First Attempt: Yeah, this is not going anywhere. Every single attempt of the twenty was a guess and I guess right 25% of the time. With only 4 options and no repeats, this is worse then random guessing actually, as that should be right 33% of the time. The music played in front of that one pitch doesn't seem to help very much 😖.

Second Attempt: Still not much pitch recognition going on here. But because their are only 4 pitches, there is quite some repetition among the pitches. I noticed three tings that made me able to perform slightly better than guessing:
  1. If it play pitch A, then pitch B, then pitch A again, it's sometimes possible to tell that it was played two pitches ago, therefore guessing correctly. 
  2. I became reasonably accurate this time around to guess whether pitch B was lower/higher then pitch A. So if pitchA was D4 and pitch B appears to be higher, I only had to guess between E4 and F4 and able to eliminate C4. 
  3. once three different pitches were played in a single session, when the fourth came I could usually tell that this one wasn't played before and was the missing fourth pitch. 

On my second attempt I had 55% right, basically I was able to eliminate one because it never repeated and on average one more because of the three tings I noticed. 😋

Next Few Attempts: The highest and lowest of the pitches, C4 and F4, were slightly easier the get right then those in middle. I avaraged somewhere between 50% and 80% most of the time now except for one lucky streak where I got 95% (😲). As time went on, C4 (which is called the tonic), came to stand out more and more. After about 10 games of twenty attempt, C4 became so distinct that I only got it wrong when I misclicked and after a few more I also stopped having false positives for C4.

As The Attempt Kept Going: After every attempt, the app plays a resolution. That is, it plays every note from the pitch I should have guessed down to the tonic. So if I had to guess D4, it plays D4-C4. If I had to guess F4, it plays F4-E4-D4-C4. So the D4-C4 was repeated almost every time (only when I had to say it's C4, it didn't), So after a while whenever the single pitch was D4, I almost heard a phantom noise of C4 right after, making it possible to identify it was indeed D4. When both C4 and D4 were (almost) guaranteed to be guessed right, scores below 65% didn't happen anymore and most were 80% correct or higher. 


Monday, February 25, 2019

CS50 - week 2 - Algorithms

CS50 - week 2 - Algorithms

lecture 3
lecture 3 is in week 2 and the lecture-week numbering is probably not going to match for quite a while. This lecture introduces some more information about strings. Which is an array of chars of length one character larger then the amount of chars (due to an ending "/0" char), which we must keep in mind.

Most of the rest of this lecture was on the topic of algorithms. More precisely: searching algorithms and sorting algorithms. Some properties about these were discussed, such as how long these take to perform as the the number to search/sort increases. In the very zeroth lecture (as they started at lecture 0), David introduces binary search(= go to middle of set you want to search, discard half then go to the middle of the remainder, sorted sets only.) and here he discusses it again and compares it to linear search (= just look at everything in order). Binary search is much faster then linear search, btw. (as David states, you effectively half your problem each step.)

Then in the discussing only sorting, he first talks about three equally efficient sorting methods. (bubble sort, insertion sort and selection sort). For each of these doubling the amount of stuff you sort, you quadruple the amount of time it takes. Then he introduces as fourth sorting method: merge sort, which is just weird, but quicker.

problem set 3

There is one problem set, split into three "helper functions". This problem set is removed now. I thought it was a nice introduction to code that was over multiple files. But it was easier then previous problems, taking less than 3 hours to complete.

Helper function 1: duration
All three functions were meant to read instruction to play music. The first function must get the duration of a certain note. notes are either 1/1, 1/2, 1/4 or 1/8. so turning their chars into ints and multiplying by 8 gave their relative duration.
int duration(string dur)
{
    if (!dur)
    {
        return 1;
    }

    int number = 8 * (dur[0] - 48) / (dur[2] - 48);
    {
        return number;
    }

}

Helper function 2: is rest
the second function determines whether a note was meant to be played at a specific time. this wasn't very difficult either.
bool is_rest(string s)
{
    if (!s)
    {
        return 1;
    }
    if (strcmp(s, "") == 0)
    {
        return true;
    }
    else
    {
        return false;
    }

}

Helper function 3: pitch
This was pretty much the meat of the exercise. turning A4 into 440hz or c4 into 256hz. So it was given that a4 was 440 hz. One ocatave higher meant doubling the pitch. Different notes were 2^1/12 apart and lastly, flat and sharp notes exist. Near the bottom I multiplied and later divided by 10000 because otherwise the floats would round in annoying ways.
int frequency(string notes)
{
    // error
    if (!notes)
    {
        return 1;
    }
    // check length
    bool three = false;
    if (strlen(notes) == 3)
    {
        three = true;
    }
    char note = notes[0];
    int ndis = 0; // for note A
    // determine the note

    switch (note)
    {
        case 'B':
            ndis = 2;
            break;
        case 'G':
            ndis = -2;
            break;
        case 'F':
            ndis = -4;
            break;
        case 'E':
            ndis = -5;
            break;
        case 'D':
            ndis = -7;
            break;
        case 'C':
            ndis = -9;
            break;
    }

    // determine octave location (place 2 or 3)
    int i = 0;
    if (three == true)
    {
        i = 1;
    }
    int octave = notes[1 + i] - 48;

    // correct for sharp or flat
    if (i == 1)
    {
        char fs = notes[1];
        if (fs == 'b')
        {
            ndis--;
        }
        else
        {
            ndis++;
        }
    }

    // output frequency
    float a = 440;

    float exp = 10000 * ndis / 12;

    float c = a * pow(2, exp / 10000) ;

    // correct for octave
    c = c * pow(2, octave - 4) ;

    int d = round(c);
    return d;

}

Thursday, February 21, 2019

CS50 - week 1, continued - some More C

CS50 - week 1, continued - Some more C

lecture 2
So, this is still week 1, apparently, despite it being lecture 2 and problem set 2. o well... This lecture starts with some simple loop examples that are easier versions of problem set 1's mario problems (,which is why I watched lecture 2 before doing problem set1, Which I kept doing. In hindsight this is only useful up to problem set 4). Some debugging help is shown here as well, like some commands programmed by the cs50 team, but honestly it never gave me any useful feedback and I always debugged by overloading on printf statements.

Afterwards the lecture goes a bit deeper in the basic data types in C: int, float, char, string (which actually doesn't exist), and so on. Some functions made by the cs50 team were also shown to get user input and it's also shown how strings are just a row of chars. The relation between int and char (ASCII) was also shown. The problem set involves toying with chars and strings in the form of cryptography

problem set 2

three problems this week:

Caeser.c (easy)
Make a program that, given a number and a word, replaces every letter in the word with another further in the alphabet by that number.
so ab and 2 gives cd
idiot and 3 gives lglrw
this wasn't too bad.

Viginere.c ("easy")
That caeser is the oldest known way to encrypt a message, by "rotating" all letters across the alphabet. Once you are aware of it, it is ofcourse easy to break, so a slightly upgraded encryption method was used later (still centuries ago). The Viginere rotates your to be encrypted message by another word (the cipher). It is just a slight upgrade from the Caeser method and I already got the code from that one, so how hard could this be? well, as the quotes around "easy" show, this was not easy. It took me 2 hours to do caeser and another 3 to upgrade it to the viginere method for a total of 5 hours.

Crypt.c (hard)

I admit, this was hard. So hard in fact that I skipped it for later as I was getting nowhere.

Monday, February 18, 2019

CS50 - week 1 - Intro to C

CS50 - week 1 - Intro to C

lecture 1
So, last week all the coding was in scratch. Which is a program made by MIT to visually represent code. It's also not that difficult to use (the latest version does seem to be difficult to embed, though). So in this lecture we (we as in, every student following this course) get introduced to the language of C. An old programming language designed in 1973 which is pretty much the opposite of scratch.

First the lecture shows a comparison between C and scratch, which makes C appear not to bad at first glance (, This isn't true at all at second, third... glance). It contains some nuisances such as a semicolon (";") after every line of text and the program throwing a fit if you don't. The basic loops and if/else conditionals get compared from scratch to C. Some background info on compilation was given (compilation, like I understand it, turns the lines of C text into 1's and 0's that the computer can read) and some more functions were shown. So, I still know next to nothing but the first C problem set shouldn't be that difficult, right?

problem set 1

So , the first problem set (the one from previous week counted as problem set 0) was rather manageable. There were 5 problems, only 3 were compulsory but I didn't feel the need to skip any as I feel practice is the best way to learn something. The problems are divided into two categories, for those less comfortable with coding (easier versions) and those more comfortable (harder versions).

Hello.C (easy version)
Have the program print 'Hello world!\n", as this was shown in the lecture, this was not difficult at all and only took 10 minutes. (I ofcourse forgot the semicolon so it threw an error, then I forgot the "\n" so it did not start a new line. Therefore, pretty much everything that could go wrong, did go wrong).

Hello, world\n

Mario.C (two versions, easier and harder)
the tl:dr pf problem set 1 said to listen to part of lecture 2, so I watched that in whole. Because an example was given during this lecture that was rather similar to these two tasks, the logic which should be typed out was immediately apparent to me (nested loops of # and spaces). So the major difficulty was wading through the 20 errors I got while making this. It only took 45 minutes 😌.
Then the harder version, which was only slightly more then the easy version. Also I could cannibalize the code of that version and only had to add one more loop in the nesting. I was a bit to "overzealous" in that I added spaces after # which weren't necessary (that is, it was wrong).

      n = 4

      #  # 
    ##  ##
  ###  ###
####  ####
The hard version separates the two pyramids of #, the easy version doesn't.

Cash.C ("easy")
Easy between quotes here, this wasn't that easy.
So, what was the task?
If I have an amount of cash, was is the least amount of coins of 0.01,0.05,0.1 and 0.02 required sum to that amount?
so if I would have 1.06 cash (of any valuta), the coins would be 5x0.2, 1x0.05 and 1x1.01 (I would need to have 7 coins minimum, I could also choose for 106 coins of 0.01, but thats unweildy).
The annoying problem here is that numbers that aren't integers in programming have the nasty habit of exhibiting rounding errors. Which can apperently be solved by multiplying and dividing by the amount of significant numbers. This problems was another hour.

Credit.C (hard)
So, given a number, tell me if it is one of the given credit cards or invalid. The requirements for the numbers are given : amount of numbers, the first number(s) as well as a stupid sum. The sum of every number plus every second number (so, these count twice) must be divisible by 10 (the last digit must be 0). This problem about as much time as the others here combined.

So the entire problem set was only 4 hours of work.

Thursday, February 14, 2019

CS50 - Intro to Computer Science - Week 0

cs50 - week 0 - scratch


"It's not the easiest way to learn it, but it is the best way"

On edx, you can follow this course for free. It has the recorded Harvard lectures and the same problems as the students of the Harvard University students.

lecture 0
A lot of the first lecture puts the emphasis on the fact that you don't need any programming experience. Apperently, even the lector , David Malan, didn't go to the University with the plan to study computer science. There's also some statistics about how the majority of students had no prior contact with programming and you should (logically) not compare yourself with others, but with where you started. Which is pretty good advice for everything you want to learn.

To start the course somewhat lighthearted, no coding takes place in the first lecture. Just a small bit on binary, a bit about how literal computers interpret commands and finnaly an introduction to Scratch. Scratch is a visual "coding" program designed by MIT meant for children but can be used as a way to introduce some concepts like loops and conditionals.


problem set 0

The first problem set is rather easy, just make anything you want in Scratch with a few requirements:
Your project must have at least two sprites, at least one of which must resemble something other than a cat.
Your project must have at least three scripts total (i.e., not necessarily three per sprite).
Your project must use at least one condition, one loop, and one variable.
Your project must use at least one sound.
Your project should be more complex than most of those demonstrated in lecture (many of which, though instructive, were quite short) but it can be less complex than Oscartime. As such, your project should probably use a few dozen puzzle pieces overall.
I made a poor imitation of flappy bird in about 2 hours.



(So... restarting this doesn't seem to work when not on the scratch site, so you should refresh the page for that. Also be wary of errors...)