Posts

Showing posts from 2013

Program to remove duplicate elements from the list in python

Removing duplicate element form the list in python is easy unlike c program.Python includes datatype for sets.A set is an unordered collection of elements without duplicate entries.We can just make set of the list and again make list of that set to get the output. Program I : inputlist = [22,33,33,44,55,55,55,66,66] outputlist = list(set(inputlist)) print outputlist Just three lines of code and you will get the list without any duplicate elements.There are several other technique also for writing program to find the distinct element in the list without using set. Program II : inputlist = [22,33,33,44,55,55,55,66,66] outputlist = [] for element in inputlist:          if element not in outputlist:             outputlist.append(element) print outputlist You can use  http://www.codeskulptor.org/  to run the python programs online.

Deloitte Interview Experience

I attended the Deloitte recruitment process in my campus placements. Deloitte came to our campus for two profiles first one was Business consultancy and another was OIM (Office of information management). I chose the OIM profile. The recruitment process consists of 4 rounds for OIM profile and 3 rounds for Business consultancy. First-round was written round, it was the usual online test conducted by AMCAT. It had 3 sections aptitude, logical reasoning, and  English. The test was very easy. Around 400-500 people appeared for the test. Next, they shortlisted around 120-150 people for the next round which was like a Business presentation. In this round, they formed groups of 10 people per group and gave topics, and told us to make presentations on chart paper and explain them. It was fun. They shortlist people from this round based on their communication skills and valid points. Around 50 were shortlisted for interview rounds. The first interview round was a technical interview for OI

Samsung R&D Bangalore Interview Experience

Image
I attended SISO Interview process recently. So I am going to share my experience with the interview process. I undergo the following rounds for the selection process Written round ( Technical) GSAT ( Aptitude test) Technical Interview I  (50-60 mins) Technical Interview II  (10-15 mins) HR Interview  (10-15 mins) CHECKOUT VIDEO of  Samsung R&D interview experience to skip reading SISO came to my college for a written test and an interview was scheduled later for shortlisted candidates in the Bangalore Samsung office.The first round was written technical in which 20 simple C, C++, JAVA, and DS questions were there. From my college, around 35-40 students were shortlisted for Interviews in Bangalore.                   In Bangalore, there were around 150 people from other colleges also. The next round was the Global Samsung aptitude test. The level of Questions was good, especially the Logical reasoning questions. The questions were quite tricky. After t

Program for Insertion and Deletion in Circular Linked list

A Circular Linked list is a complex data structure. The linked list is circular as the last node of the linked list is pointed to the head making a circular loop. The Insertion of a node can be done at the end of the linked list and any node can be deleted from the circular linked list. I will be writing only the insertion and deletion function instead of the whole program. Code : struct node { int data; node *next; } void insert(node *head,int data) { node *current=head;               // Assign head to the current node node temp; temp=(node*)malloc(sizeof(node)); temp->data=data;                 // insert data into temporary node if(head==NULL)                    // Linked list is Empty { head=temp;                           // make head as temp and temp->next pointed to head temp->next=head; } else { while(current->next!=head)   // Iterate till the end of linked list and insert element  { current=current->next; } current->next=temp; tem

Program to find the inorder successor in Binary search tree

Image
In Binary Tree the Inorder successor is the next node in Inorder traversal. The inorder successor of the root is the leftmost element in the right subtree. In the Binary Search tree, the Inorder successor of an input node can be defined as the node with the smallest value greater than the value of the input node. Basically, you can say that the next node in the sorted node will be the Inorder successor of the previous node. In this BST the inorder successor of 10 is 11 and 13 is 16. As you can see that it is the next node in the sorted order nodes. Algorithm : 1) The first step is to check whether there is a right subtree of the input node or not. If there is a right subtree then find the minimum value node in that and return that will be the inorder successor of the input node. 2) If there is not then move upwards and start from the root and follow the search technique if the value of the input node is less than the root node then move towards left otherwise right and retur

Fetching Documents from remote address in PHP

