1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.
  2. Welcome to Lake Valor!
    Catch, train, and evolve Pokémon while you explore our community. Make friends, and grow your collection.

    Login or Sign Up

Coder Dojo! -- Tracing Through Code

Discussion in 'The Lounge' started by Reckless, Dec 18, 2014.

Thread Status:
Not open for further replies.
  1. Reckless

    Reckless Won't take the easy road

    Joined:
    Jan 11, 2013
    Posts:
    2,113
    PokéPoints:
    ₽666.6
    Coding, that thing that lets us humans give a series of instructions to a computer that can be translated into a low-level, machine-readable language, where the only limit is your imagination! Through numerous trial and error, every program and application goes through numerous 'builds' and compilations, carried out each time a fresh build is required. Before all that nitty gritty however, it is vital for any aspiring programmer to learn the subtle art of "tracing"

    'Tracing! What, you mean like drawing over something?!'

    No, not quite, my friend. Tracing, in a computer context, is when, after you look at a snippet of code, you try and determine on paper the result produced by that piece of code after it is carried out by the program at run-time. It's possible that this 'technique' goes by several names, but we've called it 'tracing' here or 'stepping through the program.'

    Basically, it's like working out a maths problem.

    'Rightttt....So what's the point of this topic, then?'

    I'm glad you asked! In a nutshell, every month I shall post here part of a computer program, and all you have to do is work out, on paper, what value it will output to the user at run-time! Whilst you may use a compiler to see what value the code outputs if you wish, you must show how you arrived at a given value, be it on paper or digital art.

    Bear in mind that I'm far from a competent programmer myself (still an undergraduate, after all), so please forgive me if the code snippets I post contain syntax errors and whatnot.

    I shall largely be posting code snippets done in C++, but will branch out to C#/Java (near enough the same thing, anyway) and possibly a few legacy languages too as I myself become more familiar with those languages. Maybe even the dreaded assembly language, simply for kicks, heheh.

    I will permit members asking questions about certain aspects of posted code snippets, but again I must ask that any member who wants to make an attempt at tracing through the code must post an image of how they arrived at a value.

    Now....Onto the code!
     
    Stop hovering to collapse... Click to collapse... Hover to expand... Click to expand...
  2. Reckless

    Reckless Won't take the easy road

    Joined:
    Jan 11, 2013
    Posts:
    2,113
    PokéPoints:
    ₽666.6
    Code Snippet #1;
    Language; C++
    Recursion
    //Functions called in main
    Mystery(5);
    Rose(7);
    Cabin(20);

    //Recursive functions
    int Mystery(int n)
    {
    if (n == 1)
    return 1;
    else
    return n + Mystery(n - 1);
    }

    int Rose(int n)
    {
    if (n == 0)
    return 1;
    else
    return n * Rose(n - 1);
    }

    int Cabin(int n)
    {
    if (n == 1)
    return 0;
    else
    return Cabin(n / 2) + 1;
    }
     
  3. Fantasma

    Fantasma ♃☿♄


    (Cubone (Alolan))
    Level 1
    Joined:
    Sep 19, 2014
    Posts:
    623
    PokéPoints:
    ₽185.1
    Trainer Card - Cave Theme
    ok i didnt understand the instructions lol
    i need to show you how the code works?
    or what does it do?
    or what algorithm you are representing with that code?
    or i need to show you the console output of the code?
    i want to participate in this but i dont understand what are you asking for lol
     
    Stop hovering to collapse... Click to collapse... Hover to expand... Click to expand...
  4. Reckless

    Reckless Won't take the easy road

    Joined:
    Jan 11, 2013
    Posts:
    2,113
    PokéPoints:
    ₽666.6
    Ah. Apologies! I'm not very good at explaining stuff...

    Basically what I'm looking for is the console output of the code. But, instead of just running it through a compiler and let a machine do the number crunching for you, I want you step through the program on paper. I guess I really should've given a value that is passed to each code snippet...whoops.

    All right, please allow me to rephrase things; What do you get when you pass the following values to the functions given above;

    Mystery(5)
    Rose(7)
    Cabin(20)
     
  5. Fantasma

    Fantasma ♃☿♄


    (Cubone (Alolan))
    Level 1
    Joined:
    Sep 19, 2014
    Posts:
    623
    PokéPoints:
    ₽185.1
    Trainer Card - Cave Theme
    Ok thanks for the explanation :)
    now here is my answer :D

    Mystery(5): the method what basically do is this it receive an n > 0, and then it starts a summation n + n-1 + n-2.....+ n-(n-1) (i dont know if i represent that right)
    now with the number you gave me the output would be something like this

    the 5 enter the method
    its not a 1 so it doesn't enter the if
    the method return 5 + Mystery( 5- 1)
    the cycle continue until it gets a 1
    the 1 == 1 enter the if and return 1
    and then start adding itself
    5+4+3+2+1 = 15

    Rose(7): this is a factorial what it does is it receive a number and then start the calc n! = n * n-1! * n-2! .... * 0!

    now with the number you gave me it would be like this
    the 7 enter the method
    7 != 0 so it doesn't enter the if
    the method return 7 * Rose(7 - 1)
    the cycle continue until it gets a 0
    the 0==0 enter the if
    and return a 1
    then it start the calc that would be something like this
    7 * 6 * 5 * 4 * 3 * 2 * 1 * 1 = 5040

    Cabin(20): i really hope to get this right, this method return the number of times that a number can be divided by 2

    now with the number you gave me it would be something like this
    the 20 enters the method
    because 20 != 1 it doesn't enter the if
    and the method return Cabin ( 20 / 2 ) +1
    the cycle continuous until it get a 1
    and when 1 == 1 the method return 0
    and start counting
    eh dont know how it works in this part lol but counts all the time the cycle have been done ( excepting the last one )
    and return 4
    why 4? because
    20 / 2 1
    10 / 2 2
    5 / 2 3
    2 / 2 4
    the method doesn't count 1/2

    here is the output i get using visual studio

    [​IMG]

    i must admit this was fun lol hope to see more of this in the future :D
     
    Reckless likes this.
  6. Reckless

    Reckless Won't take the easy road

    Joined:
    Jan 11, 2013
    Posts:
    2,113
    PokéPoints:
    ₽666.6
    I must admit, that was a great trace you've done, @[member="Fantasma"] ! Don't worry, I'm not too concerned about semantics. You can give wordy explains or you can use pseudo code, I don't mind.

    Yup, I can confirm that those are the correct results, well done!

    Yeah, the recursion for 'Cabin' is daaaamn tricky (I myself do not get it 100%). But from what I understand... in the return statement, outside of the call to itself, because we're only asking for a 1 back, the function, when it hits the unwinding stage it counts every recursive call to itself, and returns that value. So that's 1+1+1+1 = 4. We can see this in practice if we slip in a print command in the non-base case, 'else' part of the function, before recursion commences;


    else
    {
    cout << n << endl;
    return Cabin(n / 2) + 1;
    }

    Console output;
    [​IMG]

    Well, I guess I'll leave this thread open for suggestions for future coding samples. So fire away, guys!
     
  7. East

    East Look to the Stars

    Joined:
    Nov 14, 2014
    Posts:
    1,785
    PokéPoints:
    ₽742.2
    @[member="Reckless"] would I be allowed to do something similar to this in other languages as well? I know Java, JS, (some) PHP, CoffeeScript, HTML, CSS, and some others to a lesser extent, so I'd like to be able to exercise that. :)
     
  8. Reckless

    Reckless Won't take the easy road

    Joined:
    Jan 11, 2013
    Posts:
    2,113
    PokéPoints:
    ₽666.6
    Oh, like make a scripting language version of this? Sure, go ahead! I'd love to see that happen, go right ahead. :)

    As for the next coding snippet I'll post here, I am looking around, so no worries there. I might do something with tracing through a Towers Of Hanoi problem next. ;)
     
  9. East

    East Look to the Stars

    Joined:
    Nov 14, 2014
    Posts:
    1,785
    PokéPoints:
    ₽742.2
    Oh my... I remember when I learned Towers of Hanoi in math class.... I became so obsessed that I made my own version of it at home and made versions of up to 13 rings.... I got crazy on that XD
    And awesome! After I finish my codes for class I'll see what I can make for this B)
     
  10. Reckless

    Reckless Won't take the easy road

    Joined:
    Jan 11, 2013
    Posts:
    2,113
    PokéPoints:
    ₽666.6
    That's great to hear. But, before this thread inadvertently turns into a chat thread, I'm gonna lock it for now.

    Alternatively, why don't one of you create a topic about Programming? Maybe talk about what projects you're working on, ask any q's you might have. I won't have a problem with it, as long as your posts are meaningful and, naturally, abide by the rules. :)
     
  11. Reckless

    Reckless Won't take the easy road

    Joined:
    Jan 11, 2013
    Posts:
    2,113
    PokéPoints:
    ₽666.6
    Welcome back, everyone! Today I'll be sharing a new coding snippet, so I hope you enjoy it!

    Code Snippet #2;
    Language; C++
    Towers Of Hanoi
    For those of you who saw the 2011 "Rise of the Planet of the Apes" film, you might have seen this technique being used to test the intelligence of the apes. (Though in the film it was called "Lucas' Tower"). The towers stem from an ancient Brahmin tale that says the life of the universe is defined in terms of the time it will take a group of monks (working continuously) to move a set of 64 gold disks, all of different diameters, from one pole to another. There are however specific rules about how the transfer should be done, and they alone causes such a trivial project to take a long time to complete.

    So you have three 'towers', essentially, with a certain number of disks stacked on the first tower on the left. The aim is to stack them all again, in the exact same order, on tower 3, the last tower on the right. The tower in the middle, tower 2, can be used to temporarily stack disks. How many moves does it take to accomplish this, bearing these rules in mind?

    Towers of Hanoi Rules (PLEASE familiarise yourself with these, if you do not already know then!)
    1. Only one disk may be moved at a time.
    2. A third pole may be used for temporary storage of disks.
    3. No disk should ever be placed on top of a disk of smaller diameter.
    4. The disks are arranged on the original pole initially with the largest disk on the bottom, the second largest disk on top of it, and so on. The smallest disk ends up being on top of the stack.

    Now that the preamble is out of the way, walk me through how you'd move 4 disks, using the following implementation file.
    /*TowersOfHanoi.cpp*/

    #include <iostream>
    using namespace std;

    void Hanoi (int n,int start, int finish, int temp);

    int _tmain(int argc, _TCHAR* argv[])
    {
    int disks = 4;

    cout << "\n Towers of Hanoi: Solving a problem of size "
    << disks << endl;
    Hanoi (disks, 1, 3, 2);
    return 0;
    }

    void Hanoi (int n,
    int start, int finish, int temp)
    {
    if ( n == 1)
    cout << "Move top disk from pole "
    << start << " to top of pole " << finish << endl;
    else
    {
    Hanoi (n-1, start, temp, finish);

    cout << "Move top disk from pole "
    << start << " to top of pole " << finish << endl;
    Hanoi (n-1, temp, finish, start);
    }
    }

    As a side activity, I've also decided to include something else for y'all to do. The following message has been encrypted with a Caesar Cipher. I want you to decrypt the Ciphertext and show me the plaintext. Have fun!

    OCDIBN OCVO BJ WPHK DI OCZ IDBCO
    NCJPGY IJO MZVGGT BDQZ JIZ V AMDBCO
    DO'N OCZ CJGZ DI ZVXC ZVM
    OCVO GZON DI OCZ AZVM
    OCVO VIY OCZ VWNZIXZ JA GDBCO!
     
  12. Steamlined

    Steamlined Jack of all trades

    Joined:
    Sep 20, 2014
    Posts:
    852
    PokéPoints:
    ₽45.0
    EDIT: Well dang, I really did forget the last two words! How did that even happen!?

    Well, while I try and figure out what the heck is going on in that script, I went for the easier Cipher for the time being.

    Don't open it if you want to work it out yourself! :P
    [​IMG]

    First off, please don't mind my god-awful handwriting. I tried my best! :P

    So, I started with the obvious. I picked the first word in the sentence, and I made the assumption that the first letter was a consonant, and the second a vowel. After all my attempts I found that wrong. Then I assumed the first letter was a Vowel, but then I figured out just how futile this approach, so I took another approach.

    I took the word "BJ" (Yes.) and I tried to decode that alone. I figured it would be a connective, but I ended up just picking 2 letter words that I could think of at random. When I got to "GO" and it matched up perfectly, I was real damn happy. That let me figure out that the key was +5.

    After that? Well it's simple enough. I wrote out the encrypted sentence and decrypted it. I drew a more helpful alphabet line halfway through, as you can see.

    And after it was done, I got the sentence below:

    THINGS THAT GO BUMP IN THE NIGHT
    SHOULD NOT REALLY GIVE ONE A FRIGHT
    IT'S THE HOLE IN EACH EAR
    THAT LETS IN THE FEAR
    THAT AND THE ABSENCE OF LIGHT! (I forgot that part on the real thing. >.<)

    ...Whatever all that means. You trying to give us memetic fear triggers Reckless? :o

    But I'll work on that code tomorrow, I'm surprisingly tired for some reason. :/
     
    Stop hovering to collapse... Click to collapse... Hover to expand... Click to expand...
  13. Reckless

    Reckless Won't take the easy road

    Joined:
    Jan 11, 2013
    Posts:
    2,113
    PokéPoints:
    ₽666.6
    @[member="Steamlined"] Verrrry impressive work! (heck, the way you decipher is way neater than mine, actually!) Yup, you've decrypted the message successfully. (Though it appears you left out the last too words. ;) )

    Hah, tenacious, I see!

    How about the rest of you? @[member="Fantasma"] , @[member="Kouhai"] ? Anyone else wanna take on the code snippet? Don't be shy now. :)
     
  14. Fantasma

    Fantasma ♃☿♄


    (Cubone (Alolan))
    Level 1
    Joined:
    Sep 19, 2014
    Posts:
    623
    PokéPoints:
    ₽185.1
    Trainer Card - Cave Theme
    Sorry Reck but i wont be doing this one :/ i have a project so I will be doing that lol
     
  15. Reckless

    Reckless Won't take the easy road

    Joined:
    Jan 11, 2013
    Posts:
    2,113
    PokéPoints:
    ₽666.6
    @[member="Fantasma"] Fair enough. That's fine. Anyone else? One than one can try their hand at tracing through the code. :)
     
  16. East

    East Look to the Stars

    Joined:
    Nov 14, 2014
    Posts:
    1,785
    PokéPoints:
    ₽742.2
    Just to note, this is solving the Caesar Cipher. I haven't gotten to the Towers of Hanoi yet since C++ still isn't my forte.
    To begin, I had to solve the key of the Caesar Cipher. After testing the first part of the cipher text, OCDIBN, (though it was through trial and error) the rest was pretty easy.
    However, here's how I found the key:
    [​IMG]
    Using ASCII decimal code, I decided to construct a Java program:
    public class CaesarDecipher
    {
    public static void main(String args[])
    {
    String cipherText;
    cipherText = "OCDIBN OCVO BJ WPHK DI OCZ IDBCO NCJPGY IJO MZVGGT BDQZ JIZ V AMDBCO DO'N OCZ CJGZ DI ZVXC ZVM OCVO GZON DI OCZ AZVM OCVO VIY OCZ VWNZIXZ JA GDBCO!";
    int j = 0;
    for (j = 0; j < cipherText.length(); j++)
    {
    char decrypt = cipherText.charAt(j);
    if (Character.isLetter(decrypt))
    {
    if (decrypt + 0 < 86)
    {
    char newLetter = (char)(decrypt + 5);
    System.out.print(newLetter);
    }
    else
    {
    char reboundLetter = (char)(decrypt - 21);
    System.out.print(reboundLetter);
    }
    }
    else if (Character.isWhitespace(decrypt))
    {
    System.out.print(" ");
    }
    else
    {
    System.out.print(decrypt);
    }
    }
    }
    }
    And ended up with the following printout:
    THINGS THAT GO BUMP IN THE NIGHT SHOULD NOT REALLY GIVE ONE A FRIGHT IT'S THE HOLE IN EACH EAR THAT LETS IN THE FEAR THAT AND THE ABSENCE OF LIGHT!
     
  17. Reckless

    Reckless Won't take the easy road

    Joined:
    Jan 11, 2013
    Posts:
    2,113
    PokéPoints:
    ₽666.6
    @[member="Kouhai"] That's another great solution! And yep, that's the message. It never struck me to make a program to encrypt a message. Hmm. Food for thought.

    I've also amended the Towers Of Hanoi code a teeny bit. So if you want to see what message your compiler throws out once you run the code, be my guest.
     
  18. East

    East Look to the Stars

    Joined:
    Nov 14, 2014
    Posts:
    1,785
    PokéPoints:
    ₽742.2
    @[member="Reckless"] what compiler do you use personally for C++? I haven't gotten much into the compiler area for that language yet and am looking for a good one to start off with.
    Notepad++ is pretty nice for code generally, but is there something different you use?
     
  19. Reckless

    Reckless Won't take the easy road

    Joined:
    Jan 11, 2013
    Posts:
    2,113
    PokéPoints:
    ₽666.6
    @[member="Kouhai"] I tend to flip-flop between two. Visual Studio Professional versions 2012 and 2013. I mainly use the 2013 version, whereas a lot of my older projects were done in 2012.
     
  20. Reckless

    Reckless Won't take the easy road

    Joined:
    Jan 11, 2013
    Posts:
    2,113
    PokéPoints:
    ₽666.6
    Well, it's been a while, but here's something new for y'all to trace through!

    Up now; Quicksort

    Here's a problem that's been annoying me for the past week or so.

    So then, to business;

    You've got an unsorted array[8] of integers;

    13


    48


    38


    18


    45


    4


    43


    55


    ...Which we want to apply a QuickSort function to;
    void QuickSort (ItemType values[], int first, int last)
    {
    int splitPt1, splitPt2;
    if (first < last)
    {
    Split(values, first, last, splitPt1, splitPt2);
    QuickSort(values, first, splitPt2);
    QuickSort(values, splitPt1, last);
    }
    }

    You'll notice that the QuickSort function in turn calls a Spilt function...
    void Split(ItemType values[], int first, int last,
    int& splitPt1, int& splitPt2)
    {
    Itemtype splitVal = values[(first+last)/2],t;
    int i = first, j = last;
    while (values < splitVal) i++;
    while (values[j] > splitVal) j--;
    while (i < j)
    {
    t = values; values = values[j]; values[j] = t;
    i++; j--;
    while (values < splitVal) i++;
    while (values[j] > splitVal) j--;
    }
    if (i == j)
    {
    i++; j--;
    }
    splitPt1 = i;
    splitPt2 = j;
    }


    So get to tracing, folks! Gonna be a tough one for sure.
     
Thread Status:
Not open for further replies.

Share This Page