Friday, December 30, 2016

PSET3 Finished

The game of fifteen wasn't too bad once I understood what they were asking me to do.  I didn't really understand how the game worked untill I was able to play with a working version of the program.

They had the game pretty much coded except I had to come in and write 4 functions that would make the game playable.

Initialize the board
Draw the game board
Write a move function
Write a won function.

Initialize
void init(void)
{
    //total numbers needed
    int total = d * d;
   
     //draws the board top left to right and reduce by 1
    for (int i = 0; i < d; i++)
    {
        for (int j = 0; j < d; j++)
        {
         
            board[i][j] = --total;
        }
    }
   
    // If board has even columns swap 1 % 2
    if ( d % 2 == 0)
    {
        board[d-1][d-3] = 1;
        board[d-1][d-2] = 2;
       
    }
 }
Comments
This function creates an array of numbers, and swaps the last 2 numbers if their are even columns.


Draw
void draw(void)
{
    for (int i = 0; i < d; i++)
    {
        for (int j = 0; j < d; j++)
        {  
            //initalizes _ to value of 0. if value is 0 draw an underscore
            if (board[i][j] == 0 )
            {
             printf("  _");  
            }
            else
            {
            printf("%3i",board[i][j]);
            }
        }
        printf("\n");
    }
}

Comments
This function "draws" the board. i designates rows, j designates columns.
When the array reaches 0 it instead draws an underscore.


Move 

bool move(int tile)
{
    // TODO
 
    for( int i = 0; i < d ; i++)
    {
        for (int j = 0; j < d; j++)
        {
            //searches for where user input is
            if( board[i][j] == tile)
            {
                //checks north tile and swaps4
                if((i - 1 >= 0) && (board[i - 1][j] == 0 ))  //if value above =input
                {
                   
                    board[i-1][j] = board[i][j];
                    board[i][j] = 0;
                    return true;  
                }
                //checks right of tile
                else if((j + 1 < d) && (board[i][j + 1] == 0))
                {
                    board[i][j+1] = board[i][j];
                    board[i][j] = 0;
                    return true;
                }
                //checks south of tile
                else if ((i + 1 < d) && (board[i + 1][j] == 0 ))
                {
                   
                    board[i+1][j] = board[i][j];
                    board[i][j] = 0;
                    return true;
                }
                //checks left of tile
                else if ((j - 1 >= 0) && (board[i][j - 1] == 0))
                {
                    board[i][j-1] = board[i][j];
                    board[i][j] = 0;
                    return true;
                }
               
            }
        }
   
   }
   return false;
 
}

Comments
This one took me some time to do. For the longest time I couldn't understand why my board was drawing an extra 0 on only some moves. Then I realized I wasn't error checking on if the move was in the confines of the virtual board.

Won Function
bool won(void)
{
    int counter = 0;
   
   
    //checks each tile to see if it's in order
    for( int i = 0; i < d ; i++)
    {
       
        for (int j = 0 ; j < d ; j++)
        {
            //checks last spot and if not correct value
            if (++counter != (d*d) && board[i][j] != counter)
            {
                return false;
            }
        }
    }
    return true;
   
}
Won Function Comments
This function checks to see if the board is in the correct order. If the board is in correct order it returns true, and stops the program.

PSET 3 Comments
It was overwhelming at first seeing all the lines of code already written. However this problem gave me a great view on how everything fits together. Try not to think of everything all at once and break the problem down...easier said than done.

Coding
I't is still not clicking for me on breaking everything down. I wouldn't be able to write this program from scratch. I feel like it should take me way less time to break everything down. All the advice I've gotten is to keep plugging away, eventually it will just snap in.

Apparently the difficulty for the next PSET is pretty tough. It starts introducing concepts about changing variables located in memory.  PSET4 looks very exciting, being able to code my own file recovery software, and learn how data is stored in a jpeg, or bitmap file. However that may change in the new year when the course changes.

 I've started with the videos learning the next bit of material because I'm sure most of it will still be relevant, however I am  going to take a small break and wait until the course material is updated.

Progress
Their are 9 problem sets and a final project. I've completed 4 of the  PSETS(0,1,2,3)