We can get information uploaded from the remote client system using PHP script below HTML  <form enctype="multipart/form-data"   action="upload.php"   method="post"> <input type="file" name="ufile"> <input type="submit" value="submit"> PHP script <?php  $fdir="C:/xampp/htdocs/mysite/uploads"; $furl="http://localhost/mysite/uploads"; echo $ufile; print "$fdir/$ufile_name"; copy($ufile,"$fdir/$ufile_name"); print "copied <br><img src='$furl/$ufile_name'>"; ?> Also See   How to upload file on server using PHP

Array functions in PHP

There are many array functions in PHP which can be used to manipulate the array elements. Some of them can be used directly on the array elements such that you don't have to write code for it. Though there are a lot of array functions I will write some of the important ones. 1) in_array() function: in_array function is used to check whether the element is present in an array or not if it is present then it will return true otherwise false. example : <?php $starwars=array("princess"=>"leia","teacher"=>"Yoda","bad guy"=>"Darth"); echo in-array("Darth",$starwars);       // returns true echo in_array("obi-san",$starwars);    //returns false ?> 2) array_search() function : array_search function is used to search an array for given value and returns its corresponding key. example: <?php $sort=array("Bubble"=>"sort1","Selection"=>"sor

Program to find the Equilibrium index of an array

Equilibrium index of an array is the index such that the sum of its lower index values and the sum of its higher index values are same. Suppose the array values are a[0] =1  a[1] =-5   a[2] =4   a[3] =4   a[4] =-6   a[5] =5   a[6] =1 then the index 3 will be at Equilibrium because a[0]+a[1]+a[2]=a[4]+a[5]+a[6]. In an array there can be more then one Equilibrium indexes provided the sum of its lower indexes and higher indexes are same. The logic of the program is pretty simple.First we will calculate the sum of the whole array elements and then initialize leftsum=0.Now we iterate through all the index of the arrays and substract all index values from the sum and add to leftsum and simultaneously check whether sum=leftsum.If it is found out equal then return i that is the index of the array. Program : #include <stdio.h> #include<conio.h> int equilibrium(int arr[], int len) {    int sum = 0;        int leftsum = 0;    int i;      for (i = 0; i < len; +

Find two element in an array whose sum is closest to zero

The array is having both +ve and -ve values.Lets take array values as  3 -7 8 9 5 -3 Then the two numbers with sum closest to zero will be 3 and -3. Program : # include <stdio.h> # include <stdlib.h> # include <math.h> void sumclosetozero(int arr[], int size) {   int count = 0;   int a, b, sum_min, sum, a_min, b_min;   a_min = 0;   b_min = 1;   sum_min = arr[0] + arr[1];   for(a = 0; a < size - 1; a++)   {     for(b = a+1; b < size; b++)     {       sum = arr[a] + arr[b];       if(abs(sum_min) > abs(sum))       {         sum_min = sum;         a_min = a;         b_min = b;       }     }   }   printf(" The two elements whose sum is minimum are %d and %d",           arr[a_min], arr[b_min]); } int main() {   int a[] = {3, -7, 8, 9, 5, -3};   sumclosetozero(a, 6);   getchar();   return 0; }

The Pigpen/Masonic Cipher

Image
Pigpen cipher is used by freemasons in 18th century.For that reason it is also called as masonic cipher.It is different from other ciphers as a fact that it does not substitute another letter in place of letter like other ciphers rather it uses symbols substituted in place of letters.Each of the 26 letters have different symbols.The freemasons actually made four different structures with letters embed in them and used part of that structure as a symbol of that particular letter. So for A they used   __| B they used    |__| for J      __.|  for S     \ / for W   \./ It is also named as rosicrucian cipher as it is believed that variations of ciphers was used by Rosicrucians  brotherhood along with freemasons.The pigpen cipher is used in Dan brown Novel "The lost symbol".It is also used in the game "Assassins creed II".It was also published in the website  The Science of Deduction  created by Sherlock series BBC as a part of puzzle.As the cipher is very sim

Ant in a Maze problem

