Vectors in C++

Vectors in C++ is an interesting data structure which is bit similar to arrays. Not having a fixed size is the main difference though. The vector class is in C++ std namespace.

Vectors are associated with some useful methods which are handy in controlling vectors. Refer to the guide for more info.

Method push_back( ) to be used to add elements to a vector. Accessing an element can be done through accessing the relevant index as in arrays. size( ) gives the number of elements in a vector.

Defining a Vector

Creating an instance of the vector class.


#include <iostream>
#include <vector>

using namespace std;

int main()
{
   vector<string> names;
   
   cout << "Size of the vector : " << names.size() << endl;
   return 0;
}

Assign Values to a Vector


#include <iostream>
#include <vector>

using namespace std;

int main()
{
   vector<string> names;
   names.push_back("Alex");
   names.push_back("Bob");
   
   cout << "Size of the vector :" << names.size() << endl;
   cout << "First Name :" << names[0] << endl;
   
   names[0] = "Alex the great";
   
   cout << "First Name :" << names[0] << endl;
   
   return 0;
}

Example

Here is an example on how vectors can be used to solve a problem.

Write a function that accepts an upper bound positive integer and then calculate all the prime numbers within the given integer (excluding). Prime number set should starts with 2 in the index = 0.


#include <iostream>
#include <vector>

using namespace std;

vector<int> get_primes(int num);
bool is_prime(int num);

int main()
{
   vector<int> output;
   output = get_primes(20);
   
   for(int j=0; j < output.size(); j++){
       cout << "Prime No at index - " << j << " = " << output[j] << endl;
   }
   
   return 0;
}

vector<int> get_primes(int limit){
    vector<int> primes;
    for(int i = 2; i < limit; i++){
        if(is_prime(i)){
            primes.push_back(i);
        }
    }
    return primes;
}

bool is_prime(int num){
    for(int i = 2; i<num; i++){
        int r = num % i;
        if(r ==0){
            return false;
        }
    }
    return true;
}

Output

Prime No at index - 0 = 2
Prime No at index - 1 = 3
Prime No at index - 2 = 5
Prime No at index - 3 = 7
Prime No at index - 4 = 11
Prime No at index - 5 = 13
Prime No at index - 6 = 17
Prime No at index - 7 = 19

The code is self-explanatory. Notice how vectors are used in methods. Assigning values and accessing the indexes.

Advertisements

New Approach to Solve Dynamic Job Shop Scheduling Problem Using Genetic Algorithm

This paper has been presented in 3rd International Conference on Information Technology Research held in Colombo on 2018 December 06th.

New Approach to Solve Dynamic Job Shop Scheduling Problem Using Genetic Algorithm

Authors : Chandradeepa Kurera, Palitha Dasanayake

Session Chair : Prof. Chan-Yun Yang

Abstract— Job Shop Scheduling Problem (JSSP) is one of the most common problems in manufacturing due to its widespread application and the usability across the manufacturing industry. Due to the vast solution space the JSSP problem deals with, it is impossible to apply brute force search techniques to obtain an optimal solution. In this research, Genetic Algorithm (GA) approach, which is another widely used nonlinear optimization technique, has been used to propose a solution using a novel chromosome representation which makes seeking solutions for the Dynamic JSSP more efficient. Due to operation order criteria of the jobs and the machine allocation requirement on machines, generating solutions for JSSP needs an extra effort to eliminate infeasible solutions. Due to level of the complexity with added constraints, there is a high tendency to get more infeasible solutions than feasible solutions. This results in consuming a lot of computing resources to correct such a conventional order-based chromosome representation. Due to this, a new representation is proposed in this paper. It is found that the proposed new chromosome representation approach makes it possible to model such dynamic behaviours of schedules without compromising the performances of GA.

Keywords— Genetic Algorithm, Job Shop Scheduling Problem, Dynamic Job Shop Scheduling Problem

Corresponding Author – bckurera AT gmail DOT com

IEE Linkhttps://ieeexplore.ieee.org/document/8736128

