Arpit Mishra

Author
Arpit Mishra

Blogs
From dorm rooms to boardrooms, Arpit has built a career connecting young talent to opportunity. Their writing brings fresh, student-centric views on tech hiring and early careers.
author’s Articles

Insights & Stories by Arpit Mishra

Arpit Mishra explores what today’s grads want from work—and how recruiters can meet them halfway. Expect a mix of optimism, strategy, and sharp tips.
Clear all
Thank you! Your submission has been received!
Oops! Something went wrong while submitting the form.
Filter
Filter

15 best computer programming languages for beginners

Computer programming languages are often confusing for beginners, each with its own dialect and vernacular.

And every programming language has its own set of syntax and code to write. So how to chose a programming language to learn?

With computer programming languages ranging from 67-year-old Assembly language to the young Ruby language.

And you know what? Every language has its own presence in the computer programming world.

Even a brief glance at the list of programming languages available gives one a nightmare. But for now, knowing the top programming languages to learn will help.

But then which is the best computer programming languages for beginners? or which programming language to learn first?

I decided to shortlist the most commonly used computer programming languages for beginners and make a complete guide to it.

Hope the list helps you.

Check this computer programming deck for dummies before you read further about each of them in detail.

This will help you with a quick glance over each programming language.

Programming language infographic, computer programming infographic, infographic programming, computer programming languages for beginners, Guide to computer programming languages, Programming languages guide, Dummies guide to programming languages, Dummies guide to computer programming languages, Learn C, Learn computer programming languages, How to begin with computer programming languages, which programming languages should I begin with, Which is the best programming languages, 15 Best programming languages to learn for beginners, programming languages to learn for beginners, 15 programming languages to learn first

  • Assembly Language

    Learn more

    It was developed as a shorthand to machine language so that you don’t only have to remember 0’s and 1’s while coding.

    Today, Assembly languages are used to access a specialized processor or address critical performance issues by direct hardware manipulation.

    Typically, they are used in low-level embedded and real-time systems.

    If you want to program a processor, the assembly language may not be necessary, but it is invaluable.

    Major Organization Users: IBM, Apple

  • C++ Language

    Learn more

    It is a middle-level, general purpose language. C++ brings in the feature of being object-oriented compared with its predecessor C.

    C++ is popular in areas where graphical representation is required like that for Windows and Macintosh.

    C++ has a rich function library and is a highly portable language.

    Here is beginners guide to C++ - C++ language tutorial

    Major Organization Users: Google, Mozilla, Firefox, Winamp, Adobe Software, Amazon, Lockheed Martin

  • C Language

    Learn more

    It is a general-purpose programming language.

    C provides a construct to map assembly language to C and has been most popularly used for operations which had been previously coded in assembly languages, including operating systems.

    C is one of the most widely used languages and has been a great influence on its successors.

    Major Organization Users: Microsoft, Apple, Oracle, Cisco, Raytheon

  • Objective C

    Learn more

    It is a general-purpose, object-oriented programming language that adds Smalltalk-style messaging in C language.

    Objective-C is one of the basic language used by Apple products and had been used in the development of iOS and OSX operating systems.

    Major Organization Users: Apple

  • MATLAB

    Learn more

    It integrates computation and programming in an easy-to-use environment where most of the objectives are represented by mathematical notation.

    Matlab is a high-performance language and is typically used for mathematical computation and algorithm development.

    Major Organization Users: GE, Continental, Robert Bosch, Honeywell, Mercedes-Benz

  • PERL

    Learn more

    It is a scripting language with syntax similar to C and has many features of UNIX. Programs written in Perl are called Perl script.

    Perl is an interpreted (not compiled) language that can optionally be compiled just before execution into either C code or cross-platform bytecode.

    Major Organizations Users: Apple, Yahoo, BBC, IMDB

  • R

    Learn more

    It is a dialect of S language. R language is used for statistical computing and graphics.

    R is commonly used by statisticians and data miners for statistical and analysis.

    R comes as a free software package and is available under GNU General public license.

    Major Organizations Users: Google, GE, Dropbox

  • Visual Basic

    Learn more

    It is a high-level language implemented on the .NET framework. VB was derived from BASIC, a user-friendly language designed for beginners.

    It enables the rapid application development (RAD) of graphical user interface (GUI) applications and access to databases using objects.

    Major Organizations Users: Microsoft

  • PYTHON

    Learn more

    It is another interpreted language on this list. Developed as a general purpose language.

    Python design emphasizes code readability and helps the user express in fewer lines of codes.

    Major Organizations Users: Google, Pinterest, Instagram, YouTube, DropBox, NASA, ESRI

  • PHP

    Learn more

    It is a scripting language used by users to create dynamic pages, which can be used further for transferring and submitting information on the web.

    You can connect with servers, databases, and external websites based on IP address or information available.

    PHP is one of the most commonly used scripting languages by web developers.

    Major Organizations Users: Facebook, Google, GE, Wordpress

  • Javascript

    Learn more

    It is a high-level programming language. Along with HTML and CSS, Javascript is one of the core languages in the development of World Wide Web content production.

    Most of the websites support javascript without needing plugins.

    Javascript is also used in the non-web-based application like PDF and desktop widgets.

    Major Organizations Users: WordPress, Soundcloud, Linkedin, Groupon, Yahoo

  • C#

    Learn more

    It is another language in the list of C languages. C# (pronounced as C-Sharp) is an object-oriented and component-oriented programming language.

    C# is one of the programming languages developed for common language infrastructure.

    Developers working on Windows prefer C# for developing applications and it turns out that C# is a big competitor to Java.

    Major Organizations Users: Any company dealing extensively with Windows

  • CSS

    Learn more

    CSS or Cascading style sheet is a style sheet language used for describing the presentation of documentation written in a markup language. Though often used for visual style up and user interface for HTML. CSS is a technology used by the most website to create visually engaging pages.

    Major Organizations Users: Apple, CyberCoders, Apex Systems

  • Java

    Learn more

    It is often called the best programming language, amidst much debate. Java is a high-level language. It was intended to be “write once, run anywhere (WORA),” i.e., once the code is written, it could be used on any platform that uses Java. Java is used for client-server applications with more than 9 million developers using the platform.

    Major Organizations Users: V2COM, Eclipse Information Technologies, eBay, Eurotech

  • Ruby

    Learn more

    It is one of the younger programming languages.

    Developed to increase productivity, Ruby is a server interpreted, non-compiled programming language.

    Ruby is used with Ruby on Rails for framework development.

    Major Organizations Users: Cybercoders, Amazon, EMC, Bloomberg

  • SQL

    Learn more

    Though not considered a programming language listed under Alan Turing test of programming language, for now, SQL is one of the recruiter's favorite programming language.

    SQL, or Structured Query Language, is a special-purpose, domain-specific programming language used in programming and managing the database (DBMS).

    Often described as a declarative language, SQL also includes procedural elements.

    Despite being a standard in ANSI since 1986, most SQL code is not portable to among different database systems.

    Major Organizations Users: Facebook, Google, Adobe, Alcatel-Lucent

