Sunday 7 January 2018


Question: What is Cognitive Computing?

Answer:

According to one of the blog, the blogger has very well said, “Cognitive Computing is a simulation of human thought process in a computerized model” - it is as simple as that.

Just as human learns about new things, we make the machine learn in the same style. This makes the learning very intuitive and genuine. Actually, the learning process, even for the humans consists of four stages:
  1. Observation
  2. Interpretation
  3. Evaluation
  4. Decision

Humans first observe any new incident very closely. This is where we grasp all the details of the incident. This is followed by the interpretation of the incident and matching against some previously known incidents of the same relevance. This is where we form various hypothesis over the incident. The hypothesis may be true or may be false. Usually there is a human factor of correction or guidance in the case of humans that leaves us with only the correct set of hypothesis. This is evaluation phase of the hypothesis. Based on the resulting hypothesis, a decision is taken and the knowledge is acquired by the humans.

This era of computing is also known as ‘the era of cognitive computing’, as the machines as coded to learn in the same way as the humans do.

The advantages of cognitive computing are:
  1. There is a better interaction among the human expertise and the machine leading to a much refined knowledge.
  2. Efficient processing to spot opportunities and uncover issues in real time for faster and more efficient response.
  3. Better analytics of the data that is fed to the system.

Tuesday 10 October 2017

Reversing a LinkedList using Stack in Java

Hello people, this is another blog dedicated to reversing a LinkedList using a Stack. Although it can be done in several ways like recursion, iteration, using constant auxiliary space, etc, 'Stack' is a very easy and efficient method to do the same.

This has been demonstrated in the code.


import java.util.*;

class TestClass {

static class Node {
int data;
Node next;
public Node(int data) {
this.data = data;
this.next = null;
}
}

static Node head;
public static void main(String[] args) {
Stack<Integer> stack = new Stack<Integer>();
for(int i = 0; i < 10; i++) {
Node temp = new Node(i);
if(head == null) {
head = temp;
} else {
Node p = head;
while(p.next != null) {
p = p.next;
}
p.next = temp;
}
}
System.out.print("Printing the LinkedList: ");
Node x = head;
while(x != null) {
System.out.print(x.data + " ");
x = x.next;
}
System.out.println();

try {
Node p = head;
while(p != null) {
stack.push(p.data);
p = p.next;
}
System.out.print("Reversing the LinkedList using stack: ");
while(!stack.isEmpty()) {
System.out.print(stack.pop() + " ");
}
System.out.println();
} catch (EmptyStackException exception) {
System.out.println("The stack is Empty!");
}
}
}

People, please let me know if this could be improvised and let me know the concerns if any!

Sunday 8 October 2017

Hours, Minutes and Seconds!!!

Hey people, I am having a doubt here, a puerile one!

There is a clock that is 24 hours format and every other property of the clock is as same as the other regular 12 hours format wall clock.

So I am not able to fix this formula to calculate the "Angle between the hour hand, the minute hand and the second hand".

Please look at the code and someone help me fix this.

import java.util.Scanner;

class Solution {
public static void main(String[] args) {
Scanner scanner = null;
try {
scanner = new Scanner(System.in);
int testCases = scanner.nextInt();
String[] time1 = new String[3];
String[] time2 = new String[3];
String[] input = new String[testCases];
for(int i = 0; i < testCases; i++) {
input[i] = scanner.next();
}
for(int i = 1; i < testCases; i++) {
time1 = input[i-1].split(":");
time2 = input[i].split(":");
String res = String.format("%.6f %.6f %.6f",
(Math.abs(Float.parseFloat(time2[0]) - Float.parseFloat(time1[0])) * 6),
(Math.abs(Float.parseFloat(time2[1]) - Float.parseFloat(time1[1])) * 6),
(Math.abs(Float.parseFloat(time2[2]) - Float.parseFloat(time1[2])) * 6)
);
System.out.println(res);
}
} catch (Exception exception){
exception.printStackTrace();
} finally {
scanner.close();
}
}
}


The output of the program should be the angle between the hour hand, minute hand and the second hand with respect to the one succeeding it.

For example, consider...

2
10:00:00
12:00:00

is given as the input. In this case, since we can simply calculate that the hour hand has traversed 30 degrees and the hour and minute hand has traversed 0 degree and 0 degree respectively. The output would be

30.000000 0.000000 0.000000

Please help me make a formula for it!

In  case of further clarification, please feel free to clarify!

Thanks a lot in advance! :)

Saturday 7 October 2017

Finding the middle Node of the Linked List using fast and slow method

