Friday, March 27, 2015

Check if 3 numbers are equal without using conditional or loop statements - Python Program (Procedural)


Problem Question

Write a python script to check if 3 numbers are equal or not. Print the following output:
  • All Numbers Unique: If all numbers are unequal
  • Two Numbers Equal: If one set of numbers is equal, and one is not
  • All Numbers Equal: If all the three numbers are equal
The program should not use any conditional statements or looping statements like (if .. else) or (do … while) or (switch… case) or (for…loop).

Explanation of Problem

This is a straightforward and easy program if we were to check if 3 numbers are equal or not. However, the added condition of not using conditional or loop statments makes it a bit tricky. The user would input 3 numbers. We need to check if they are equal (all are equal, or two numbers are equal), or not, and give the suitable output as indicated in the problem statement.

Code

#@Title: check_equal_without_if
#@Language: Python 3
#@IDE: PyCharm Community Edition
#@Author: Rogue Coder
#@URL: http://letsplaycoding.blogspot.com/
#@Date: 27-Mar-2015

first_number = int(input("Please input First Number: "))
second_number = int(input("Please input Second Number: "))
third_number = int(input("Please input Third Number: "))
result_array = ['All Numbers Unique', 'Two Numbers Equal', 'Not Possible', 'All Numbers Equal']
result = int((first_number == second_number)) + int((second_number == third_number)) + int((first_number == third_number))
print (result_array[result])

Explanation of Code

input -> This is a standard python built-in function which is used for accepting user input. The function accepts a string parameter, which is output to the user as a prompt for input message. The value returned is the user input in string format, which can be stored in a variable. In our case, we are storing the inputs in variables, first_number, second_number, and third_number. However, we typecast the user intput to int. Refer the standard documentation here.

int() -> This function is used to tyepcast a string into integer. The default conversion is done on base 10, however, we can specify the base as a second argument if needed. You may refer the standard documentation here.

result_array = ['All Numbers Unique', 'Two Numbers Equal', 'Not Possible', 'All Numbers Equal'] -> This is a string array, where we are storing the output that we would display to the user. The index of values is as under.
All Numbers Unique 0
Two Numbers Equal 1
Not Possible 2
All Numbers Equal 3



result = int((first_number == second_number)) + int((second_number == third_number)) + int((first_number == third_number)) -> This is the core logic of this program. The program equates each value with the other. The comparison returns a bool value. This value is either true if the condition is true, else false. In Python, like most programing languages out there, these values correspond to integer values 1 for true and 0 for false. Thus, each comparison is type-casted to int. The result of each expression typecasted to int is summed up, and stored in result variable.
Thus, if all values are unique, all expressions will evaluate to false, hence 0, causing the result to be 0 + 0 + 0, hence 0. If 2 values are equal, one of the three expressions would be true, rest false. Hence, result variable would store value 1 + 0 + 0, OR 0 + 1 + 0, OR 0 + 0 + 1, depending on which of the two values are equal. If all values are equal, then all expressions will evaluate to ture, hence 1. Thus, result variable in this case would store value 1 + 1 + 1, which is 3. Note that value 2 is not possible, becuase if 2 of the 3 expressions are true, that means third has to be true. Like, if a = b and b = c, then a = c is implicitly derived. This value that we get in result variable, will next be used to get the result displayed out.

print (result_array[result]) -> This is the final statement of the program that uses the result derived in the last statement, to get the array index. The table I added before the last explanation would now come in handy. As you can observe, the vlue stored in result variable can be 0, 1, or 3. The array result_array, has values at indexes 0, 1, 2, and 3. The program would use the result of the expression evaluation done in previous statement as the array index, and this statement would print the value at that index, thus giving the expcted output.

print() -> This is a standard Python built-in function, used to display a statement to standard output stream by default, or to a file if the necessary arguments are passed to the function call. You can refer the standard documentation here.

Output(s)


Download Source Code


Monday, March 09, 2015