Image
Ant in a maze is another problem that can be solved using backtracking algorithm.In this problem there is a NxN  maze in which one corner of maze is entry point and other is exit point.Now there is an ant in a maze who wants to go from entry to exit.For doing this there are certain constraints like an ant can move only forward or downward but no backward and upward.For the sake of simplicity we are taking 4x4 Maze.The maze can be denoted by a matrix with values 0 and 1.0 means the path is blocked and 1 means the path is available.The maze and the path for ant from entry to exit is The block which are in grey color are dead end in the maze that is the ant cannot go through such blocks.The red path is the path travelled by ant from entry to exit.The matrix representation of the above maze without the path will be (input to be taken) maze[4][4]={{1,1,0,0}, {1,1,0,1}, {0,1,0,0}, {1,1,1,1} } and the matrix representation of path travelled by ant will be (output to be

Functions declarations which cannot be overloaded

Generally there is a confusion among students regarding the function overloading.So it is an important part to be covered for interviews.Companies often asked function overloading questions which are generally tricky and confuse students.So here are some functions which cannot be overloaded in C++. 1) Function declaration that differ only in return type cannot be overloaded. 2) Member function with the same name and the parameter list cannot be overloaded if any of them is static member function declaration. ex : static void func(int i)                void func(int i) 3) Parameter declaration that differ only in a pointer (*) versus an array [] are equivalent and hence cannot be overloaded. ex : int func(int *p)       int func(int p[]) 4) The function declaration with parameter having const keyword is equivalent to normal parameter declaration hence cannot be overloaded. ex : int func(int x)       int func(const int x) 5) The function declaration in which one parame

Program to convert Binary tree to Doubly linked list

Image
The order of Doubly linked list will be same as the inorder of the Binary tree.So the first node of DLL will be the leftmost node of Binary tree.Let us assume that the given Binary tree is Now the order of the Doubly linked list will be 31 23 36 15 42 34. Algorithm : The algorithm of this program is pretty simple.We will first find the inorder of the left subtree and convert into DLL.Then we again find the inorder of right subtree and convert into DLL.Then finally we join both DLL to the root node of the tree. 1) Recursively convert left subtree to DLL 2) Now find the inorder predecessor of root node. Inorder predecessor is the right most node of left subtree.Let take it as IP node. 3) Now nake root node as next of IP node and IP node as previous of root node. 4) Recursively convert Right subtree to DLL 5) Now find the inorder successor of root node.The inorder successor of root node is the left node of right subtree.Let take it as IS node. 6) Now make IS node next of

Program to find the maximum Height of a Binary Tree

Maximum Height of binary tree is the maximum number of nodes between the root node and the farthest leaf node which could be in either left or right subtree of Binary tree. Program : #include<stdio.h> #include<stdlib.h> #include<conio.h> struct node {     int data;     struct node* left;     struct node* right; }; int maxheight(struct node* node) {    if (node==NULL)        return 0;    else    {              int l = maxheight(node->left);        /*Recursively travel till you reach the farthest node on left        int r = maxheight(node->right);     /*Recursively travel till you reach the farthest node on Right        if (l>r)            return(l+1);                             /* if l>r it means there are more number of nodes in left then right so                                                                return (l+1) including root node.        else            return(r+1);                            /* otherwise ret

Register keyword in C