I started the last week in November so It's taken me 5 weeks to complete 4 psets with working 40 hours a week. I'm pretty proud of that so far. I am fairly certain that as more concepts are introduced It will take me more time to go through.  More than anything though I'm hoping for the point where coding just clicks..

I am  starting to loose a little bit of motivation. That is normal for me at this point. I always tend to get bored quick. This break will hopefully me a good refresh.



Sunday, December 18, 2016

PSET 3 Update 2

This weekend was difficult to find time to code, however I managed to solve the first problem of PSET3.

Sort and Search
Implementing a sort and search algorithm.

This wasn't quite difficult but when I write code that I've never done it before my brain isn't quite sure which way to go about doing it. This problem set involved using someone elses code, and then adding to it.  Through this example I can begin to see how a program can be broken up to work within a team of people.

Once I see an example snippet, I kinda go ah, that is how you do it, and then begin to implement it in my own way, and it wasn't difficult to see how to code the search and sort functions.

Sort
I wrote a selection sort algorithm for this problem.

The code is relatively simple. You use 1 loop to iterate through the array of numbers. It essentially keeps track of the first unsorted number.

The second loop basically scans the rest of the array for the remaining smallest number and then swaps in that number.

The first loop iterates to the 2nd number, then finds the next smallest, swaps, and so forth until it reaches the end of the array, and that means the array will then be sorted from smallest to largest.
----------------

void sort(int values[], int n)
{
 
    // TODO: implement an O(n^2) sorting algorithm
    for (int i=0; i < n-1 ; i++)
    {
        int min = i;
     
        //finds index value of min
        for (int j = i+1; j < n ; j++)
        {
            //finds lowest number between 2 integers
            if (values[j] < values[min])
            {
                min = j;
            }
         
            //swaps array integers
            if (min != i)
            {
            int high = values[i];
            values[i] = values[min];
            values[min] = high;
         
            }
        }
     
    }
    return ;
}


Search
I learned a lot of about algorithms and the  scaleability time they take to function during PSET 3.

searching an array of 5 numbers [2,6,8,13,15]  it's easy to search 1 by 1. However if the array was 13 trillion numbers, this would take forevor.  A better approach would be to continually split the problem in half until the number is found.

This does require the array to be sorted first. This approach won't work unless the list is sorted.

bool search(int value, int values[], int n)
{
 
   //find start, end and middle of the value array
   int start = 0;
   int end = n-1;
 
   //searches for needle using binary search
   while (start <= end )
   {
     
        int middle = (start+end) / 2;
        if (value == values[middle] )
        {
            return true;
        }
        else if ( value > values[middle])
        {
           start = middle + 1;
        }
        else if ( value < values[middle])
        {
              end = middle-1;    
        }
     
        else
        break;
    }
 
    return false;
 
}


The Game of Fifteen
I'll have 13 days to complete this before the PSETS's change in the new year. It looks like it may involve swapping multidimensional arrays which will be similar"ish" to the sort function. 


I'll probably start the problem today and try to write down some pseudocode. The example files have 200 lines of code, and this will be the largest program i have worked with to date, and feels a little intimidating at first.

Edit:
This may be difficult. The basic game structure is given, I just have to code some functions to make the game work. I't's difficult to visualize, as I don't understand how the code fits together, or how the game works.

Saturday, December 17, 2016

PSET 3

Progress
This week I've found it really tough to find some time. Not only do I have Christmas parties Thursday and Saturday, but I also had food poisoning friday, blah not fun.


PSET 3 Problem #1
The first pset problem is already written, but  I need to edit functions that is written in a different file and linked to the main program.  

The program has a "sort" and "search" function.

I understand the basic framework for a selection sort

2 loops that iterative over the array.
the second loops will find the smallest number and then replace that number into the first loops position...

 I'm just a little fuzzy on how to swap the numbers in an array but I think I have a good idea of where to start. Using a placeholder to hold a value, and then I can do the swap that way.

2nd Part
The Search function they are calling for binary search.


Game of Fifteen 
This looks like it may be challenging. I took a brief look at the second problem, and it looks like it involves a multidimensional array. It looks like it might take some effort to do.