You can also read about these 13 rare and underrated programming skills to learn here

Breadth First Search example (BFS) - How GPS navigation works

There are differences in the route which I usually take and the one which GPS shows as the shortest, probably due to the algorithms used. I learned from my graph theory data structure classes that (BFS) Breadth First search example is GPS navigation and digital maps. I tried looking for the possible use of Algorithms (Breadth First Search example or A* application) used in GPS navigation on the web, but I couldn’t find a lot of details. So here is how Breadth First Search is used in real life application like GPS.

Let’s first understand working of GPS navigation

Digital maps, unlike humans, see streets as a bunch of nodes. The 2.6-mile road from the Columbus Circle station (59 st) to Cathedral Pkwy (110 st) is called Central Park West. We (humans) consider this road a single entity (You may divide it into few more segments based on metro stations or intersections, but not more than that).

Central Park West Map

But a GPS navigation or any other digital map divides it into hundreds of segments, with some only 24 meters long. A GPS looks at this street as a graph divided into vertices and edges.

Graph Representation of Streets

Considering this, there is a lot of data to be covered and calculated while finding the shortest path.

What is a graph?

A graph usually looks like the image below and is made up of vertices and edges (represented by lines and circles, respectively).

Graph Nodes and Edges

The objective of a graph is to represent a problem as a set of points that are connected in various ways using edges. With the help of such graphs, we tend to solve our problems by applying various algorithms.

Let’s take an example to understand better.

Facebook is a good example to understand graph theory.

Facebook has millions of users. If a person needs to find a friend, he can use an array and search. But that would take a lot of time and memory to search for so many people, making the problem quite complex.

But if the same scenario is represented using a graph, the problems tend to get solved easily. With a graph, you know that these two people are actually friends (Though real-life scenarios are not exactly that simple!). Check this video on how graph theory is used in social networks:

Graph theories are frequently used in various other fields, such as maps, e-commerce, and computer games.

Before we go further down this road, read this detailed article about graph theory, which explains other important aspects of Graphs such as Directed, Undirected, Cycle or Loop, and Matrix.

What’s the difference between a Graph and a Tree?

A tree is a special type of graph, i.e., a minimal graph, where there is only one path between two vertices.

So what is Breadth First Search and how does it work?

Depth First Search (DFS) and Breadth First Search (BFS) are algorithms, or in simple terms, they are methods to traverse a graph.

Before I explain Breadth First Search, consider this example.

Take a graph with 13 nodes. When Breadth First Search is applied to this graph, the algorithm traverses from node 1 to node 2 and then to nodes 3, 4, 5, 6 (in green) and so on in the given order.

If you consider 1 (in red) as the first node, you observe that Breadth First Search gradually moves outward, considering each neighboring node first.

BFS Example on Graph

This eventually brings us to the accepted definition of the Breadth First Search algorithm:

“Breadth First search (BFS) is an algorithm for traversing or searching tree or graph data structures. It starts at the tree root (or some arbitrary node of a graph, sometimes referred to as a "search key") and explores the neighbor nodes first, before moving to the next level neighbors.”

Graph Traversal in Maps

Take a look at this simple “Gridworld” which is used for various graph traversal algorithms. Your digital map considers your world a similar grid, which is made up of intersections connected to each other.

Grid World

Now for the grid shown, there could be N number of ways to traverse from point A to point P.

Following are two of these N ways in which one can travel from point A to point P.

Multiple Gridworld Paths

So how does an algorithm decide which the shortest way to reach a destination is? Graph Traversal Algorithms!