Conference Web Site – http://www.icitr.mrt.ac.lk/

Working with Dictionaries – JSON in Python

In Python, Dictionary is a data structure in which data is indexed by the key value. Therefore in order to access it’s data members the key value is required. When converting data to JSON it is ideal to use dictionary as JSON format support the key-index and value pairing format. In this post, it is mentioned how to achieve dictionary to JSON and JSON to dictionary conversion.

Dictionary

A structure of a simple dictionary is as follow:


sample_dictionary = {'key-1' : 'value-1', 'key-2' : 'value-2' }

There is a function named dict( ) which can be used to create a dictionary.

JSON library

In Python, JSON library is readily available. Main two methods we are using are dumps and loads.

.dumps()

Converts a data structure in this case a dictionary to a JSON string.

.loads()

This method can be used to convert a JSON string to a dictionary data structure so that it can be accessed within the code using key-values of the indexes.

Study the following example, a dictionary is defined with few levels, termed as nested dictionary. Data of a Tennis match is arranged.

import json

match = {
	'match-name' : 'USA F35 Futures',
	'match-general-info' : 
		{'match-date' : '2018.12.04', 'match-time' : '22:30', 'match-place' : 'Tallahassee'},
	'player-A' : 
		{'name' : 'Random Name A', 'age' : 20, 
			'rankings' : {'local' : 4, 'ITF' : 17, 'results' : 
				{'winner': 35, 'runner-up': 20, 'break-down' :
					{'semi' : 10, 'quarter' : 4, 'R16' : 1}
				}
			}		 
		}
}


json_string = json.dumps(match,0)

print ('Data Set in JSON format \n' + json_string)

match_dict = json.loads(json_string)

no_of_semis = match_dict['player-A']['rankings']['results']['break-down']['semi']

print ('Number of semi-final matches the player played : ' + str(no_of_semis) + ' matches')

Note that how the values of the data structure are accessed using nested indexes. This method can be used to manage multi-level data hierarchy but it might be bit difficult to manage as the size of the data structure increases. Another disadvantage is to access the values, it is required to supply the key of the index.

Download files from a URL – Python script

Downloading files from a web server over the internet is a trivial task which is performed in our everyday life. Isnt it?

For example when accessing a web site, your browser downloads some files to your computer. Commonly, it could obviously be .html files and then it might include .css .js files as well. You dont notice it as it is handled and managed by the browser itself. However there can be instances that you need to access a specific URL and download some files. No doubt it can be done manually. What if there are hundreds of files to be downloaded. In this article it is discussed how to get it done with minimal effort using a Python script.

Disclaimer – Employing a script to access/ download content from a web server can cause a higher traffic towards the web server. Therefore do not use this knowledge to access any resource in a web server without getting prior permissions. Use this script at your own risk. The author bears no responsibility.

For the purpose we are going to use the library urllib which is an inbuilt library in Python. .urlopen and .read methods can be used to access the content of the resource and then .write method can be used to save the content to the local machine. Check how the code is organized.

Python Version 2.7.15

import urllib
url = 'http://url-for-resources'

webf = urllib.urlopen(url)
txt = webf.read()
f = open('local-machine-folder-path', 'w+')
f.write(txt)
f.close()

It is pretty straight forward. Then the next objective is to automate the process. Using a loop is the easiest. One issue to overcome though. How to get the file names. If the file names follow a regular sequence for example data_01.json, data_02.json, data_03.json etc, it is possible to generate the sequence. Otherwise file names should be inserted to the code. A solution could be to extract the file names to a file and then read the file and get filenames. 

Here is the Python script for the above approach.


import urllib

f = open("local-file-with-file-names", "r")
file_list = f.readlines()


for x in file_list:

	filename = x.strip()
	url = 'http://url-for-resources/'+ filename

	webf = urllib.urlopen(url)
	txt = webf.read()
	f = open('local-file-path-to-save/'+filename, 'w+')
	f.write(txt)
	f.close()
	
	print('Saving file ' + filename)

One line contains one file name in the file which is used to include files to be downloaded.