Fast and slow pointers are very useful in LinkedList especially when traversal of the LinkedList is required several times.

Here is an implementation of fast and slow method for finding the middle of the LinkedList without traversing the whole array.

class Node {
int data;
Node next;
public Node(int data) {
this.data = data;
this.next = null;
}
}

class LinkedList {
static Node head;

public static Node printMiddle(Node head) {
Node fast_ptr = head;
Node slw_ptr = head;
if(head != null) {
while(fast_ptr != null && fast_ptr.next != null) {
fast_ptr = fast_ptr.next.next;
slw_ptr = slw_ptr.next;
}
System.out.println("The middle element is: " + slw_ptr.data);
}
return slw_ptr;
}

public static void main(String[] args) {
head = new Node(1);
head.next = new Node(2);
head.next.next = new Node(3);
head.next.next.next = new Node(4);
head.next.next.next.next = new Node(5);
head.next.next.next.next.next = new Node(6);
head.next.next.next.next.next.next = new Node(7);
head.next.next.next.next.next.next.next = new Node(8);
head.next.next.next.next.next.next.next.next = new Node(9);

printMiddle(head);
}


Please feel free to comment over for any suggestions / doubts.

Monday 21 August 2017

Breadth First Search of a graph using Adjacency List

Breadth First Search of a graph using Adjacency List.



This post is an implementation of a breadth first search of a Graph using Adjacency List in Java. In this, we go level by level and add all the elements onto the queue and maintain a array of boolean values to mark them as visited. The boolean array is required just to make sure we do not get into a circular graph.

As said, the algorithms uses the FIFO, thus queue is required as a data structure in this implementation.

More details on it coming soon...


import java.util.Iterator;
import java.util.LinkedList;
import java.util.Scanner;

@SuppressWarnings("unchecked")
class BreadthFirstSearch {

private int v;
private LinkedList<Integer> adj[];

public BreadthFirstSearch(int v) {
this.v = v;
adj = new LinkedList[v];
for (int i = 0; i < v; ++i) {
adj[i] = new LinkedList();
}
}

void addEdge(int v, int w) {
adj[v].add(w);
}

void breadthFirstSearch(int s) {
boolean[] visited = new boolean[v];
LinkedList<Integer> queue = new LinkedList<Integer>();
// Adding the first element to the queue
visited[s] = true;
queue.add(s);

// Adding its adjacent elements to the queue
while (queue.size() != 0) {
s = queue.poll();
System.out.print(s + " ");
Iterator<Integer> iterator = adj[s].listIterator();
while (iterator.hasNext()) {
int next = (int)iterator.next();
if(!visited[next]) {
visited[next] = true;
queue.add(next);
}
}
}
}

public static void main(String[] args) {
BreadthFirstSearch bfs = new BreadthFirstSearch(4);
bfs.addEdge(0, 1);
bfs.addEdge(0, 2);
bfs.addEdge(1, 2);
bfs.addEdge(2, 0);
bfs.addEdge(2, 3);
bfs.addEdge(3, 3);

System.out.print("BreadthFirstSearch starting at vertex 1: ");
bfs.breadthFirstSearch(1);
System.out.println();
}
}


Please leave your comments for any suggestion or query.

Saturday 6 June 2015

Stack implementation

Stack implementation in C using Arrays.



As in one of my previous blog, I showed the Stack implementation in Java using arrays, this time I will demonstrate the same features using C as a programming language. This is a very basic implementation and nicely shows the use of pointers in the easiest way. 



#include <stdio.h>
#include <stdlib.h>

struct ArrayStack {
    int top;
    int capacity;
    int *array;
};

struct ArrayStack *createStack(int capacity) {
    struct ArrayStack *stack = malloc(sizeof(struct ArrayStack));
    stack -> top = -1;
    stack -> capacity = capacity;
    stack -> array = malloc(stack -> capacity * sizeof(int));
    return stack;
}

int isStackEmpty(struct ArrayStack *stack) {
    return (stack -> top == -1);
}

int isStackFull(struct ArrayStack *stack) {
    return (stack -> top == stack -> capacity - 1);
}

void push(struct ArrayStack *stack, int data) {
    if (!isStackFull(stack)) {
        stack -> array[++stack -> top] = data;
    } else {
        printf("The stack is Full!\n");
    }
}

int pop(struct ArrayStack *stack) {
    if (!isStackEmpty(stack)) {
        return stack -> array[stack -> top--];
    } else {
        printf("The stack is Empty!\n");
        return 0;
    }
}

void deleteStack(struct ArrayStack *stack) {
    if(stack) {
        if (stack -> array) {
            free(stack -> array);
        }
        free(stack);
    }
}

void display(struct ArrayStack *stack) {
    int i = 0;
    if(!isStackEmpty(stack)) {
        printf("The Stack contents are: ");
        for(i = 0; i <= stack -> top; ++i) {
            printf("%d ", stack -> array[i]);
        }
        printf("\n");
    } else {
        printf("The Stack is empty!\n");
    }
}

int main(int argc, char const *argv[])
{
    int capacity, operation, num;
    char choice;
    printf("Enter the stack capacity: ");
    scanf("%d", &capacity);
    struct ArrayStack *stack = createStack(capacity);
   
    do {
        printf("Stack Operations: \n");
        printf("\t1. Push\n");
        printf("\t2. Pop\n");
        printf("\t3. Stack Overflow\n");
        printf("\t4. Stack Unverflow\n");
        printf("\t5. Display\n");
        printf("Enter the operation to be performed: ");
        scanf("%d", &operation);

        switch(operation) {
            case 1: printf("Enter the number to be pushed to the stack: ");
                    scanf("%d", &num);
                    push(stack, num);
                    break;

            case 2: printf("The element popped is: %d\n", pop(stack));
                    break;

            case 3: if (isStackFull(stack)) {
                        printf("Stack Overflow: True\n");
                        break;
                    } else {
                        printf("Stack Overflow: False\n");
                        break;
                    }

            case 4: if (isStackEmpty(stack)) {
                        printf("Stack Underflow: True\n");
                        break;
                    } else {
                        printf("Stack Overflow: False\n");
                        break;
                    }

            case 5: display(stack);
                    break;

            default: printf("InCorrect Input, please try again!\n");
                     break;
        }

        printf("Do you want to continue, 'y' / 'n'?: ");
        scanf(" %c", &choice);
    } while(choice == 'y');
    return 0;
}
 

Please feel free to comment and let us know if this could be simplified any further!

Tuesday 2 June 2015

Stacks implementation in Java

Stacks is a ADT in Java which follows 'Last In First Out' principle. This post is a very simple implementation of Stacks in Java.

 

import java.util.Scanner;
class Stack {
    int top;
    int capacity;
    int array[];