The Breadth First Search algorithm looks at the map as we do; it just can’t perceive it completely. When you have to travel from one destination to another, you draw a line from point A to point B, and then chose the road closest to that line. Algorithms repeat the same method choosing the node nearest to the intersection points, eventually selecting the route with the shortest length.

Let’s take a simple example of GridWorld given above and try solving it using Breadth First Search. Assume you need to travel from location A to location P.

Note: Every vertex in the image is given a number, which is the total distance from the source and an alphabet which represents the previous node.

Breadth First Search for GridWorld

Step 1 - Visit neighboring nodes to A, i.e, B, E, and F. The vertex to B would become 1-A and since E and F are also at an equal distance as B, hence vertices to both E and F from A, could be denoted as 1-A too.

BFS Step 1

Step 2 - Mark "A" as visited. Use B as the source node. Visit adjacent nodes to B: C (2B) and G (2B). Node F is already considered.

BFS Step 2

Step 3 - Visit neighboring nodes of E: I (2E) and J (2E), and mark E as visited.

Step 4 - Visit neighbors of F: K (2F). F is marked as visited.

Step 5 - Repeat until all nodes are visited.

Step 6 - The shortest route from A to P is diagonal with distance 3.

Shortest BFS Path

Removing unused vertices creates a minimum spanning tree, where each node is connected to at least one vertex.

But in real scenarios, diagonal movement isn't always possible. Let's analyze GridWorld again, this time disallowing diagonal moves.

Step 1 - Source node A: visit B(1A), E (1A). Mark A as visited.

BFS No Diagonal Step 1

Step 2 - Node B: visit C (2B) and F (2B), mark B as visited.

Step 3 - Node E: visit I (2E), mark E as visited.

BFS No Diagonal Step 3

Step 4 - Continue visiting all nodes and marking visited.

Step 5 - Remove unconnected vertices, and build the minimum spanning tree.

Step 6 - Highlight shortest path A to P with a distance of 6.

Shortest BFS Path Without Diagonal

You now understand why GPS navigation didn't suggest the path A, E, I, M, N, O, P or A,B,C, D, H, L, P though they were equidistant.

Once you've understood the way GPS works, you’d wish the world could be a simple Grid! But to a programmer's disappointment, it isn’t. Hence, for a GPS, distance is not the only factor in choosing a route, rather elapsed time, the speed limit on a route, live traffic update, the number of stop signals all has to be taken into consideration. That’s why you would find your GPS occasionally suggesting winding state highways to travel instead of the usual national highways.

Most of the GPS or digital maps have evolved over Breadth First Search to A* algorithm (You can read more about A* algorithm - Here) due to better complexity over a period of time.

Yet, GPS is one of the most amazing devices. Connected to satellites 12,000 miles above the planet, it calculates your position in real time with more than 50,00,000 possibilities for a particular route.

Watch the video explaining the Use of Breadth first search in GPS navigation here:

Tower of Hanoi recursion game algorithm explained

Tower of Hanoi game is a puzzle invented by French mathematician Édouard Lucas in 1883.

History of Tower of Hanoi

There is a story about an ancient temple in India (Some say it’s in Vietnam – hence the name Hanoi) has a large room with three towers surrounded by 64 golden disks.

These disks are continuously moved by priests in the temple. According to a prophecy, when the last move of the puzzle is completed the world will end.

These priests acting on the prophecy, follow the immutable rule by Lord Brahma of moving these disk one at a time.

Hence this puzzle is often called Tower of Brahma puzzle.

Tower of Hanoi is one of the classic problems to look at if you want to learn recursion.

It is good to understand how recursive solutions are arrived at and how parameters for this recursion are implemented.

What is the game of Tower of Hanoi?

Tower of Hanoi consists of three pegs or towers with n disks placed one over the other.

The objective of the puzzle is to move the stack to another peg following these simple rules.

  1. Only one disk can be moved at a time.
  2. No disk can be placed on top of the smaller disk.

Before we proceed, let’s understand Recursion –

What is Recursion?

When a function calls itself, it’s called Recursion.

It will be easier for those who have seen the movie Inception.

Leonardo had a dream, in that dream he had another dream, in that dream he had yet another dream, and that goes on.

So it’s like there is a function called dream()dream(), and we are just calling it in itself.

function dream()
    print "Dreaming"
    dream()

Recursion is useful in solving problems which can be broken down into smaller problems of the same kind.

But when it comes to solving problems using Recursion there are several things to be taken care of.

Let’s take a simple example and try to understand those.

Following is the pseudo code of finding the factorial of a given number XX using recursion.

function factorial(x)
    if x is 0                    // base case
        return 1
    return x*factorial(x-1)       // break into smaller problem(s)

Detailed explanation to Recursion can be found – Here

Tower of Hanoi algorithm explained

Let’s try to solve a puzzle – Tower of Hanoi using recursion.

Take an example with 2 disks: Disk 1 on top of Disk 2 at peg A. The target is to move both these disks to peg B.

Looks simple, Right!

Move Disk 1 from peg A to peg C. Then move disk 2 from peg A to peg B and, finally, move disk 1 from peg C to peg B.

This solution takes 3 steps.

You can easily move this stack from peg B to any other peg using these 3 steps.

But what if we have 3 disks – 1,2, and 3 stacked in peg A.

