Coding Challenge #1 – Sum of multiples

Here is a little coding challenge to try.

The objective is to find the sum of multiples within a given range.

For example assume that given multiples are 4, 5 and 7. The upper limit is 20 (excluding). Multiples of 4 within 20 are 4, 8, 12 and 16. Then multiples of 5 within 20 are 5, 10 and 15. The multiples of 7 within 20 are 7 and 14. The objective is to find the sum of all those numbers.

The upper limit and the number of multiples can be vary from problem to problem.

Solution in Cpp

#include <iostream>

using namespace std;

int isMult(int mult[], int n, int length);

int main () {
    int no_of_mult = 2;
    int multiSet[no_of_mult] = {3, 5};
    int upper_limit = 10;
    int sum = 0;
    for (int i=0; i &lt; upper_limit; i++){
        sum = sum + isMult(multiSet, i, no_of_mult);
    cout &lt;&lt; "Sum = " &lt;&lt; sum;

int isMult(int mult[], int n, int length){
    for(int i =0; i &lt; length; i++){
        int r = n % mult[i];
        if(r == 0){
            return n;
    return 0;

Try it online


Finding nth prime number – JavaScript

Recently one of my friends mentioned a coding problem where the 1001th prime needs to be found out. Out of many ways to achieve the answer, I used the elimination method which probably you would have used in the elementary school. Formally, this method is known as Sieve of Eratosthenes. When the position of the prime needs to be found out this approach is pretty simple and straightforward.

Following is how the problem is solved:

The 1001th prime is 7927
The source code can be used to find out any nth prime.

However the time efficiency of this algorithm is in order of n! which means for higher upper limit, this method is extremely slower.

Check the code which is self explanatory.

class prime{
		let arr = this.createList(limit);
		let primes = this.savePrimes(arr);
		return primes;
		let numberList = [];
		for (let i=2; i<=max; i++) {
		return numberList;

		let i, j;
		for (i=0; i < numArr.length; i++){
			let x = numArr[i];
			for (j=i+1; j < numArr.length; j++ ){
				let y = numArr[j];
				let r = y%x;
					numArr[j] = null;
			numArr = this.removeZeros(numArr);
		return numArr;

		let newArr = [];
		for (let x in numArr){
			let e = numArr[x];
		return newArr;

let obj = new prime();
let primeNumbers = obj.getPrimes(10000);

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

Conference Web Site –

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.


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.


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


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 =
f = open('local-machine-folder-path', 'w+')

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 =
	f = open('local-file-path-to-save/'+filename, 'w+')
	print('Saving file ' + filename)

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

Constitutionality of the NCM – Democracy As Seen By A Dummy

Trias Politica or Separation of power is a common concept among the democratic hemisphere. The basic concept holds the governance of the state. Being a Democratic Republic state, the governing structure of Sri Lanka comprises of three branches. namely the Executive, the Legislature and the Judiciary. These are three independent institutions which are governed by the supreme law of the land which is currently the 1978 Constitution 19th Amendment. How these three entities should adhere to the governance of the state is clearly mentioned in the constitution. In basic definition:

The Executive which is lead by the Executive President who is the head of the state and of the government, is responsible for implementing and administering the laws passed by the legislature.

The Legislature which is the Parliament, is responsible for enacting the laws of the state.

The Judiciary which is the Supreme Court, is responsible for interpreting the Constitution and the laws enacted by the legislature.

As these three institutions are independent and their duties are mutually exclusive, the Constitution has provided required regulatory powers to safeguard the continuity of the system, to be specific the balance of the democracy. Due to these boundaries no institution subdues another and ultimately ensures these entities are following the Constitution. This protective measures prevents the tyranny among the institutions which is an inherent weakness of democracy as the classical Greek philosopher Plato discussed.

One of such key important limitations imposed by the Constitution is the power of interpreting the Constitution. In fact the legislature has no right to interpret the Constitution even though the legislature is the body which enacts it. This is clearly mentioned in the Article 125, Section 1 of the Constitution. Any matter which arises the constitutionality should be brought before the Supreme Court.

125. (1) The Supreme Court shall have sole and exclusive jurisdiction to hear and determine any question relating to the interpretation of the Constitution and accordingly, whenever any such question arises in the course of any proceedings in any other court or tribunal or other institution empowered by law to administer justice or to exercise judicial or quasi-judicial functions, such question shall forthwith be referred to the Supreme Court for determination. The Supreme Court may direct that further proceedings be stayed pending the determination of such question.

Therefore at this point, it is clear that any assertions of breaching the Constitution should be adjudicated by the Supreme Court, neither the Executive nor the Legislature is privileged to hold a proclamation.

Below is the proposal for the No Confidence Motion (NCM) submitted to the parliament yesterday (2018 November 14) by the JVP[1].


මෙම ගරු සභාව,

  1. අතිගරු ජනාධිපතිවරයා විසින් ප්‍රකාශයට පත්කල 2018 ඔක්තෝබර් 26 වන දින හා අංක 2094/43, 2094/43 A සහ 2094/44 දරණ අති විශේෂ ගැසට් නිවේදන සහ එහි සදහන් නියෝගයන් සහ පත්කිරීම් ආණ්ඩුක්‍රම ව්‍යවස්ථාවට පටහැනි වන බවත්, නීතිය ඉදිරියේ ශුන්‍ය සහ බල රහිත බවත්, නීතිය ඉදිරියේ කිසිදු බලයක් හෝ වලංගු භාවයක් නොමැති බවත්,
  2. ඉහත සදහන් හේතු නිසා 2018 ඔක්තෝබර් 26 වන දා හෝ ඉන් පසුව හෝ පත් කල අග්‍රාමාත්‍ය මහින්ද රාජපක්ෂ මහතා හා කැබිනට් මණ්ඩලය හා එලෙස පත් කරන ලද්දාවූ ආණ්ඩුව කෙරෙහි කිසිදු විශ්වාසයක් නොමැති බවත්,

යෝජනා කර සිටී.

In the above proposal, it lacks the adjudication of the Supreme Court but supported by an assertion of the proposers. According to the Article 125 section 1 of the Constitution, nobody interprets the Constitution but the Supreme Court. In such grounds the proposal is merely based on personal interests of some MPs, not to mention the majority of 122 MPs. Therefore the proposal itself has no legal standing form the inception and cannot be voted for or against. The proposal is null and void. And specially the MPs were violating the Article 125 section 1 of the Constitution as they were testifying their own assertions and including it in a proposal to the house. In the contatary the speaker has accepted an incomplete document which lacks constitutional adherence. Both are serious misconducts and setting adverse examples.

The proper procedure was to seek the Supreme Court opinion over the incident and present the NCM which upholds the democracy as laid by the supreme law of the state.



Attribution – The featured image used in this article is attributed to Vikalpa | Groundviews | Maatram | CPA from Sri Lanka, courtesy of This file is licensed under the Creative Commons Attribution 2.0 Generic license.

Disclaimer – The writer is neither an expert on Constitutional law nor a counsellor at law. The content is based on the observations of the states political status quo and the personal opinion of the writer.

Copyright Waiver No Copyright, This article was released in Public Domain except the featuring image in this article. This work has been identified as being free of known restrictions under copyright law, including all related and neighboring rights. You can copy, modify, distribute and perform the work, even for commercial purposes, all without asking permission.

Inoculation the Balance of the Democracy

Countries in which Presidential system is in place, enjoy the separation of powers. Democratic Socialist Republic of Sri Lanka is one of such states. Basically the branches of separation are the Executive, the Legislature and the Judiciary. The executive president enjoys number of privileges as the head of the state and the head of the government. One of them is the immunity over the jurisdictions [Article 35 of the Constitution]. It is vested by the constitution itself. At the same time, the constitution proclaims that nobody is above the law [Article 12 Section 1 in the Constitution].

If the facts hold as above, then how can the Supreme Court which is the Judicial branch of the separation of power can go against the executive presidency.

In order to understand the dynamics, the Article 35 of the Constitution should be closely examined.  The Executive president cannot be indicted for civil or criminal proceedings as long as he/ she holds the office. Even though it grants a supremacy over the presidency, the constitution itself places few boundaries. According to the Article 126 Section 1 of the Constitution, the Supreme Court possesses the jurisdiction against the matters which infringe the fundamental rights established by the supreme law of the state which is the Constitution [Chapter III and IV of the Constitution]. In fact this clause resides since the inception of the 1978 Constitution. The root of the infringement could be an executive or administrative action. According to the Article 126 Section 5 of the Constitution the hearing should be concluded within 2 months.

This is how the executive presidency has been protected, as a result the president is not capable of ruling against the Constitution.

President’s orders are often termed as Executive Orders, well famoused in the United States of America. The Supreme Court had issued restraining orders for Trump’s Executive Order on travel policies at the beginning of his term is one of the recent examples. Recently CNN reports that they are planning to sue the President for banning Jim Acosta[1]. 

In Sri Lanka, the extraordinary gazette no 2096/70, issued for dissolving the Parliament is being contested before the Supreme Court[2]. In such a background, the writer finds the statements of the judicial supremacy/ immunity of the executive presidency is fatuous. The Supreme Court has the absolute powers to make sure the executive is within the boundaries of the supreme law of the state. Challenging the order issued by the president before the Supreme Court is the righteous move.



Disclaimer : The sole objective of this article is discussing the balance of the democracy hence the purpose is purely educational. This neither a discussion of an ongoing proceeding nor an opinion on it.