Morse code

As a test, I was asked to write a morse code task where some of the signals weren’t able to be determined from the input. So in this case instead of having either the dot (.) or dash (-) we have a question mark (?) where it could be either a dot / dash.

Here is an image of the morse code alphabet of dots / dashes and here is a link to a view of the “tree” of the morse code of the dichotomic search, basically binary search of the morse code.

So, we are only going down 3 levels, below are some tests to confirm that the process is working fine.

  • .- = A
  • . = E
  • … = S
  • -.- = K
  • ? = ET
  • -? = NM

So, I approached this test by thinking that I need to have an “item” that stores the current value (e.g. character) and left / right item, and here is my item.h definition.

class item {
    private:
        char value;
        item *left;
        item *right;
    public:
        item(char value,item *left,item *right);
        item(char value);
        item(item *left,item *right);

        item();

        char getValue();

        item* leftItem();
        item* rightItem();
};

And then to build the 3 levels of the search tree

    item* head = new item(
        new item('e',
            new item('i', 
                new item('s'),
                new item('u')
            ),
            new item('a',
                new item('r'),
                new item('w')
            )
        ),
        new item('t',
            new item('n', 
                new item('d'),
                new item('k')
            ),
            new item('m',
                new item('g'),
                new item('o')
            )
        )
    );

and then the last part was literally reading in the signal to be processed and going down the tree either left / right or both for undermined signal.

string output(string signal, item* codes) {
    string ret="";
    if (signal.size() ==0 ) 
        return string(1,codes->getValue());
    for (string::size_type i=0; i < signal.size();i++) {
        if ('?' == signal[i]) {
            ret += output("."+signal.substr(i+1),codes);
            ret += output("-"+signal.substr(i+1),codes);
            return ret;
        } else if ('.' == signal[i]) {
            return output(signal.substr(i+1),codes->leftItem());
        } else if ('-' == signal[i]) {
            return output(signal.substr(i+1),codes->rightItem());
        } else {
            throw invalid_argument(string("Invalid character at this point of the string ").append(signal));
        }
    }
    return ret;
}

If you want to view the whole code, here is the link to the zip file of the morse code.

vectors and for_each

A friend of mine asked how to use the newer for_each and is it similar to the foreach in php, so here is the example that I gave and thus doing it online as well.

To start with the foreach (php version here) does loop over data and so does the for_each in c++, but the main difference is that the for_each in c++ is basically a for loop

for (; first!=last;++first)
   functionCall(*first);

where the functionCall is the parameter passed in to do something with that part of the data.

The great thing with c++ is that you are able to use either a method, structure etc as long as it is able to output a variable then we are good.

So here is a example, please note that I am loading up a vector e.g. only functions that have a single int make sense.

void printNumber (int i) {
	cout << "Print the number from a function : " << i << "\n";
}
 
for_each(v.begin(), v.end(), printNumber);

here we are using the for_each (where the v is a vector) passing in the start and end of the vector with a function as the last parameter.

and here

// create a object that can use the operator() to output value passed in.
struct structToOutput {
	void operator() (int i) {
		cout << "Struct to output : " << i << "\n";
	}
} structToOutputObject;
 
for_each(v.begin(), v.end(), structToOutputObject);

will output the values differently but in essence still able to access the values.

Here is the code in full

#include <iostream>
#include <vector>
#include <algorithm>
 
using namespace std;
 
void printNumber (int i) {
	cout << "Print the number from a function : " << i << "\n";
}
 
// create a object that can use the operator() to output value passed in.
struct structToOutput {
	void operator() (int i) {
		cout << "Struct to output : " << i << "\n";
	}
} structToOutputObject;
 
int main(int argc, char* argv[])
{
	// lets load up some dummy data.
	vector<int> v;
	for (int i =0; i< 10; i++)
		v.push_back(i);
 
	// run through the vector using a standard function with parameter
	for_each(v.begin(), v.end(), printNumber);
	// output using a operator() method
	for_each(v.begin(), v.end(), structToOutputObject);
	return 0;
}