To move the stack to peg B you would have to expose disk 3 and to do that disk 1 and 2 have to be moved to peg C.

So by ensuring that you do not break the rules, using the above subsets of 3 steps in the previous case, you would move disk 1 and 2 to peg C, leaving disk 3 exposed with no disk above it.

https://www.hackerearth.com/blog/become-better-developer

Now to solve the problem, recursively move disk 3 from peg A to peg B.

Then disk 1 from peg C to peg A. After which disk 2 can be moved above disk 3 at peg B.

The puzzle is finally completed by moving disk 1 from peg A over disk 2 and 3 at peg B.


Would you like to get updates once a month on our latest articles? We won’t spam, we promise. Subscribe now to The HackerEarth Blog!


What if you have 4 disks?

  • Recursively solve the problem of moving disk 1,2, and 3 from peg A to peg C
  • Move disk 4 from A to C
  • Recursively solve the problem of moving disk 1,2 and 3 from peg C to peg B

Eventually, you figure out that there is some pattern to the puzzle and with each increment in disks, the pattern could be followed recursively.

While the 3-disk puzzle required 7 steps. 4-disk requires 7+1+7 = 15 steps to be solved.

Check the GIF here for 4 disks

  • Create a function Tower with int ‘a’ – for number of disks, char ‘from’ – for from peg, char ‘aux’ – for a secondary peg, char ‘to’ – for destination peg
  • Put ‘if’ loop
  • If (a=1) i.e. if number of disk = 1, move it from ‘initial peg’ to the ‘destination peg’
  • Else, call function tower for ‘a-1’ i.e. the number of disk -1, recall function tower for n-1 disk and move it ‘from’ to ‘to’
  • Recall function again using recursion until an or number of the disk is 1.
void tower(int a,char from,char aux,char to){
    if(a==1){
       cout<<"\t\tMove disc 1 from "<<from<<" to "<<to<<"\n";
       return;
    }
    else{
       tower(a-1,from,to,aux);
       cout<<"\t\tMove disc "<<a<<" from "<<from<<" to "<<to<<"\n";
       tower(a-1,aux,from,to);
    }
}

Call the function ‘tower’ in the main program

void main(){
     clrscr();
     int n;
     cout<<"\n\t\t*****Tower of Hanoi*****\n";
     cout<<"\t\tEnter number of discs : ";
     cin>>n;
     cout<<"\n\n";
     tower(n,'A','B','C');
     getch();
}

Tower of Hanoi maths explained

By now, you might have identified that to move N disks from one peg to another, you need 2N1.

So, the number of steps almost double every time you insert another disk in the stack.

Let us prove that the number of steps in 2N1

The question is what is the minimum number of moves(aN) required to move all the Ndisks to another peg.

Let’s look at a recursive solution

One can already see that a1=1,a2=3,a3)=7 and so on.

For a given N number of disks, the way to accomplish the task in a minimum number of steps is:

  1. Move the top N1 disks to an intermediate peg.
  2. Move the bottom disk to the destination peg.
  3. Finally, move the N1 disks from the intermediate peg to the destination peg.

Therefore, the recurrence relation for this puzzle would become:

a1=1,a2=3;aN=2aN1+1;N2

Tower of hanoi, recursion, algorithm , explained, Tower of hanoi explained, Recursion explained

Now one can solve this relation in an iteration as follows-

Tower of hanoi recursion explained, Tower of Hanoi, Tower of Hanoi recursion, Recursion explained, Tower of Hanoi explain

But what about the prophecy for the tower of Hanoi where the priests are using 64 disks?

Suppose that these priests are highly powerful and can move these massive disks at a speed of 1 per second per hour every day.

At this speed, they would need 2^64 -1 move to complete the task.

That is, 18,446,744,073,709,551,615 moves to complete, which would take about 580 billion years.

Considering our Milky Way is about 13.21 billion years old and our planet is only 5 billion years old, that is a lot of time for the prophecy to be true.

Tower of Hanoi dynamic programming problem

Now that you have understood the algorithm and reasoning behind the Tower of Hanoi problem, it’s time to take up a small assessment to test your understanding of the Tower of Hanoi

Tower of Hanoi recursion sample problem in C++

Tower of Hanoi is a common dynamic programming problem used in various competitive programming challenges.

Here is one such question from HackerEarth Challenge

Q. Bob and Alice like to play the game Tower of Hanoi. One day Alice challenges Bob to build the tallest tower from a set of disks of different height and radius. The Tower of Hanoi can be built by stacking disks on top of each other. To put disk A on top of disk B, the radius and height of A must be strictly smaller than those of B. Help Bob win the challenge.

Here is the Tower of Hanoi program using C++

#include <bits/stdc++.h>
#define lli long long
using namespace std;
lli dp[202];
int main()
{
  int t,n;
   lli x,y;
   cin >> t;
   assert(t<=10);
   while ( t-- ) {
      cin >> n;
     assert(n<=200);
       vector < pair<lli,lli> > v;
       for ( int i = 0; i < n; i++ ) {
           cin >> x >> y;
           assert(x<=1000000000);
           assert(y<=1000000000);
           v.push_back(make_pair(x,y));
       }
       sort(v.begin(),v.end());
       dp[0] = v[0].second;
       lli ans = v[0].second;
       for ( int i = 1; i < n; i++ ) {
           dp[i] = v[i].second;
           for ( int j = 0; j < i; j++ ) {
               if ( v[i].second > v[j].second && v[i].first > v[j].first ) dp[i] = max(dp[i], dp[j]+v[i].second);
         }
  ans = max(ans, dp[i]);
       }
       cout << ans << endl;
   }
   return 0;
}

