Posts

Showing posts from 2017

C++: Sorting Elements by Frequency

Image
We are going to write a program to sort the elements of an array by Frequency. If two elements have the same frequency of occurrence, then they are sorted in increasing order.

For eg. an array has { 2, 3, 2, 4, 5, 12, 12, 3, 4, 3 }

Then the output will be

3 3 3 2 2 4 4 12 12 5

Top 10 Web Sites Every Programmer Should Visit Daily

Image
Computer programming is one of the fastest growing field. If you are a programmer then you can be hired by a top tech company or you can also work as a freelancer and earn decent amount. So the question arises, how to learn to code ? Initially it was very difficult to learn programming. As there was no internet and you have to relay on books or your colleagues’ code. Now you can find tons of material on the internet. You can learn any computer programming language you want. I am going to tell you some sites which you should visit regularly. 

C++: STL Iterators

Image
Iterators arepointer like object which are used to point at the memory addressess of STL containers.

Properties of Iterator 

We can dereference an iterator in order to access the value towhich itrefers. That is, if p is an iterator, *pis defined.

We can assign one iterator to another. That is, if p and q areiterators, theexpression p = qis defined.

We can compare one iterator to another for equality. That is, if p and q are iterators, the expressions p == q and p != qare defined.

We can move an iterator through all the elements of a container. This canbe satisfied by defining ++p and p++ for an iterator p .

C++: Queue implementation using Linked List (Data Structure)

Image
We have already learnt about Queue int the post C++: Implementation of Queue using Array (Data Structure). Now we are implementing Queue using Linked List which we have learnt in C++: Singly Linked List using Template (Data Structure).

Here is the C++ program for implementing Queue using Linked List.

C++: Stack implementation using LinkedList (Data Structure)

Image
We have already learnt about Stack in the post C++: Implementation of Stack using Array (Data Structure).  Now we are implementing Stack using Linked List which we have learnt in C++: Singly Linked List using Template (Data Structure). The C++ program for implementing Stack using Linked List is very simple. For push() and pop() function we have to use insert() and deleteNode() function from Linked List program.

C++: Doubly Linked List using Template (Data Structure)

Image
A doubly linked list is a linked data structure that consists of a set of sequentially linked records called nodes. It consists of an attribute key and two other pointer attributes: next and prev.The two node links allow traversal of the list in either direction. While adding or removing a node in a doubly linked list requires changing more links than the same operations on a singly linked list, the operations are simpler and potentially more efficient (for nodes other than first nodes) because there is no need to keep track of the previous node during traversal or no need to traverse the list to find the previous node, so that its link can be modified. I would recommend you to read C++: Singly Linked List using Template (Data Structure)Because some of the methods used in the program are explained in this post.

C++: Singly Linked List using Template (Data Structure)

Image
A linked list is a data structure in which the objects are arranged in a linear order. Unlike an array, in which the linear order is determined by the array indices, the order in a linked list is determined by a pointer in each object. It has a group of nodes which together represents a sequence.  Under the simplest form, each node is composed of data and a reference (in other words, a link) to the next node in the sequence. 

Adavantages:

C++: Understanding Template

Image
C++’s class templates provide a better way to generate generic class declarations.Templates provide parameterized types—that is, they are capable of passing a type name as an argument to a recipe for building a class or a function. By feeding the type name int to a Queue template, for example, you can get the compiler to construct a Queue class for queuing ints.

Defining Template:
template <class Type>

C++: Implementation of Queue using Array (Data Structure)

Image
I have studied the algorithm for implementation of Queue from Introduction to Algorithm.
Queue is one of the elementary data structure. And as I had said earlier to learn programming we have understand Data Structure and Algorithm. Any programming language is just a tool to solve a problem.

Queue:

C++: Implementation of Stack using Array (Data Structure)

Image
I have studied the algorithm for stack implementation from Introduction to Algorithm.
We all want to learn programming languages. It is not just to learn to code. It is understanding algorithms, data structures their relationships and implementing them using a computer programming language. Stack is one of the elementry data structure.

Stack:

What is "namespace" and why do we use it?

Image
What is namespace?"In general, a namespace is a container for a set of identifiers   Namespaces provide a level of direction to specific identifiers, thus  making it possible to distinguish between identifiers with the same  exact name. " Or According to Wikipedia “In computer programming namespaces are typically employed for the purpose of grouping symbols and identifiers around a particular functionality and to avoid name collisionsbetween multiple identifiers that share the same name.”

C++: Program to Add and Multiply the digits of a Number

Image
We are the students of Computer Science and Engineering. We have to make many programs in various programming languages. We have to submit them in college assignment work or in school. Many times teacher just taught us the syntax of a language. The logic part has to be done on our own. I have written a post on it.How to improve logical thinking and problem solving skills?

C++ STL :Implementation of Counting sort (Sorting)

Image
I have studied this algorithm from Introduction to Algorithm.


Counting sortassumes that each of the n input elements is an integer in the range 0 to k, for some integer k means the maximum element in the array must be equal to k.

C++: Implementation of Quicksort (Sorting)