Loops & Arrays
The last 2 PSETS have hammered home the use of loops. This  pset  also uses loops, but has thrown in arrays and basic use of functions.  I really enjoy how this course is linking everything together. Loops for a beginners are kind of tricky in applying them to problems, but I feel that for every problem I do, I gain a lot of knowledge in how to apply them to a problem.

Not only am i learning how to code, but I'm also learning a bit more on the history of programming languages, and how things work under the hood.

Sunday, December 11, 2016

Finished PSET 2 (Encryption)

Rewarding Experience
Well that felt rewarding. I got stuck a few times, got a little frustrated but persevered.
PSET2 to recap I had to make 3 programs using the C programming Language.

initials.c
caesar.c
vigenere.c

Initials.c
This code prompts a user for his/her name, and then prints out the initials.


#include <stdio.h>
#include <cs50.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>

int main(void)
{
   
    //asks for name
    string GetName =  GetString();

    //Prints First Initial
    printf("%c", toupper(GetName[0]));

    //Finds whitespace and prints next letter
    for (int i=0, n = strlen(GetName); i <n; i++)
    {
        if (GetName[i] == ' ')
        printf("%c", toupper(GetName[i+1]))   ;  
    }

 printf("\n");
 //return 0;

}


Summary
I had troubles trying to figure out how to find the first character of each name. After many attempts I had a light-bulb go off, printing the first character after a space.   So my code finds the whitespace, then prints out the next letter. Looking back at how long it took my I feel a little dumb, but I think that is a good thing as that means I have learned a lot!


Caesar Cipher
This program runs with a command line argument. The argument has to be an integer. If an integer is not ran when executing the program, it will return an error message and fail.

Key = 7
Example: If I execute: ./caesar 7
This program enciphers text using the Caesar Cipher.

It Spits out
Aopz wyvnyht lujpwolyz alea bzpun aol Jhlzhy Jpwoly

Here is my code.

#include <stdio.h>
#include <cs50.h>
#include <string.h>
#include <ctype.h>
#include <stdlib.h>

int main (int argc, string argv[])
{
    //error checks 1 command line argument
    if (argc != 2)
    {
        printf ("Enter 1 Command Line Integer");
        return 1;
    }
   
    //converts string number into an integer
    int k = atoi(argv[1]);
   
    //grabs a string from the user
    string UserInput = GetString();  
   
    //This will itereate through each character in user input  
    for (int i = 0, n = strlen(UserInput); i < n; i++)    
    {
        int c = 0;
       
        //IF input is a letter  
        if (isalpha(UserInput[i]))    
        {
            //IF input is UpperCase
            if (isupper(UserInput[i]))    
            {
                c = (((int)UserInput[i] - 65 + k) % 26) + 65;    //calculates integer value of upper character and adds caser cipher key
                printf("%c",(char) c);  
            }  
           
            //If string Input is lowerCase  
            if (islower(UserInput[i]))    //If is a letter and lowercase
            {
                c = (((int)UserInput[i] - 97  + k) % 26) + 97;   //calculates integer value of lowercase character and adds caser cipher key
                printf("%c",(char) c );  
            }
               
        }
       
        else
        {
            //prints a space if space in string
            printf("%c", UserInput[i]);
        }  
    }
           
    printf("\n");
    return 0;

}

Summary
I struggled with this quite mightily. I ended up quitting, then coming back to it the next day, and spending probably 9-10 hours on it. I knew I needed to iterate over the string, but after  I was overwhelmed at the next step. When I attempted the next step I wasn't sure if i was doing it right.

I ended up creating and deleting my code multiple times.I found out that I don't break down the problems very well. I was overwhelmed trying to figure how upper/lower case figures out with the algorithm to solve.

This is what I should have done from the start.

  • Really grasp how the modulo works first.   
    • ex  1 % 3 = 1  why?
      • well 1 can't divide into 3, so 1 is the remainder
    • likewise 2 % 3 = 2
  • When figuring out the formula, forget everything else and write down an examples
    • lower case a Key of 7 = h
    • lower case a Key of  33 = h
      • ascii a = 97
      • ascii h = 104
    • you can see you only need to apply modulo to the Key and not the ascii value. That is where I spent a lot of time banging my head against a wall, and the corresponding "duh" moment when I re-visited how modulo works.