Time to end the world on a doomsday or by Tower of Hanoi all can be calculated by mathematics.

Mathematics holds the solution for most of the complex problems, from football betting to banking.

Practice and learn more such algorithms and on CodeMonk and participate in HackerEarth challenges.

Subscribe now for more such article on Algorithms.

Dijkstra's Banker's algorithm detailed explanation

Even after reading many articles on Banker’s algorithm and Europe’s deadlock several times, I couldn’t get what they were about.

I didn’t understand how an algorithm could have solved with the debt crisis.

I realized I would have to go back to the basics of banking and figure out answers to these:

How do banks work? How do banks decide the loan amount? What is the Banker’s algorithm?

We will begin with the Banker’s algorithm, which will help you understand banking and “Deadlock.”

What is banker’s algorithm?

The Banker’s algorithm sometimes referred to as avoidance algorithm or Deadlock algorithm was developed by Edsger Dijkstra (another of Dijkstra’s algorithms!).

It tests the safety of allocation of predetermined maximum possible resources and then makes states to check the deadlock condition. (Wikipedia)

Banker’s algorithm explained

Let’s say you’ve got three friends (Chandler, Ross, and Joey) who need a loan to tide them over for a bit.

You have $24 with you.

Chandler needs $8 dollars, Ross needs $13, and Joey needs $10.

You already lent $6 to Chandler, $8 to Ross, and $7 to Joey.

So you are left with $24 – $21 (6+8+7) = $3

Even after giving $6 to Chandler, he still needs $2.Similarly, Ross needs $5 more and Joey $3.

Until they get the amount they need, they can neither do whatever tasks they have to nor return the amount they borrowed. (Like a true friend!)

You can pay $2 to Chandler, and wait for him to get his work done and then get back the entire $8.

Or, you can pay $3 to Joey and wait for him to pay you back after his task is done.deadlock, Banker's algorithm, Dijkstra's algorithm

You can’t pay Ross because he needs $5 and you don’t have enough.

You can pay him once Chandler or Joey returns the borrowed amount after their work is done.

This state is termed as the safe state, where everyone’s task is completed and, eventually, you get all your money back.

The second scenario –Deadlock explained

Knowing Ross needs $10 urgently, instead of giving $8, you end up giving him $10.

And you are left with only $1.

In this state, Chandler still needs $2 more, Ross needs $3 more, and Joey still needs $3 more, but now you don’t have enough money to give them and until they complete the tasks they need the money for, no money will be transferred back to you.

This kind of situation is called the Unsafe state or Deadlock state, which is solved using Banker’s Algorithm.

Let’s get back to the previous safe state.

You give $2 to Chandler and let him complete his work.

He returns your $8 which leaves you with $9. Out of this $9, you can give $5 to Ross and let him finish his task with total $13 and then return the amount to you, which can be forwarded to Joey to eventually let him complete his task.

(Once all the tasks are done, you can take Ross and Joey to Central Perk for not giving them a priority.)

The goal of the Banker’s algorithm is to handle all requests without entering into the unsafe state, also called a deadlock.

The moneylender is left with not enough money to pay the borrower and none of the jobs are complete due to insufficient funds, leaving incomplete tasks and cash stuck as bad debt.

It’s called the Banker’s algorithm because it could be used in the banking system so that banks never run out of resources and always stay in a safe state.

Banker’s Algorithm

For the banker’s algorithm to work, it should know three things:

  1. How much of each resource each person could maximum request [MAX]
  2. How much of each resource each person currently holds [Allocated]
  3. How much of each resource is available in the system for each person [Available]

So we need MAX and REQUEST.

If REQUEST is given MAX = ALLOCATED + REQUEST

NEED = MAX – ALLOCATED

A resource can be allocated only for a condition.

REQUEST<= AVAILABLE or else it waits until resources are available.

Let ‘n’ be the number of processes in the system and ‘mbe the number of resource types.

  • Available – It is a 1D array of size’m’. Available [j] = k means there are k occurrences of resource type Rj.
  • Maximum – It is a 2D array of size ‘m*n’ which represents maximum demand of a section. Max[i,j] = k means that a process i can maximum demand ‘k’ amount of resources.
  • Allocated – It is a 2D array of size ‘m*n’ which represents the number of resources allocated to each process. Allocation [i,j] =k means that a process is allocated ‘k’ amount of resources.
  • Need – 2D array of size ‘m*n’. Need [i,j] = k means a maximum resource that could be allocated.
    • Need [i,j] = Max [i,j] – Allocation[i,j]

Take another Banker’s Algorithm example in the form of the table below

Where you have 4 processes, and 3 resources (A, B, C) to be allocated.

Process
Allocated Maximum Available Need (Maximum Allocated)
A B C A B C A B C A B C
P1 0 1 0 7 5 3 3 3 2 7 4 3
P2 2 0 0 3 2 2 1 2 2
P3 4 0 1 9 0 4 5 0 3
P4 2 1 1 2 2 2 0 1 1