Image
I have studied this algorithm from Introduction to Algorithm and if you want to learn Data Structure and Algorithm I would strongly recommend this book.
Quicksort applies Divide and Conquer paradigm.
Divide: Partition the array A[p…r] into two subarrays A[p…q-1] and A[q+1…r] such that each element of A[p...q-1] is less than or equal to a[q] which is, in turn, less than or equal to each element of  A[q+1…r]
Conquer: Sort the two subarrays A[p…q-1] and A[q+1…r]by recursive calls to quicksort
Combine: Because the subarrays are already sorted, no work is needed to combine them the entire array A[p...r] is now sorted.

C++: Implementation of Heapsort (Sorting)

Image
I have written this code after studying Heapsort algorithm from Introduction to Algorithm

1. #include <iostream>
2. void max_heapify(int arr[],int i,int si){ 3. int largest, l=(2*i)+1, r=l+1;

4. if(l<si&&arr[l]>arr[i]) 5.    largest=l; 6. else 7.    largest=i;
8. if(r<si&&arr[r]>arr[largest]) 9.    largest=r;
10. if(largest!=i){ 11.    int temp=arr[i];

Cool Websites you don't know about...

Sci-Hub
This website allows you to download research papers free of cost. If you are a student/researcher you must know about this.
Library Genesis
This is another great website for students. This website provide books for free.
http://Scholar.google.com: This is another type of search engine created by Google, students can search on it for school related stuff and find good results, there are also articles available there.
Unpaywall
This amazing extension provides all the papers you need to read, for FREE!Available for Chrome and FireFox
http://www.gutenberg.org
50000 free ebooks to download (epub, kindle, android, ipad)
Old versions of Windows, Mac and Linux Software, Apps & Abandonware Games - Download at OldVersion.com If you update or upgrade any software and if you don't like it; then you can downgrade

C++: Check if the String is Palindrome

1. #include <iostream> 2. #include <algorithm> 3. #include <string>
4. bool is_palindrom(const std::string& str) 5. { 6.    std::string temp(str); 7.    std::transform(temp.begin(), temp.end(), temp.begin(), ::tolower); 8.    return temp == std::string(temp.rbegin(), temp.rend()); 9. }
10. int main() 11. { 12.    std::string str{ "KArak" }; 13.    std::cout << is_palindrom(str) << std::endl; 14.    return 0; 15. }

We are not writing using namespace std because it

C++ STL : An example of Transform Algorithm

#include <iostream>
#include <algorithm>
#include <list>

double reciprocal(double i){
  return 1.0/i;
  }

int main()
{
    std::list<double> vals;
    int i;
    for(i=1; i<10; i++) vals.push_back((double)i);
    std::cout << "Original contents of vals:\n";
    std::list<double>::iterator p = vals.begin();
    while(p != vals.end()) {
    std::cout << *p << " ";
    p++;
}
   std::cout << std::endl;

C++ STL: Merge_Sort using Vector (Sorting)

#include <iostream>
#include<vector>
#include<algorithm>
using namespace std;
void merge_(vector<int>& v,int p,int q,int r){
int n1=q-p+1;  int n2=r-q;// here n1 was written as q+p+1
vector<int>L(n1);
vector<int>R(n2);
for(int i=0;i<n1;i++){
    L[i]=v[p+i];
}
for(int j=0;j<n2;j++){
    R[j]=v[q+j+1];
}
int i=0,j=0;
int k;// declaring k outside
for( k=p;k<=r && i<n1 && j < n2;k++){// if i >= n1 || j> = n2 then it will access random memory
    if(L[i]<=R[j]){
        v[k]=L[i];
        i++;
    }
    else{
        v[k]=R[j];
        j++;
    }
}
for(i = i;i<n1;++i)// these are the two loops must be there if L or R runs out
{
    v[k] = L[i];
    k++;
}

What programming languages do what?

Here is the list of computer programming languages and their use: Java - the general-purpose enterprise standard heavily used for server-side web development; used to write Android appsPython - general-purpose scripting language, popular for numerical computing, financial industry, web development, etc.PHP - used for server-side web developmentC# - general-purpose and largely Windows-centricC++ - general-purpose and high-performance; used for nearly everything, esp. financial industry, scientific computing, game developmentC - used for writing operating systems, device drivers, embedded

Which Linux distribution is the best for a programmer?

Image
You need to specify what sort of engineering: Software engineering/IT/Web—you’re better off sticking with Debian, Ubuntu, or RedHat/CentOS if you want to use the computer to write your own software and/or manage commonly-used platforms without constantly tweaking with the guts of it. Computer Engineering/System Programming—use a source-based distribution like Gentoo, Slackware, or Linux From Scratch.

How do I learn data structures and algorithms from scratch?

Learn Big-Oh notation, omega and theta notations denoting complexity of algorithms and data structures.If you don’t know, learn some discrete mathematics and probability. Learn basic combinatorics, graph theory, matrices, probability theory, especially the concept of expected values. Do this on the fly.Learn basic data structuresImplement singly and doubly linked lists on your own.Learn stack and queue. Implement them using linked lists. For more fun - try implementing stacks and queues using arrays.Implement vector data structure in C++ on your own. It is simple - when you run out of space, allocate twice the memory you had allocated previously and copy all the data to newly allocated array.Implement binary heap data structure and use it as priority

What to use endl or "\n"

The difference between std::endl and '\n' is that std::endl actually flushes the stream. This can be a costly operation in terms of processing time, so it's best to get in the habit of only using it when flushing the stream is actually required.

You may also like:
C++: Basic Data Types
C++: Functions -1
C++: Implementation of Quicksort
C++: Implementation of Heapsort
Cool Websites you don't know about...

How do I improve my logical thinking and problem solving skills?

Here are some of the steps that one can take to build on to the  skill.


The core activitiesFocus and attention: When you face a problem, give it your full focus. Think only about the problem and forget everything else.
Suspect your memory: While memory may be good for various tasks but when it comes to logic, memory is a bad master. Scrutinize your memory and don't trust it completely.
Avoid multitasking: You cannot do two logical thinking activities at once. 
Diagrams are your savior: Always use paper and pencil, draw flowcharts, boxes, circles, to represent logic. Since you have not used your left-brain that much, you will use your right-brain to wake up your left-brain. After you have developed sufficient skills you will be able to do much of this stuff mentally.
Read good books: Find books on logical reasoning, which promises to build the skills  from ground up. Never try to master too much at once, take is slow and steady.
Take online tests: Find some good online tests e.g. Online…

How do I learn competitive programming as a beginner?

Image
Here is a step by step procedure. Some of it can/should be done in parallel. Learn a subset of C++. In Ubuntu, the compiler g++ is already available and if are using latest version then it also supports C++11 and C++14 standards. Use them. Some features make your life very easy. You don’t need to learn about Object-Oriented programming features like classes, inheritance, constructor, destructor etc. You may not even need to learn about templates although they are quite interesting. Think of it as enhanced C.Learn STL - Standard Template Library in C++. It contains implementation of commonly used routines like sort, searching - both linear and binary searching, data structures like vector, linked list, set, map etc. THIS IS VERY IMPORTANT.Learn discrete mathematics, data structures and algorithms - Start from the basics and learn them RIGOROUSLY if you want to become a red coder. Your foundations should be solid. Buy “Introduction to Algorithms” [CLRS] (Yes. Buy it. It is worth the mone…

C++ STL : Insertion Sort (Sorting)

#include<iostream>
#include<vector>
#include<algorithm>


void insertionSort(std::vector<int>&a){
typedef std::vector<int>::iterator it;
for(auto i=1;i<a.size();i++){
it end_sorted =a.begin()+i;
    it insertion_point=std::upper_bound(a.begin(),end_sorted,a[i]);
    std::rotate(insertion_point,end_sorted,end_sorted+1);
}
}
void print(std::vector<int>a){
for(int i=0;i<a.size();i++){
std::cout<<a[i]<<" ";
}

C++ STL :Recursive Merge Sort (Sorting)

#include<iostream>
#include<vector>
#include<algorithm>

template<typename T>

void merge(std::vector<T>& left_vector,std::vector<T>& right_vector,std::vector<T>& merged_vector){
auto left=left_vector.begin();
auto right=right_vector.begin();
auto merged=merged_vector.begin();
auto left_end=left_vector.end();
auto right_end=right_vector.end();

while(left!=left_end&&right!=right_end){
if(*right<*left){
*merged=*right;
++right;
}
else{
*merged=*left;
++left;
}
++merged;
}
std::copy(left,left_end,merged);
std::copy(right,right_end,merged);
}

template<typename T>
void merge_sort(std::vector<T>& A){

C++ Program: Counting letters,words,etc in input

#include <iostream>
#include <fstream>

int main()
{
std::string word;
std::getline(std::cin,word);
std::ofstream outf;
outf.open("lab3.txt");
outf<<word<<std::endl;
outf.close();
    std::ifstream lab3;

    lab3.open("lab3.txt");
    int countletters=0,countnum=0,countpunc=0,countspace=0,words=0,line=0;
    char character,prevchar = 0;
    if(!lab3)
    {
        std::cout << "Could not open file \n";
        return 1;
    }
    while(lab3.get(character) && !lab3.eof())
    {
        if(isalpha(character))
        {
            countletters++;
        }

C++ STL : Reading Elements from Vector until EOL

/* In this program we are entering elements in two vector. We can enter elements if we are pressing "space key".
 If we press "Enter" then we will start to enter in new vector
*/
#include <iostream>
#include <string>
#include <sstream>
#include <vector>
#include <iterator>
using namespace std;
std::vector<int> read_vector()
{
    std::string line = "";
    std::getline(std::cin, line);
    std::istringstream iss(line);

    std::vector<int> v;

    int x = 0;
    while (iss >> x)
        v.push_back(x);

    return v;
}

int main()
{

JAVA: Enhanced For Loop

Image
Enhanced for loop was introduced in JAVA 5 as a simple way to iterate all the elements of a collection.

It is useful when scanning a array instead of using for loop. 
Here we will take a simple example to sum all the elements of an array

    public class EnhancedForLoop {
    public static void main(String[] args) {        int  arr[]={3,2,4,5};        int sum=0;