Implementing Shuffle Merge Operation on Linked List - Data Structures - C++ Program (Procedural)





Problem Question


To implement alternate split operation on Linked List.

Explanation of Problem

In this program we would be implementing a Linked List. Make sure you have a strong understanding of pointers to understand Linked Lists. A linked list is a basic data structure that is used in dynamic memory allocation applications. It comprises of 'nodes' which are linked together to form a sequence of nodes called Linked List. The linkage is done using memory addresses of adjacent nodes (next node in singly linked list, and both next & previous node in doubly linked list).



In this program we use a struct to implement the node of our linked list. We will implement addition function to get some data in linked list before we can perform desired operations on it. Adding a new node to the list means, creating a new node structure, allocating memory to it and linking it to the list.

Consider we have two linked lists. With shuffle merge operation, we output one merged list, such that the elements of the list are alternatingly inserted in the result list. For example, we had lists 1->2->3 and 4->5->6, the output of shuffle merge would be 1->4->2->5->3->6.




Code


#include<iostream>

/**@Title: LinkedList v1.12.cpp*
*@Programming Paradigm: Procedural*
*@Language: C++*
*@Compiler: GNU GCC*
*@IDE: Code::Blocks 13.12*
*@Author: Rogue Coder*
*@URL: http://letsplaycoding.blogspot.com/*
*@Date: 09-03-2015*
*/

struct node
{
  int data;
  node* next;
};

void addAtLast(node** rootNode, int userData);
void shuffleMerge(node* rootNodeFirst, node* rootNodeSecond, node **rootNodeMerge);
void displayList(node* rootNode);

int main()
{
  int choice, userInput;
  node *startListFirst = NULL, *startListSecond = NULL, *startListMerged = NULL;
  std::cout << "Welcome to LinkedList v1.12" << std::endl << "Made by Rogue Coder" << std::endl;
  do
  {
    std::cout << std::endl << "1 : Add a Node to the list 1" <<
         std::endl << "2 : Add a Node to the list 2" <<
         std::endl << "3 : Perform Shuffle Merge" <<
         std::endl << "4 : Display Lists" <<
         std::endl << "5 : Exit" <<
         std::endl << "Enter your choice : ";
    std::cin>>choice;
    switch(choice)
    {
    case 1:
        std::cout<<std::endl<<"Enter data : ";
        std::cin>>userInput;
        addAtLast(&startListFirst, userInput);
        break;
    case 2:
        std::cout<<std::endl<<"Enter data : ";
        std::cin>>userInput;
        addAtLast(&startListSecond, userInput);
        break;
    case 3:
        startListMerged = NULL;
        shuffleMerge(startListFirst, startListSecond, &startListMerged);
        std::cout<<std::endl<<"Shuffle Merged List: ";
        displayList(startListMerged);
        break;
    case 4:
        std::cout<<"List 1: ";
        displayList(startListFirst);
        std::cout<<"List 2: ";
        displayList(startListSecond);
        break;
    case 5:
      std::cout<<std::endl<<"Thank you for using LinkedList v1.12"<<std::endl<<"Made by Rogue Coder"
           <<std::endl<<"Press any key to exit"<<std::endl;
      break;
    default:
      std::cout<<"\a\aWrong Choice\a\a"<<std::endl;
      break;
    }
  }
  while(choice != 5);
  std::cin.get();
  return 0;
}

void addAtLast(node** rootNode, int userData)
{
   node* newNode = new node;
   newNode -> data = userData;
   if(*rootNode == NULL)
   {
      *rootNode = newNode;
   }
   else
   {
       node* currentNode = *rootNode;
       while(currentNode->next != NULL)
       {
           currentNode = currentNode->next;
       }
       currentNode -> next = newNode;
   }
   newNode -> next = NULL;
}