Need P2<Available, so we allocate resources to P2 first.

After P2 completion the table would look as

Process
Allocated Maximum Available Need (Maximum Allocated)
A B C A B C A B C A B C
P1 0 1 0 7 5 3 5 3 2 7 4 3
P3 4 0 1 9 0 4 5 0 3
P4 2 1 1 2 2 2 0 1 1

Need P4<Available, so we allocate resources to P4.

After P4 completion

Process
Allocated Maximum Available Need (Maximum Allocated)
A B C A B C A B C A B C
P1 0 1 0 7 5 3 7 4 3 7 4 3
P3 4 0 1 9 0 4 5 0 3

And P3 will be allocated before P1, which gives us the sequence P2, P4, P3, and P1 without getting into deadlock.

A state is considered safe if it is able to finish all processing tasks.

Banker’s algorithm using C++

#include <iostream>
#define MAX 20
using namespace std;

class bankers
{
    private:
        int al[MAX][MAX],m[MAX][MAX],n[MAX][MAX],avail[MAX];
        int nop,nor,k,result[MAX],pnum,work[MAX],finish[MAX];

    public:
        bankers();
        void input();
        void method();
        int search(int);
        void display();
};

bankers::bankers()
{
    k=0;
    for(int i=0;i<MAX;i++)
    {
        for(int j=0;j<MAX;j++)
        {
            al[i][j]=0;
            m[i][j]=0;
            n[i][j]=0;
        }
        avail[i]=0;
        result[i]=0;
        finish[i]=0;
    }
}

void bankers::input()
{
    int i,j;
    cout << "Enter the number of processes:";
    cin >> nop;
    cout << "Enter the number of resources:";
    cin >> nor;
    cout << "Enter the allocated resources for each process: " << endl;
    for(i=0;i<nop;i++)
    {
        cout<<"\nProcess "<<i;
        for(j=0;j<nor;j++)
        {
            cout<<"\nResource "<<j<<":";
            cin>>al[i][j];
        }
    }
    cout<<"Enter the maximum resources that are needed for each process: "<<endl;
    for(i=0;i<nop;i++)
    {
        cout<<"\nProcess "<<i;
        for(j=0;j<nor;j++)
        {
            cout<<"\nResouce "<<j<<":";
            cin>>m[i][j];
            n[i][j]=m[i][j]-al[i][j];
        }
    }
    cout << "Enter the currently available resources in the system: ";
    for(j=0;j<nor;j++)
    {
        cout<<"Resource "<<j<<":";
        cin>>avail[j];
        work[j]=-1;
    }
    for(i=0;i<nop;i++)
        finish[i]=0;
}

void bankers::method()
{
    int i=0,j,flag;
    while(1)
    {
        if(finish[i]==0)
        {
            pnum =search(i);
            if(pnum!=-1)
            {
                result[k++]=i;
                finish[i]=1;
                for(j=0;j<nor;j++)
                {
                    avail[j]=avail[j]+al[i][j];
                }
            }
        }
        i++;
        if(i==nop)
        {
            flag=0;
            for(j=0;j<nor;j++)
                if(avail[j]!=work[j])

            flag=1;
            for(j=0;j<nor;j++)
                work[j]=avail[j];

            if(flag==0)
                break;
            else
                i=0;
        }
    }
}

int bankers::search(int i)
{
    int j;
    for(j=0;j<nor;j++)
        if(n[i][j]>avail[j])
            return -1;
    return 0;
}

void bankers::display()
{
    int i,j;
    cout<<endl<<"OUTPUT:";
    cout<<endl<<"========";
    cout<<endl<<"PROCESS\t     ALLOTED\t     MAXIMUM\t     NEED";
    for(i=0;i<nop;i++)
    {
        cout<<"\nP"<<i+1<<"\t     ";
        for(j=0;j<nor;j++)
        {
            cout<<al[i][j]<<"  ";
        }
        cout<<"\t     ";
        for (j=0;j<nor;j++)
        {
            cout<<m[i][j]<<"  ";
        }
        cout<<"\t     ";
        for(j=0;j<nor;j++ )
        {
            cout<<n[i][j]<<"  ";
        }
    }
    cout<<"\nThe sequence of the safe processes are: \n";
    for(i=0;i<k;i++)
    {
        int temp = result[i]+1 ;
        cout<<"P"<<temp<<" ";
    }
    cout<<"\nThe sequence of unsafe processes are: \n";
    int flg=0;
    for (i=0;i<nop;i++)
    {
        if(finish[i]==0)
        {
        flg=1;
        }
        cout<<"P"<<i<<" ";
    }
    cout<<endl<<"RESULT:";
    cout<<endl<<"=======";
    if(flg==1)
        cout<<endl<<"The system is not in safe state and deadlock may occur!!";
    else
        cout<<endl<<"The system is in safe state and deadlock will not occur!!";
}

int main()
{
    cout<<" DEADLOCK BANKER’S ALGORITHM "<<endl;
    bankers B;
    B.input ( );
    B.method ( );
    B.display ( );
}

If you understood the process, congratulations on being a non-certified banker of the nation!

How football betting odds work using Poisson distribution

Toward the end of the 19th century, Russia-born Polish economist, Ladislaus Bortkiewicz came up with a strategy to predict the incidence of deaths among Prussian soldiers from horse kicks.