with the output being

Print the number from a function : 0
Print the number from a function : 1
Print the number from a function : 2
Print the number from a function : 3
Print the number from a function : 4
Print the number from a function : 5
Print the number from a function : 6
Print the number from a function : 7
Print the number from a function : 8
Print the number from a function : 9
Struct to output : 0
Struct to output : 1
Struct to output : 2
Struct to output : 3
Struct to output : 4
Struct to output : 5
Struct to output : 6
Struct to output : 7
Struct to output : 8
Struct to output : 9

How to compile with g++

g++ <filename> -o <outfilename> -std=c++11

auto and lambda

The C++ 11 standards are starting to take more and more cue’s from other languages where you are able to create functions on the fly (lambda). With also adding the “auto” keyword which will allow the program to automatically figure out what type of variable will be returned from lambda function.

So here the break up of the lambda function is

<return type> <[optional local variables to be used]>(optional parameters);

The optional local variables are abit like the “use” within PHP (use)

So the full code is

#include <iostream>
#include <vector>
#include <algorithm>
 
using namespace std;
 
int main(int argc, char* argv[])
{
	int num = 30;
	int anothernum = 0;
 
	auto func = [&anothernum](int i) {
			cout << "Parameter passed in :" << i << "\n";
			anothernum = anothernum + 10; // alter the value passed in.
			return 50;	// return a value and use the auto keyword.
	};
	int ret = func(num);
	cout << "Return from func :" << ret << "\n";
	cout << "Another num :" << anothernum << "\n";
	return 0;
}

and the output would be

Parameter passed in : 30
Return from func : 50
Another num : 10;

To compile with g++ I used these parameters

g++ <filename> -o <outfilename> -std=c++11

Function vs Method

The main difference between a function and a method is that a function can live independently of the any instance of a class, where as a method sits within a class.

That is about it, e.g. a function is

int func(int value);
...
 
int main()
{
  cout << funct(3) << endl;
}

whereas a method has to live within a class

class myclass
{
    int myMethod(int it);
};
 
....
 
int main()
{
   myclass theclass;
   cout << theclass.myMethod(4) << endl;
}

Strings

Just a small thing encase anyone else finds this interesting as such.. but you cannot add a set of ” ” strings together in c++ without declaring one being a string.. for example

cout << "hi" + "bye" << endl;

the error would be

error: invalid operands of types 

Why -> and not *name.type

When you are coding with pointers in c++ and you want to access the function/variable from that pointer deferenced, how come you cannot use something like below.

struct typeT{
   int value1;
};
 
typeT* tt = new typeT;
*tt.value1;

it is because the access element of the variable tt is higher in the compiler and thus it tries to equate

tt.value1

first, which is not a good thing because the tt has not been de-referenced and thus it is just a memory address pointer to the actual object. so you need to do

(*tt).value1

because like in maths the () will be equated first and then the access element part “.” and thus to make it easier

tt->value1

will change to

(*tt).value1

within the compiler.

CS107 – Assignment 2 – Six degrees

This is assignment 2 from a older CS107 course, because the latest course work is held on a UNIX server which in turn you need access to!!.. kinder does not help when you do not have access too!!.. Here is where I got the files from cs107 link, there is a zip file at the bottom of that page which has all of the assignments and handouts etc.

I have included the PDF of the assignment in the above file link, but since the actual assignment includes a few massive files you can download them from the CS107 link of the whole course work that I am using from the cs107 link.

As a note, within my linux setup, I need to setup the environment variable to tell the program to use a Linux little endian by

export OSTYPE=linux

Basically the assignment is to load in cast/movie details (which the base code from the assignment already does for use) and then we are needed to pull out the data from the structure of the file, the structure of the actors is (as taken from the PDF file)

  1. The name of the actor is laid out character by character, as a normal null-terminated C-string. If the length of the actor