void shuffleMerge(node* rootNodeFirst, node* rootNodeSecond, node **rootNodeMerge)
{
    if (rootNodeFirst == NULL || rootNodeSecond == NULL)
    {
        std::cout<<"One of the Lists is Empty!";
        return;
    }
    node *currentNodeFirst = rootNodeFirst, *currentNodeSecond = rootNodeSecond;
    while (currentNodeFirst || currentNodeSecond)
    {
        if (currentNodeFirst)
        {
            addAtLast(rootNodeMerge, currentNodeFirst -> data);
            currentNodeFirst = currentNodeFirst -> next;
        }
        if (currentNodeSecond)
        {
            addAtLast(rootNodeMerge, currentNodeSecond -> data);
            currentNodeSecond = currentNodeSecond -> next;
        }
    }
}

void displayList(node* rootNode)
{
  node *currentNode = rootNode;
  if(currentNode == NULL)
  {
    std::cout<<std::endl<<"\aList Empty\a"<<std::endl;
  }
  else
  {
    std::cout<<std::endl;
    while(currentNode != NULL)
    {
      std::cout<<currentNode->data<<"->";
      currentNode=currentNode->next;
    }
    std::cout<<"End of List"<<std::endl;
  }
}


Explanation of Code





#include <iostream> -> The compiler calls the Preprocessor to include the IOSTREAM(Standard Input / Output Streams Library) header file into the program, thus letting the use of the Standard Input / Output Streams functions like std::cin and std::cout. As per C++11 specification, including <iostream> automatically includes also <ios>, <streambuf>, <istream>, <ostream> and <iosfwd>.

int main() -> The entry point of the program where the execution starts. This function has to be named main. As per the ANSI specification, the return type has to be int. Since the return type is specified as int in my program, I have to use a return statement at the end of my code. So I use return 0 since zero returned from a function, by convention, implies a correct execution of the program. The return values are used to debug the program.

std::cin (extern istream cin) -> Standard Input Stream, and object of class istream. It is generally used with the extraction operator (>>), though we can use member functions like get (cin.get()), read (cin.read()), etc. for the input. The use of extraction operator is much more popular due to the fact that it aids in getting formatted input.

std::cout (extern ostream cout) -> Standard Output Stream, and object of class ostream. It is generally used with the insertion operator (<<), though we can use member functions like write (cout.write()) for the output. The use of insertions operator is much more popular due to the fact that it aids in giving formatted output.

using namespace std; -> In modern IDEs, we have to explicitly write std::cout instead of cout to use the ostream cout object. Namespace std helps in easing off the pain of writing std:: again and again. Though make sure you are not trapped! The classes defined in std should not be redefined by you. So in case you want to define a class 'distance', you can't do so if you have used std namespace. Though you can define 'Distance' (capital D).

std::endl (ostream& endl (ostream& os)) -> This is a function which is used to insert a newline character and flush the stream. Because this function is a manipulator, it is designed to be used alone with no arguments in conjunction with the insertion (<<) operations on output streams.



struct node
{
  int data;
  node* next;
};
->
This is where we create the struct node that is going to be the building block of our linked list. It comprises of an int 'data' where the user shall store the data they wish. Please note, you can use as many variables and of as many types in the struct, but be sure you handle them correctly. For simplicity we have used int type in our case. The other variable inside our node is 'next', which is a pointer to node. This would be used to build the linkage between the nodes of our linked list. 'next' is going to hold the address of the next node in the sequence.

node* startListFirst; node* startListSecond; -> These are the pointers, which we are going to use to point to the first node / root node / start node of the linked list, that will be input to the shuffle merge function, which we are going to implement in this program.

int choice; -> This variable 'choice' will be used for the user’s choice in the menu driven program.