Node-to-Node Secure Data Transmission Protocol for Low-power IoT Devices

This paper has been presented in 2018 International Conference on Advances in ICT for Emerging Regions (ICTer) held in Colombo on 2018 September 28th.

Node-to-Node Secure Data Transmission Protocol for Low-power IoT Devices

Authors : Chandradeepa Kurera (University of Moratuwa, Katubedda, Sri Lanka.), Dasun Navoda

Session Chair : Prof. Christian Rohner

Abstract— Through the internet and local networks, IoT devices exchange data. Most of the IoT devices are low-power devices, meaning that they are designed to use less electric power. To secure data transmission, it is required to encrypt the messages. Encryption and decryption of messages are computationally expensive activities, thus require considerable amount of processing and memory power which is not affordable to low-power IoT devices. Therefore, not all secure transmission protocols are low-power IoT devices friendly. This study proposes a secure data transmission protocol for low-power IoT devices. The design inherits some features in Kerberos and one-time password concepts. The protocol is designed for devices which are connected to each other, as in a fully connected network topology. The protocol uses symmetric key cryptography under the assumption of that the device specific keys are never being transmitted over the network. It resists DoS, message replay and Man-of-the-middle attacks while facilitating the key security concepts such as Authenticity, Confidentiality and Integrity. The designed protocol uses less number of encryption/ decryption cycles and maintain session based strong authentication to facilitate secure data transmission among nodes.

Keywords— IOT, Secure Data Transmission, Node to node data transmission, Transmission Protocol, Low-power IoT devices

Corresponding Author – bckurera AT gmail DOT com

Conference Web Site – http://www.icter.org/

Published in IEEE Xplorehttps://doi.org/10.1109/ICTER.2018.8615511

Ballerinalang – Union Type

Ballerinalang is a strongly typed language, meaning that type of a variable is very important. As a result, if a variable is defined as an int type variable, it cannot hold any other value which does not belong to the said data type, such as a float type value.  Then in functions in Ballerinalang, it is possible to return multiple values which belongs to different types, discussed earlier in Ballerinalang – Functions post. When a function can return values belong to multiple types, there should be a way of assigning those different values with different types. Should not it?

The concept is as simple as the name, it explains itself. In a union type, the variable can take any value which belong to it’s component types. Ok, lets say a union type variable is defined using types int, float and string. Then that variable can hold an int type value (integer) or a float type value (decimal figure) or a string (some characters). But at a given time it can take one form, value which belongs to a type, only one type.

Following is the syntax:

type1 | type2….. | type n <variable name>;

or

type1 | type2….. | type n <variable name> = <initialization value> ;

Define Union Type variable

Union type variable can have many types. The implicit default value is ( ). Check the following code:

import ballerina/io;

function main(string... param){
    int|float|string one_var;
    float|boolean|() two_var = 3.14;

    io:println("Value of one_var = ", one_var);
    io:println("Value of two_var = ", two_var);

    one_var = "Assigning string value";
    two_var = false;

    io:println("Value of one_var = ", one_var);
    io:println("Value of two_var = ", two_var);
}



Output
Value of one_var =
Value of two_var = 3.14
Value of one_var = Assigning string value
Value of two_var = false

Observe the following scenario which captures a value passed by a function which returns multiple types.

import ballerina/io;
import ballerina/math;

function main(string... param){
    float|string converted_speed;

    converted_speed = convert(45.5);
    io:println("Converted Speed is - ", converted_speed);

    converted_speed = convert(100);
    io:println("Converted Speed is - ", converted_speed);
}

function convert(float speed) returns (float|string){
    if(speed < 0) || (speed>60) {
        return "Not defined !";
    }
    return speed * 0.45;
}



Output
Converted Speed is - 20.475
Converted Speed is - Not defined !

The converted_speed variable can take two type of values, float and string. Therefore based on the type the function returns, the variable hold the value.

More…

Actually, the variable can take many forms but it is not purely belonging to one type. For an example, at any time, it is wrong to identify one_var as a string type variable, because it holds a string value. It is type is compuse always. All time, the type of variable one_var is int|float|string