    public Stack(int capacity) {
        this.top = -1;
        this.capacity = capacity;
        array = new int[capacity];
    }

    boolean isStackFull() {
        return this.top == capacity - 1;
    }

    boolean isStackEmpty() {   
        return this.top == -1;
    }

    void push(int data) {
        if(!isStackFull()) {
            this.array[++this.top] = data;
        } else {
            System.out.println("The Stack is Full!");
        }
    }

    int pop() {
        if(!this.isStackEmpty()) {
            return this.array[this.top--];
        } else {
            System.out.println("The Stack is Empty!");
            return -1;
        }
    }

    void display() {
        if(this.isStackEmpty()) {
            System.out.println("The Stack is Empty!");
        } else {
            System.out.print("The elements in the stack are: ");
            for (int i = 0; i <= this.top; i++) {
                System.out.print(this.array[i] + " ");
            }
            System.out.println();
        }
    }

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter the size of the stack: ");
        Stack stack = new Stack(scanner.nextInt());

        do {
            System.out.println("1: Push");
            System.out.println("2: Pop");
            System.out.println("3: Display");
            System.out.println("4: isStackEmpty");
            System.out.println("5: isStackFull");
            System.out.println("6: Quit");
            System.out.print("Enter the stack operations: ");   

            int choice = scanner.nextInt();

            switch(choice) {
                case 1: System.out.print("Enter the element to be pushed: ");
                        stack.push(scanner.nextInt());
                        break;

                case 2: System.out.println("The element popped is: " + stack.pop());
                        break;

                case 3: stack.display();
                        break;

                case 4: System.out.println("Stack Empty: " + stack.isStackEmpty());
                        break;

                case 5: System.out.println("Stack Full: " + stack.isStackFull());
                        break;

                case 6: break;

                default: System.out.println("Please enter a valid input!");
            }

            System.out.print("Do you want to continue, 'y' / 'n'?: ");
        } while(scanner.next().toLowerCase().charAt(0) == 'y');
    }
}


  • Space Complexity: O(n)
  • Time Complexity(for all the individual operations): O(1)
  • Limitations: Max size of the array must be defined and cannot be changed.
  • Solution: Dynamic Array Implementation

Please Let me know if this could be simplified any further and done more efficiently!