Showing posts with label C. Show all posts
Showing posts with label C. Show all posts

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.