In order to fully understand the logic, observe the following example:

import ballerina/io;
import ballerina/math;

function main(string... param){
    float|string speed = "NA";

    if (speed=="NA"){
        speed = math:random() * 60.0;
    }

    io:println("Current speed = ",speed);

    speed = speed * 0.5;
    io:println("Half of Current speed = ",speed);
}

Output
operator '*' not defined for 'float|string' and 'float'
compilation contains errors

If following line is excluded, the program works fine. Because speed is not considered as a float type value though it holds a float type value. It is always float|string type variable.

speed = speed * 0.5;

In case it is required to carry out the above calculation, then it is required to define another float type variable, get the calculation done and assign the value to the speed variable. That should be the correct way of doing it.

import ballerina/io;
import ballerina/math;

function main(string... param){
    float|string speed = "NA";

    if (speed=="NA"){
        speed = math:random() * 60.0;
    }

    io:println("Current speed = ",speed);

    float half_speed = speed;
    half_speed = half_speed * 0.5;
    speed = half_speed;

    io:println("Half of Current speed = ",speed);
}


Output
incompatible types: expected 'float', found 'float|string'
compilation contains errors

Then another error, it is obvious right. Because since the newly defined variable is float type, then it is not possible to assign float|string type value. Then what is the way around here?

This is why match construct and match expression come handy. Will discuss them in the next post.

Ballerinalang – Maps

In case it is required to maintain an array with defined indexes, Maps is the right choice in Ballerina. Not like arrays Maps are mutable, meaning that once the variable has been defined it is not possible to modify it. In maps indexes are termed as fields.

Defining a Map

When defining a map variable, the type of the map can be added. However it is not mandatory. The default type, if no type is mentioned, taken as any. The value of fields of the map, should belong to string type.


import ballerina/io;

function main(string... param){
    map person_info = {"name": "John", "age": 25, "isMarried": true};
    io:println(person_info);

    map speed = {"pointA": 12.75, "pointB": 15.0, "pointC": 5.658};
    io:println(speed);
}

Output
{"name":"John", "age":25, "isMarried":true}
{"pointA":12.75, "pointB":15.0, "pointC":5.658}

Note that when a map is defined with no type, any value can be assigned to it’s filed, whereas when a map is defined with a type, it is not possible to assign value with other types.

To access values in a map,the dot (.) operator or field name can be used.


import ballerina/io;

function main(string... param){
    map person_info = {"name": "John", "age": 25, "isMarried": true};
    io:println(person_info.name , " is ", person_info.age, " years old.");

    map speed = {"pointA": 12.75, "pointB": 15.0, "pointC": 5.658};
    io:println(speed["pointC"]);
}

Output
John is 25 years old
5.658

Observe how map is used in the following example, hope it helps to understand the usability of maps.


import ballerina/io;

function main(string... param){
    map vehicle = {"carType":"A", "mass": 1500, "speed": 60, "isSpeedMetric": false, "unit":0};
    
    io:println("Before Conversion = ",vehicle);

    vehicle.unit = "km/h";       

    if(! check vehicle.isSpeedMetric){
       vehicle.speed = convertToMetric(vehicle); 
       vehicle.isSpeedMetric = true;
    }    
    io:println("After Conversion = ",vehicle);
    io:println("Speed in Metric Units = ",vehicle.speed," ",vehicle.unit);
}

function convertToMetric(map vehicle_info) returns float{
    if(check vehicle_info.isSpeedMetric){
        return check vehicle_info.speed;
    }
    var speed = check vehicle_info.speed;
    return speed*1.60934;
}

Output
Before Conversion = {"carType":"A", "mass":1500, "speed":60, "isSpeedMetric":false, "unit":0}
After Conversion = {"carType":"A", "mass":1500, "speed":96.5604, "isSpeedMetric":true, "unit":"km/h"}
Speed in Metric Units = 96.5604 km/h

Type conversion and type checks need to be performed as the map is not defined with a type.