And he did this how? He applied the Poisson distribution. It ended becoming a famous example by the way.

Fast forward a bit...

Poisson distribution can be used in many scenarios—importantly and interestingly in betting.

Sports betting is a global phenomenon, and it is estimated that this industry is worth between $700bn and $1tn globally.

And football betting is most popular among all sports.

But how does football betting odds work? how are football betting odds calculated?

It's difficult to believe that a simple mathematical equation - Poisson distribution is used to calculate the odds for a football match.

Betting on a team winning or losing is done based on the calculation explaining the sports betting across a globe.

What is 'Football betting odds' and how they define bets?

[caption id="attachment_5252" align="aligncenter" width="911"]Football betting odds, How are football betting odds calculated, Football betting explained using Poisson distribution, How football betting works ,Poisson distribution, How football betting is done, how is poisson equation used in football betting, Manchester united vs Manchester city, How do I bet on football, What are football odds Image Source: Bet365[/caption]

If you've ever tried placing a few pounds on your favorite team, you would have noticed these confusing numbers in front of you.

These numbers are called 'odds' and they define the probabilities of each possible outcome in an event.

The higher the value of these numbers, the less probable that particular event is.

Take the Real Madrid vs Roma match above as an example.

Since the probability of Madrid winning is higher, the odds against them winning is just 1.40. A draw, which is more unlikely, has odds of 4.75.

And the odds of a highly unlikely Roma win in 7.00.



How do these numbers impact your bet amount and their returns?

Simple. In the above example, if you bet 1 pound on a Real Madrid win and win the bet, you get back a total of 1.40 pounds (inclusive of the 1 pound that you originally bet).

Which is why winning bets on more unlikely events (like a Roma victory) gets you bigger returns.

In this case, you would have got back 7 pounds for every pound you bet on Roma if they ended up winning.

Let us now see how do bookmakers calculate football betting odds using a simple Poisson Distribution equation.

What is Poisson distribution?

“Poisson distribution is the probability of the number of events that occur in a given interval when the expected number of events is known and the events occur independently of one another.

For instance, suppose you sit in a park for a few days and count the number of people who come to the park in a black T-shirt.

Using Poisson distribution, you can guess if the number of people coming to the park on a specific day in a black t-shirt will be 10, 11, etc.

But how does it relate to football betting odds prediction?

If you are able to calculate the average attack and defense strength of the teams in a match over a certain period and calculate the Poisson distribution, you will be able to predict the odds of one team performing over other.

But if the data is too long the data would be irrelevant, and if it's short, outliers might skew the data.

This means that not only external factors like transfers, home, and away from ground affect the odds, but also the duration of events which need to be taken into consideration for calculation.

Let’s see how football betting odds work using Poisson distribution

Before we apply Poisson, we need to get some mathematical figures.

Let’s use this method to calculate the odds for the Manchester United vs. Manchester City matches to be played on February 26, 2017.

First, we need to find the attack and defense strength of these teams.

Calculating Average Attack and Defense for prediction

Before we identify a particular team strength and weakness, we need to find the average strength and weakness of all teams in the last playing season.

This can be calculated by dividing the total goals scored in particular season by a total number of games played in a particular season.
  • Number of Goals Scored at Home / Number of Games = 203/380 = 0.534
  • Number of Goals Scored Away / Number of Games = 158/380 = 0.415
The difference from the values above gives the “Attack intensity” of a team.

We will also need an average of goals conceded to know the weakness, which is simply the inverse of goals scored.

The average number of goals conceded at Home = 0.415

The average number of goals conceded away = 0.534

This gives us the “ Defense intensity” of a team.

Now that we have the average strength and weakness of the teams, let's take a look at the stats for Manchester United and Manchester City in 2015.

Based on these stats, we can calculate the Poisson distribution for the teams playing in February 2017, where Manchester United is the away team and Manchester City is the home team.

[caption id="attachment_5249" align="aligncenter" width="3509"]Football betting odds, How are football betting odds calculated, Football betting explained using Poisson distribution, How football betting works ,Poisson distribution, How football betting is done, how is poisson equation used in football betting, Manchester united vs Manchester city, How do I bet on football, What are football odds 2015 Statistics - Manchester United vs Manchester City[/caption]

Predicting Manchester United Goals

Let’s see the possibility of Manchester United scoring at Manchester City’s home ground.

Number of Goals scored away = 22/19 = 1.15

Manchester United Goals = Number of goals scored/Season’s average goals scored away = 1.36/0.415 = 2.77

Manchester City Defense at home