Again looking back I feel a bit embarrassed I took so long to solve this. Here I learned a lot about how to convert and add letters to ints, and visa versa. more importantly I think I made a tiny step forward in learning how to break problems down more efficiently.

Vigenere
Instead of a key like Caesar, vigenere takes a keyword. 

This program takes a keyword as a user argument. It then waits for a user to enter a string of text. This program then enciphers the text with vigenere 


#include <stdio.h>
#include <cs50.h>
#include <string.h>
#include <ctype.h>
#include <stdlib.h>

int main (int argc, string argv[])
{
    //if their are less than 1 argument return an error and prompt user to try again   
    if (argc != 2)
    {
        printf ("Enter 1 Command Line Integer\n");
        return 1;
    }
    
    string key = argv[1];
    int keyLength = strlen(key) ;
    
    //Iterate through argv and check to ensure everything is an alphabet character
    for (int i = 0, n = strlen(key); i < n; i++) 
    {
        
        if (!isalpha(key[i]))
        {
            printf("You have a number in your key, Try again\n");
            return 1;
        }
    }    
    
    //Grabs a string to be ciphered    
    string UserInput = GetString();    
     
    
    //i  tracks string position, j tracks keyLength position
     //This will itereate through each character in user input string
    for (int i = 0, j = 0,  n = strlen(UserInput); i < n; i++)     
    {
        int cipherLetter = 0;
        int shift = 0;
        
        //this checks for alphabet characters     
        if (isalpha(UserInput[i]))
        {     
                  
            //finds shift if letter is uppercase
            if (isupper(UserInput[i]))
            {
                //calculates lowercase shift value
                shift = (int)toupper(key[j]) - 65;
                    
                //adds shift value to letter value and wraps around alphabet
                cipherLetter =  (((int)UserInput[i] - 65 + shift) % 26) + 65;
                
                //prints coresponding enciphered letter
                printf("%c", (char)(cipherLetter));
                j++;
            }
                
            //finds key shift if letter is lowercase
            if (islower(UserInput[i]))
            {
               //calculates lwoercase shift value
                shift = (int)tolower(key[j]) - 97;
                    
                //adds shift value to letter value and wraps around alphabet
                cipherLetter =  (((int)UserInput[i] - 97 + shift) % 26) + 97;
                
                //prints coresponding enciphered letter
                printf("%c", (char)(cipherLetter) );
                     
               j++;
            }
            
        }   
            
            else
            {
            printf("%c", UserInput[i]);
            }
            
            //wraps key back to first position
            if (j >= keyLength)
            {
                j = 0;
            }
            
    }
    printf("\n");
}    

Summary:
This didn't take me as long as Caesar did. probably 5 hours. Still longer than I would like to admit. I did get a bit overwhelmed again and looked for help. I had an aha moment when I saw a loop with 2 counter variables being initialized in the condition. I didn't realize that was an option.

I took a small break, stepped back and tried to go through this step by step. I ended up building some test code as I went. I experimented with print f everytime I wrote a line of code to test my integer and character math. I think going forward I will continue to do this if I can as it will help me to break the problems down and not become overwhelmed at the big picture.

I felt I cemented my knowledge of modulo as well as learned how to keep track of 2 changing variables for a loop.

It feels very rewarding to finish this. I am probably going to spend some time watching the RSA encryption video again, as well as week 3's videos.

ProblemSet3
Week 3 has a total of 3.5 hours of video to not only watch, but understand.  I found in the past I usually watch some videos more than once to understand a concept. Most people who have done the course say Pset3 is a slight notch more difficult, but far from the most difficult pset.


The problem sets will be changed at the end of the year. So I essentially have until the end of the year to complete a problem set. Knowing that their is only 2 weeks left in the year, with one of those being Christmas and multiple Christmas parties. I will only attempt one more pset before they change. It might be a tight fit, especially since my freetime after this weekend will be at a premium. 

Hopefully I can get a few hours at work I can escape to learn.

Saturday, December 10, 2016

Pset2 Caesar Cipher

Concentration is back
It is amazing what a break does to your concentration.

Saturday morning I re-attempted problem 2 and re-watched the walk through video and almost immediately discovered my incorrect thinking  from my code and what I needed to change.

