Posts

Showing posts from 2017

C++: Binary Tree using STL

Image
In computer science, a binary tree is a tree data structure in which each node has at most two children, which are referred to as the left child and the right child. 

SPOJ Problem - CPTTRN6 - Character Patterns (Act 6)

This is a problem from SPOJ. We have to print a character pattern according to the input given.

We have input

33 1 2 1 4 4 1 2 2 5 3 2

SPOJ Problem - CPTTRN5 - Character Patterns (Act 5)

This is a problem from SPOJ. We have to print a character pattern according to the input given.

We have input 

33 1 24 4 12 5 2

C++: Huffman Coding using STL

Image
Huffman Code compress data very effectively: saving of 20% to 90% are typical, depending on the characteristics of the data being compressed.Huffman's greedy algorithm uses a table giving how often each character occurs (i.e., its frequency) to build up an optimal way of representing each character as a binary string. This algorithm constructs an optimal prefix code called a Huffman Code.

C++: Maximum Priority Queue

Image
In a Priority Queue, an element with high priority is served before an element with low priority. If two elements have the same priority, they are served according to their order in the queue.

While priority queues are often implemented with heaps, they are conceptually distinct from heaps. [Wikipedia]

C++: Selection sort using STL

Image
Selection sort is an sorting algorithm. It has O(n2) time complexity. It has performance advantages over more complicated algorithms in certain situations, particularly where auxiliary memory is limited.

It divides the input list or the array in two parts:
1. Sorted array
2. Unsorted array

The minimum element from the unsorted array is picked and placed at the end of sorted array in each iteration.

C++: Program to find smallest element is an array which is repeated exactly 'k' times

Image
This is a problem from GeeksForGeeks. I have tried to write different code for the problem.

The problem says we have an array of elements . We have to find the smallest element which is repeated exactly k times.

C++: Implementation of Merge Sort

Image
Merge sort is a sorting algorithm which uses Divide-and-Conquer approach.

A merge sort works as follows: 
1. Divide the unsorted list into n sublists, each containing 1 element (a list of 1 element is considered sorted). 

2. Repeatedly merge sublists to produce new sorted sublists until there is only 1 sublist remaining. This will be the sorted list.  Source Wikipedia

C++: Swapping Node Links in Linked List

Image
Here we are going to swap the links of the node instead of data in the node. 

Here we are using swapLinks() function to swap the links of the node. We are using search() function which returns the node of the value entered and insert() to insert the values.  

You can refer C++: Singly Linked List for the code of search() and insert().
For eg.

LinkedList1 = {10, 15, 12, 13, 28, 14, 16}swapLinks(10, 13)LisnkedList1 = {13, 15, 12, 10, 28, 14, 16}

C++: Insertion Sort using STL (Sorting)

Image
An insertion sort is generally described simply as: read each element in turn, and insert it in the right position among the previous read (and sorted) elements.

It is much less efficient on large lists than more advanced algorithms such as quicksort, heapsort, or merge sort.

However, insertion sort provides several advantages:

➧ Simple implementation

C++: Sorting Elements according to 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

max_heapify()function: The running time of this procedure is 
O(lg n) and it helps to maintain the max-heap property. Max-heap property means every node other than root node must be smaller than or equal to its parent.

build_max_heap()function: Its running time is O(n lg n). Result after execution ofbuild_max_heap() function is

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;

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++ 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;

Popular Posts

Top 10 Web Sites Every Programmer Should Visit Daily

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