This is calculated by dividing the number of goals conceded at home in the last season by the home team by the number of away games, which is 1.105 ( (21/19).

Manchester City Goals = Number of goals conceded/ Season’s average goals conceded = 1.105/0.415 = 2.66

Manchester United’s Goals = Manchester United’s Attack? Manchester City Defense? Average Number of Goals = 3.05

Predicting Manchester City Goals

Manchester City Attack at Home

Manchester City = Number of Goals scored home - 47/19 = 2.47

Manchester City Goals = Number of goals scored/Average goals scored in the last season =2.47/0.534 = 4.62

Manchester United Defense away

Take the number of goals conceded away last season by the away team and divide by the number of away games, which is equal to 1.05 ((20/19).

Manchester United Goals = Number of goals conceded/Average goals conceded in the last season =1.05/0.534 =1.966

Manchester City’s Goals = Manchester City’s Attack? Manchester United’s Defense? Average No. Goals = 1.10

Once we have the averages of Manchester United’s goals and Manchester City’s goals, we can use them to calculate the Poisson distribution for a number of goals scored by a particular team . (various goals possibilities).

Poisson Distribution betting – Predicting multiple match outcomes

The formula for Poisson distribution is:

P(x; ?) = (e-?) (?x) / x!

e = Euler’s constant = 2.718

! = Factorial

x = number of successes of the event

µ = mean distribution of the event

It can be coded as follows
#include <stdio.h>

#include <math.h>
double factorial(int n) {
int fact = 1;
for (int i = 1; i<=n; i++) fact *= i;
return fact;
}
float poisson(int r, float mean) {
return (exp((-1) * mean) * pow(mean,r))/factorial(r);
}
int main(int argc, char const *argv[])
{
printf("%f\n", poisson(1, 1.10));
return 0;
}

You can also use the Poisson Distribution Calculator for such equations.

Poisson Distribution prediction for match the between Manchester United and Manchester City

Goals 0 1 2 3 4 5
Manchester United 4.73% 14.44% 22.02% 22.39% 17.07% 10.41%
Manchester City 33.28% 36.61% 20.13% 7.38% 2.03% 0.44%
Probability 1.5 5.28 4.43 1.65 0.34 0.23

The possibility that Manchester United and Manchester City would score 1 goal each is 14.44% and 36.61% respectively.


From the above distribution table we can see that the possibility of Manchester city scoring no goal is 4.73 and that of Manchester United is 33.28.

Scoring 2 goals, each for Manchester United and Manchester City is 22.02% and 20.13% respectively.

The possibilities decrease as the number of goals increases to 4 and 5 goals by the individual team.

Taking these number into consideration, the odds of Manchester City winning is high if the number of goals in a match is 0 or 1. But if Manchester United is able to score 2 goals it’s the probability of winning the match increases.

So how is football betting odds made?

Based on the number by distribution table and the probability of these goals in a match, it is clear that a 1-1 draw has the highest possibility of 5.28, followed by 4.43 for a 2-2 draw. But the possibility of Manchester City winning with 1-0 or 2-1 also looks great.

Based on the previous match at Old Trafford, which is the home ground to Manchester United, Manchester City won by 2-1.

Not taking any sides (I support Algorithm), I would put my bet on 1-0 or 1-1 draw in favor of Manchester City.

The disadvantage of using the Poisson equation is that it doesn’t take into consideration external factors like the players/coach changed in transfer windows, the home ground factor, and injured players.

It helps you calculate the distribution only based on the averages of previous occurrences.

But then Elihu Feustel is one such person who makes a million dollars by betting using mathematical algorithms.

Top 7 most popular programming languages to learn

This blog has been picked up by the Economic Times Tech


Top Programming Languages to Learn

How do we determine the most preferred programming languages?

By “most preferred,” we don’t mean that Java is superior to C++ or Python is better than MATLAB. This analysis aims to highlight languages most in demand in the industry and most preferred by users.

Languages like C++, MATLAB, and Java are traditionally taught in technical institutes. However, industry requirements often differ from academic focus areas.

Languages to Learn:

  • Javascript
  • Java
  • Python
  • PHP
  • R
  • Matlab
  • Arduino
  • Swift

We pulled data from TIOBE, PYPL, Stack Overflow, GitHub, Indeed, Glassdoor, and our own platform at HackerEarth to identify which languages are preferred by developers and most sought after by companies.

TIOBE Index

TIOBE measures language popularity based on search engine queries. In 2016, Java remained #1, followed by C and C++. Visual Basic and Python scored higher than Javascript, and Assembly entered the top 10.

PYPL Index

PYPL ranks languages by how often tutorials are searched on Google. Java leads worldwide, while Python has grown rapidly in popularity. PHP has seen a decline.

Stack Overflow

Stack Overflow is one of the largest programming communities. Based on questions asked, Javascript tops the list, with Node.js and Angular gaining popularity while PHP declines.

GitHub

GitHub's Octoverse report showed Javascript as the most widely used language in repositories, outpacing other languages significantly.

HackerEarth

HackerEarth hosts thousands of coding challenges. Based on internal data from over 1 million users, the most used languages are C++, Java, Python, and C#.

Indeed

Indeed job listings show Java as the most in-demand, followed by PHP, C, and Javascript. R is also gaining traction.

Glassdoor

Glassdoor job data suggests Java remains top for job demand. Developers increasingly prefer R, while Python and Perl are rising in usage.

Recommended Programming Languages for 2017

  • Javascript: Essential for web development. Widely used for frontend interactions and effects.
  • Java: Backbone of Android apps and financial systems. Known for speed and performance.
  • R: Perfect for statistics and data analysis, with rising job market demand.
  • MATLAB: Regaining popularity due to analytics and scientific computing needs.
  • SQL: Crucial for database management. A must-have for data-focused roles.
  • Arduino: Vital for IoT and embedded systems, based on C/C++.
  • Swift: Apple's modern programming language for iOS/macOS app development.

These languages are expected to be in high demand in the near future. Others won’t vanish, but these are currently trending in the developer and employer communities.

Read more: Best countries to work as a developer