Problem 2
Problem 2 is about having a user inputting a sentence or string, and then encoding it with the caesar cipher, and spitting it back out. The Ceasar Cipher is relatively simple. Take below as an example

Ceasar Cipher
"The elephant"   Key of 2

This means that every letter in the alphabet shifts by the Key, so 2 characters.
So "The elephant" becomes Vjg gngrjcpv

The hard part in coding is that a "z" character with a key of 1 wraps around to an "a"

I understand the next steps on what I need to do now, and I'm working on how to translate alphabet into integers and vica versa according to the ascii guide.

Finished
The code above led me down the path, but I ran into another problem getting the algorithm right, as well as my order of operations inside the algorithm. I'm going to need a refresher on this.

I initially needed help figuring out the algorithm, I peaked at forums that offered help to similar issues, and it was another "duh" moment. I had initially thought of something really similar but scrapped it and went down another route.

Realizations
I really want to finish this course. but more importantly I want to 100% understand everything I do, and not try to finish it without understanding  because that negates the whole purpose of me taking this course.

I got frustrated because I was overwhelmed about how to solve the algorithm and printing out the corresponding caeser cipher letter

  I felt I did well on the first 2 problem sets and on PSET2 I took a long time to finish the first and second problems and needed help while doing so.

I think my brain gets overwhelmed and always tries to piece more than 1 thing together. I don't think I've quite grasped the language of how logic and programming works just yet. When I try to break things down, I can, but I break it down in a way that breaks programming rules, which isn't logical.

I think it's important I recognized that, and try to alter my thinking when approaching problems.  This is the reason why I took programming because my brain is poor at solving problems and thinking logically quickly. I like to try everything wrong first, and by that I learn how something works.

I don't know If I can change that, or if I will just struggle with everything before getting it, but I will continue on in hopes that I will be able to adapt to problems in a more logical way.

On to problem 3. I'm setting my expectations that it will take me 8-10 hours, that way I don't feel overwhelmed if I get stuck.




Friday, December 9, 2016

PSET2
Struggling with this one. I've spent a lot of time going over concepts in the videos so I won't struggle when it comes to the PSETS.

Spent probably 4 hours at work with the first problem. The program was to accept a persons name as input, the output should be the persons initials. It seems simple

I was overthinking this and tried to lookup help. once I saw code looking for the char right after the whitespace, it was like a "Duh" moment.

I feel bad for needing to look up the solution, but this seems like a common theme. I'm a terrible problem solver. I need to see an example before figuring something out.

I hear that programming is about solving problems, and this is a weakness for me, so that's partly why I'm trying to learn programming. To get better at a weakness and it's frustrating as hell.
---

Problem 2 isn't going any better. I got pissed off, and then had a beer or two and played video games.
I'm having trouble concentrating, went to bed early last night only to wake up to my cat meowing like he was dieing, then proceeded to meow for the next 3 hours. I couldn't fall asleep and basically wrecked my evening and got 4 hours of sleep.

 The last 7-8 months this seems to be a common theme. I go to bed shut off the lights, and then he starts running around and meowing, until 2 in the morning. I'm fed up and it's beyond ridiculous. He has already wrecked my carpet, and I don't invite people over without cleaning for 2-3 hours. Anybody want a cat?

Anywho It's 9PM on a friday, and I'm wiped. Going to bed. I had planned to complete the 2nd solution and spend my Saturday struggling on the big one, but I may have to change that.

Monday, December 5, 2016

PSET 0&1

100%
I found the gradebook section of the CS50 course, and received 1.00, for both PSET 0, and PSET1. (means 100%) So I am stoked about that.

As far as I know it's a bot that tries your program with multiple inputs and ensures the output is what's specified.

Last Week
Last week I finished the PSET1, as well as started watching the lectures and shorts of PSET2. I did notice that the "floats" walk-through section might have helped me through PSET1, If I find difficulties in PSET2 I may skip ahead a little to next week's walk-through's.

On PSET2. I have watched the 2 (almost hour long lectures), as well as the walkthough videos. I still have over 2 hours of video to watch for this week before attempting the PSET2. which hopefully I can start to work on thurs/fri.