The variables which are most frequently used in a program can be put in registers using 'register' keyword  because register are faster than memory to access..The keyword 'register' tells compiler to store the variable in register instead of memory.Its compiler choice to put it in register or not.But mostly when compiler do optimizations then they put the variables in registers. When we store variables in a register and not in memory we cannot use & operator with variables because we cannot access the address of register.Using & operator with register variable will throw error by the compiler. int main() { register int j=10; int *p=&j; printf("%d",*p); getch(); } The above program will throw error as we are accessing address of register variable j.Now suppose we make pointer variable register instead of j what will happen now? will program run successfully or throw error? int main() { int j=10; register int *p=&j; printf(&quo

How to Create Project in Django Python Framework

Installation and setup of python and Django Django is a Python framework that is used to make python projects and web applications easily.It works for any python version. It supports a database called SQLite and you don't have to set up the database. For using Django you first need to install python. You can get python @  http://www.python.org .After installing python you can check whether Python is installed or not by typing python command in cmd, and if python is installed you will see the python version in the command line. After that, you can install Django's latest version and start making python projects. For the installation of Django you can refer  https://docs.djangoproject.com .Now if you are done with installing python and Django you can check the version of Django you installed by typing and running the command   python -c "import django;print(django.get_version())" Creating a project in Django Change your current directory where you want to st

Heaven Dream Riddle

Riddle : A man saw in a dream that he died and went to the heaven.In heaven he saw thousands of people roaming whom he dont know.All of the people were naked.Suddenly he saw two couples moving around and he recognized them.He knew that these couples are Adam and Eve.How would he so sure that the couple he saw was adam and eve (obviously he never met adam and eve before)? Solution : He immediately recognized adam and eve because he saw the couples who dont have navel.Obviously those two were not born of women so they dont had umbilical cord and therefore never had navel.

Password riddle

Riddle : Steve works in cryptology department.One fine morning when steve entered his room in office he saw that his system is already logged in and all his important files are gone .Steve then went to his boss cabin and said "I need my system to be secure for that i need new password.My old password is hacked and all my important files are gone". Boss told him "I know your important files are gone and for that i issued you new password.Your new password is unbreakable,trust me". Steve said "But what is my new password?" Boss said "This is important.If you will listen carefully you will get your new password.Your new password is in someway opposite to your old password and you already heard that.Your new password and old password has 3 letters in common and your new password length is one less then the double of your old password length.Always remember more the length of password more it is difficult to crack." Steve then went to his

Water cans puzzle

Water cans puzzle is very common puzzle asked in interviews.somewhere or the other you must have encountered with this type of puzzles. Puzzle : Sam is on a treasure hunt and on his way to find out the treasure he reached at river where he encountered with the next clue which will further show him the path towards the treasure.Now for the next clue he saw two cans,one is of 9 gallon and another is of 4 gallon both are empty initially and a balance with a note on it "Exactly six gallons of water will show you the way".Now Sam has to measure exactly six gallons of water to get the map for further search.Assume that Sam can transfer water from one can to another and also throw water if it is required.How will he measure exactly 6 gallons of water? Solution : Obviously you cannot measure 6 gallons of water in a 4 gallon can.So you have to take 6 gallons of water in a 9 gallon can and keep it on balance. Here are the steps sam will follow :- 1) Sam will first pour wat

Program for union of two linked lists

Union of two linked list will give the distinct elements of both the linked list. List 1 : 4->8->9->30->5 List 2 : 6->4->9->32->7 Union : 4->8->9->30->5->6->32->7 The logic for program of union of two linked list is very simple.Take the resultant linked list and initialize it to NULL.Now traverse list 1 till the null and insert all the values in resultant linked list.Now take list 2 and check whether the value of list 2 is already present in resultant linked list.If the value is not present in the linked list then insert it otherwise move forward without inserting. Program : struct node { int data; node* next; } void insert(node** head,int value) { node* temp; temp=(node*)malloc(sizeof(node)); temp->data=value; temp->next=head; head=temp; } bool present(node* head,int data) { node* temp; temp=(node*)malloc(sizeof(node)); while(temp!=NULL) { if(temp->data==data) return 1; temp=temp->next; } retur

8 Queens Problem

Image
8 Queen problem is a problem in which we have to place 8 Queens on 8x8 chessboard such that no two Queens attack each other.For placing the queens Backtrack Algorithm is used.Let us know first what is backtrack algorithm. Backtrack Algorithm : Backtrack algorithms uses a incremental technique to arrive at a final solution.It will take the candidate as valid and check all the constraints,if the solution is possible then it moves forward or else it will abandons it when it determines that solution is not possible taking the present candidate. How backtracking is helpful in the case of 8 Queens problem?? We will be going to place all the Queens in columns one by one from the leftmost column.When we will be placing the queens in the column we will check the constraints like if there is another queen in the row or column or diagonally.If we find a row that is valid and we can place a queen in that then we will take that row and column as a part of the solution.But if we cannot find s

Program to Rotate a linked list by k nodes

Lets take linked list as 10->30->60->90->20->40 and we want to rotate it by k=4 nodes.That means we want to rotate from (k+1)th node.The final linked list after rotation will be like 20->40->10->30->60->90. The basic idea to do that is make the kth node as NULL and the last node will point to the head node.So here is the function of rotating the linked list by k nodes. Program : struct node {     int data;     struct node* next; }; // This function rotates a linked list counter-clockwise by k nodes and update head. void rotate (struct node **head, int k) {      if (k == 0)        return;         struct node* current = *head;     // current will either point to kth or NULL after this loop.         int count = 1;     while (count < k && current != NULL)     {         current = current->next;         count++;     }     // If current is NULL, k is greater than or equal to count     // of nodes in linked list.  

How to make a simple GUI in Matlab

Image
Recently i was working on project which was to be done on Matlab and we have to present our analysis in Matlab.For that i need to make some kind of User Interface.After searching on internet for some time i found out about GUIDE in matlab for making basic GUI in Matlab.In this post i will tell you how to make a simple GUI in Matlab using GUIDE. To start with type Guide in your command line window.You will get window opened in which there is a tab create New GUI under which there will be 4 options Blank GUI GUI with UI Controls GUI with Axis and Menu Modal Question Dialog /* User interface (.fig file) */ Select Blank GUI to make your user interface.You can select other three options also to fit your needs.But in this post i will be using Blank GUI for making simple User Interface.After selecting, a Window will get opened where a palette with all the UI components is there.You can drag and drop it and place anywhere you want. I will make a simple GUI with two Edi

Mango apples and bag labels

You have three bags and three labels. One bag has only Mangoes, one has only Apples and one has both Mangoes and Apples. Three labels are M, A and MA. M label was meant for the bag with only Mangoes, A label was meant for the bag with only Apples and MA for the bag with both Mangoes and Apples. Victor by mistake labelled the bags wrongly such that all the labels are wrong, how many minimum number of Fruits he should pick and from what bags to correct the labels? It is given that each bag has unlimited number of Fruits to be picked. Solution : The minimum number of Fruits Victor should pick to identify correct labels is 1 from the bag with label MA How just 1 ball ? As the label of all the bags are wrong, bag with label MA can either have all Mangoes or all Apples. Now Victor will either get Mango or the Apple. Case 1: Lets assume Victor gets Mango Bag with label MA is the bag with all the Mangoes. So now MA is M. Bag with label A can either be MA or M(as all the label

Program to separate Even and Odd numbers in a linked list

struct node {   int data;   struct node *next; };   void separateEvenOdd(struct node **head_ref) {   struct node *end = *head_ref;     struct node *prev = NULL;   struct node *curr = *head_ref;     while(end->next != NULL)        end = end->next;     struct node *new_end = end;     /* Take all odd nodes before the first even node      and move then after end */  while(curr->data %2 != 0 && curr != end)   {     new_end->next = curr;     curr = curr->next;     new_end->next->next = NULL;     new_end = new_end->next;   }         /* Do following steps only if there is any even node */   if (curr->data%2 == 0)   {       *head_ref = curr;           /* now current points to the first even node */    while(curr != end)     {       if ( (curr->data)%2 == 0 )       {          prev = curr;          curr = curr->next;       }       else       {                  prev->next = curr->next;            c

The Prisoners Black and White Hat Riddle

Problem : Suppose there are 4 prisoners named A, B, C, and Z. Prisoner Z is standing on one side of a wall, and prisoners A B and C are standing on the other side of the wall. Prisoners A, B, and C are all standing in a straight line facing right – so A can see prisoner B and C, and B can see prisoner C. This is what their arrangement looks like: Z | A B C Where the “|” represents a wall. The wall has no mirrors. So, prisoner Z can see the wall and nothing else. There are 2 white hats and 2 black hats and each prisoner has a hat on his head. Each prisoner can not see the color of his own hat, and can not remove the hat from his own head. But the prisoners do know that there are 2 white hats and 2 black hats among themselves. The prison guard says that if one of the prisoners can correctly guess the color of his hat then the prisoners will be set free and released. The puzzle for you is to figure out which prisoner would know the color of his own hat?And also discuss the vari

Program to find all the permutations of the string

#include<iostream> #include<conio.h> #include<string.h> using namespace std; void permutation(char *a, int i, int n) {    int j;    if (i == n)      printf("%s\n", a);    else    {         for (j = i; j <= n; j++)        {           swap((a[i]), (a[j]));           permute(a, i+1, n);           swap((a[i]), (a[j]));        }    } } void swap (char *x, char *y) {     char temp;     temp = *x;     *x = *y;     *y = temp; } int main() { char a[] = "ABCD";    permutation(a, 0, 3);    // start index-0 and last index-3 of an array    getch(); }

Program to separate positive and negative numbers in an array

#include<iostream> #include<conio.h> using namespace std; void separateposneg(int arr[10],int a) {     int j=0,b[10],count=0;  for(int i=0;i<a;i++)  {   if(arr[i]>0)   {   count++;   b[j]=arr[i];   j++;   } }  for(int i=0;i<a;i++)  {   if(arr[i]<0)   {     b[count]=arr[i];   count++;   }      } cout<<"The separated numbers are\n";  for(int j=0;j<a;j++)  {  cout<<b[j]<<"\n";        }  } int main() {     int ar[10],n;     cout<<"enter no of values\n";     cin>>n; cout<<"Enter array\n"; for(int i=0;i<n;i++) { cin>>ar[i]; } separateposneg(ar,n); getch(); } Input : 6 3 90 -2 6 -90 5 Output : 3 90 6 5 -2 -90

Program to print the numbers with Odd Occurences

#include<iostream> #include<conio.h> using namespace std; int main() { int a[10],b[10]; int n,c; cout<<"Enter the total numbers to be checked\n"; cin>>n; cout<<"Enter the numbers\n"; for(int i=0;i<n;i++) { cin>>a[i]; } for(int j=0;j<n;j++) { int count=0; if(a[j]==0) { c++; continue; } for(int k=j+1;k<n;k++) { if(a[j]==a[k]) { count++; a[k]=0; } } b[j-c]=count+1; if(b[j-c]%2!=0) cout<<"The numbers with odd occurence are\n"<<a[j]<<"\t"; } getch(); } Input : 8 3 3 3 4 4 6 7 7 Output : 3 6

Program to search the element in Sorted Rotated Pivoted array

Sorted Rotated Pivoted array means the sorted array is rotated through the pivot element.The element in a sorted array can be find using binary search in O(logn) time.But if the sorted array is rotated through some pivot element then how to search for an element in that array.Suppose take sorted array 1 2 3 4 5 it might become 3 4 5 1 2 after rotating at Pivot element 5.Pivot element can be found by the idea that the only element whose next element is smaller then pivot element in an array.So here is the program to find the element in a sorted rotated pivoted array. Our first task is to find a pivot element in an array.The above idea of  pivot element is used to find the pivot element in an array. int findpivot(int a[],int low,int high) { int mid=(low+high)/2; if(a[mid]>a[mid+1])        // if middle element is greater then its next element then it is pivot element as it is the                                                    only element whose next element is smaller the

Tricky Questions or Puzzles in C

This post is about the Tricky Questions   or code snippet in C or C++ asked in most of the Interviews   (See Interview Experience ) by some of the good companies. You may know probably the right concept but it will not strike you at the interview and to crack all those Interview Questions  you should know some of them beforehand. If you are applying for Job related to JAVA then checkout the blog post  Tricky Questions in JAVA . 1) what will be the output of the following Printf function.   printf("%d",printf("%d",printf("%d",printf("%s","ILOVECPROGRAM")))); Ans-ILOVECPROGRAM1321 The above printf line gives output like this because printf returns the number of character successfully written in the output. So the inner printf("%s","ILOVECPROGRAM") writes 13 characters to the output so the outer printf function will print 13 and as 13 is of 2 characters so the next outer printf function will print 2 and then