void addAtLast(node** rootNode, int userData)
{
   node* newNode = new node;
   newNode -> data = userData;
   if(*rootNode == NULL)
   {
      *rootNode = newNode;
   }
   else
   {
       node* currentNode = *rootNode;
       while(currentNode->next != NULL)
       {
           currentNode = currentNode->next;
       }
       currentNode -> next = newNode;
   }
   newNode -> next = NULL;
}
->
This function is used to add a new node at the end of our linked list. The user input which is fed as a parameter to the function, is stored in the ‘newNode’ which is the pointer to the new node that we are going to add to our list. The first statement of this function means, memory is allocated for a node type variable and a pointer is returned which we capture in the variable ‘newNode’. The program checks if the list is empty which we come to know if the ‘rootNode’, i.e., root node of the linked list is initialised as yet or not. If the root node is not yet initialised for our list, we make the ‘rootNode’ pointer to point to the ‘newNode’ we just created. Else, we traverse through the list. Starting from the root node, we hold the position in a new pointer, ‘currentNode’. Since the last node’s ‘next’ won't point to any node, thus we use currentNode->next != NULL for that. Till so is the case, we keep on assigning the address of the next node in sequence to the pointer ‘currentNode’. So as and when we encounter the last node in the list, we come out of the loop. The pointer ‘currentNode’ now holds the address to the last node in the list. So we define the ‘next’ for this last node of ours as the newNode we just created. Now the next of newNode is set to NULL, hence the newNode is added at the end of the list.


void shuffleMerge(node* rootNodeFirst, node* rootNodeSecond, node **rootNodeMerge)
{
    if (rootNodeFirst == NULL || rootNodeSecond == NULL)
    {
        std::cout<<"One of the Lists is Empty!";
        return;
    }
    node *currentNodeFirst = rootNodeFirst, *currentNodeSecond = rootNodeSecond;
    while (currentNodeFirst || currentNodeSecond)
    {
        if (currentNodeFirst)
        {
            addAtLast(rootNodeMerge, currentNodeFirst -> data);
            currentNodeFirst = currentNodeFirst -> next;
        }
        if (currentNodeSecond)
        {
            addAtLast(rootNodeMerge, currentNodeSecond -> data);
            currentNodeSecond = currentNodeSecond -> next;
        }
    }
}
->
We first check if either of our original list is empty. If so, we prompt the user about it and exit out of the function. Else we go ahead.
We traverse through the both the lists, and assign the nodes to our output list alternatingly. We start at with the rootNode of our first original list, as done in the line node *currentNodeFirst = rootNodeFirst;. If the reference is not NULL, that means we have not yet reached end of the list. We ad the value stored at this node to the first node of the output list, pointed to by rootNodeMerge. Then we do similar operation with second list and assign it's value to the next node of rootNodeMerge. We keep traversing through the lists and assign their nodes alternatingly. If we encounter end of list of one, we assign rest of the nodes of other list to output, else we keep assigning nodes in alternate manner.
At the end, when we reach end of list for both the lists, we come out of the function. We have 1 output list that contains data from both lists shuffle merged into one.

void displayList(node* rootNode)
{
  node *currentNode = rootNode;
  if(currentNode == NULL)
  {
    std::cout<<std::endl<<"\aList Empty\a"<<std::endl;
  }
  else
  {
    std::cout<<std::endl;
    while(currentNode != NULL)
    {
      std::cout<<currentNode->data<<"->";
      currentNode=currentNode->next;
    }
    std::cout<<"End of List"<<std::endl;
  }
}
->
This function is used to display the list. The functions accepts the address of the root node as the argument. It then starts traversing through the list from root node, until it finds a node which points to NULL as the next element, indicating the end of list. While traversing through, the function displays the values held in each node on the screen separated by '->'.




do{..}while() -> The program loop which encapsulates the whole program. Until the user chooses to exit the program, the control loops within this.

exit(0); -> This function is used to exit the program with an error code as it's argument. '0' implies normal exit. Other values are used for debugging purposes.

std::cin.get() -> This statement is used to pause our program, until user presses a key. This function is not necessary in your program, I use it to see my outputs at a paused screen. If you use cmd to run your programs, you might not need this. If you use linux/unix you might not need this. Moreover, removing this line of code from this program, doesn't affect the functionality of the program.

Output(s)

















Download Source Code