Monday, August 10, 2015

How much time robot will take to fell in ditch

A robot is programmed to move forward F meters and backwards again, say B meters, in a straight line. The Robot covers 1 meter in T units of time. On Robot's path there is a ditch at a distance FD from initial position in forward direction as well as a ditch at a distance BD from initial position in backward direction. This forward and backward movement is performed repeatedly by the Robot.
Input Format:

First line contains total number of test cases, denoted by N
Next N lines, contain a tuple containing 5 values delimited by space
F B T FD BD, where

  1. F denotes forward displacement in meters
  2. B denotes backward displacement in meters
  3. T denotes time taken to cover 1 meter
  4. FD denotes distance from Robot's starting position and the ditch in forward direction
  5. BD denotes distance from Robot's starting position and the ditch in backward direction

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

public class Catch22
{
    public static void main(String[] args) throws FileNotFoundException, IOException
    {
        BufferedReader br;
        br = new BufferedReader(new FileReader(args[0]));
        String line;
        int loc = 0 ,numOfTestCases = 0;
        int F,B,T,FD,BD,distanceFromCenter , totalDistanceCovered;
        while( ( line = br.readLine()) != null )
        {
            distanceFromCenter = 0;
            totalDistanceCovered = 0;
            ++loc;
            if ( loc > (numOfTestCases+1))
            {
                break;
            }
            else if ( loc == 1)
            {
                numOfTestCases = Integer.parseInt(line.trim());
                continue;
            }
            String[] tokens = line.trim().split("\\s+");
            F = Integer.parseInt(tokens[0].trim());
            B = Integer.parseInt(tokens[1].trim());
            T = Integer.parseInt(tokens[2].trim());
            FD = Integer.parseInt(tokens[3].trim());
            BD = Integer.parseInt(tokens[4].trim());
            if ( ( F == B) && ( F < FD) )
            {
                System.out.println("No Ditch");
                continue;
            }
            else
            {
                distanceFromCenter = F;
                totalDistanceCovered = F;
                while (true)
                {
                    if ( distanceFromCenter >= FD)
                    {
                        int time = (totalDistanceCovered+(FD-distanceFromCenter)) * T;
                        System.out.println(time+" F");
                        break;
                    }
                    distanceFromCenter = distanceFromCenter - B;
                    totalDistanceCovered = totalDistanceCovered + B;
                    if ( distanceFromCenter < 0 )
                    {
                        if ( (-1*distanceFromCenter) >= BD)
                        {
                            int time = (totalDistanceCovered+(BD-(-1*distanceFromCenter))) * T;
                            System.out.println(time+" B");
                            break;
                        }
                    }
                    distanceFromCenter = distanceFromCenter + F;
                    totalDistanceCovered = totalDistanceCovered + F;
                }
            }
        }
    }
}

Sunday, August 2, 2015

Mtable using matlab

function [mt , s] = mtable( n , m)
mt = zeros(n,m);
for c = 1 : m
    for r = 1 : n
        mt(r,c) = c*r;
    end
end
s = sum(sum(mt));
end

Identity using matlab

function [Q] = identity(n)
Q = zeros(n,n);
for c = 1 : n
    for r = 1 : n
        if c == r
            Q(r,c) = 1;
        end
    end
end
end

Checkerboard using matlab

function [ Q ] = checkerboard( n , m )
Q = ones(n,m);
for c = 1 : m
    for r = 1 : n
        if mod(r,2) == 0 && ~mod(c,2) == 0
            Q (r,c) = 0;
        elseif ~mod(r,2) == 0 && mod(c,2) == 0
            Q (r,c) = 0;
        end
    end
end
end

Randomness using matlab

function [Q] = randomness (limit , n , m )
Q = 1 + floor(rand(n,m)*limit);
end

Quadrants using matlab

function [Q] = quadrants(n)
Q = [ones(n) ones(n)+1 ; ones(n)+2 ones(n)+3];
end

Saturday, April 25, 2015

Prime numbers in a range given by user in C Language


#include <conio.h>

int main(int argc, char* argv[])
{
    int start = 0 , end = 0 ;
    printf("Enter the starting number in range");
    scanf_s("%d",&start);
    printf("Enter the ending number in range");
    scanf_s("%d",&end);
    for (int i = start; i < end ; i++)
    {
        int count = 0;
        for(int j = 1 ; j <= i ; j++)
        {
            if ( i % j == 0 )
            {
                count++;
                if ( count > 2)
                {
                    break;
                }
            }
        }
        if ( count <= 2 )
        {
            printf("%d\n",i);
        }
    }
    getch();
    return 0;
}

Saturday, April 18, 2015

Binary search implememtation in C Language

In previous post we have seen how we can search the list by using simple loop and process is called sequential search. This is useful when we have small lists. But in real world we encounter large lists having thousands or even millions of elements(data).

Iterating over such a large list using simple loop is inefficient in terms of time. Considering the large list having sorted elements we can employ binary search. Generally when storing the data itself if we stored them in sorted order makes our life simple at later part of time when we are retrieving data.

If you observe the name of search algorithm "Binary Search". It conveys we have two parts(Binary). The part of the list having the desired data and the part does not having the desired data.

The c code which explains the binary search is as follows:

int binarySearch(int* array, int size, int reqNum, bool *result )
{
    int startIdx;
    int endIdx;
    int midIdx;
   
    startIdx = 0;
    endIdx = size;
   
    while ( startIdx <= endIdx)
    {
        midIdx = ( startIdx + endIdx ) / 2 ;
        if (reqNum > array[midIdx])
        {
            startIdx = midIdx + 1;
        }
        else if (reqNum < array[midIdx])
        {
            endIdx = midIdx - 1;
        }
        else
        {
            startIdx = endIdx + 1;
        }
    }
    *result = ( reqNum == array[midIdx]);
    return midIdx+1;
}

The logic returns the position of the desired elements in the list. But if we dose not have the required data in the list then also the algorithm returns the 1. but before that we are comparing if the required number is present at the array[midIdx] if the number does not there we are passing the failure as the pointer to the calling function. By using that the calling function can determine weather the data is present in the list are not.

the calling function can be coded as

int main ()
{
    int a[10] = {1,2,120, 240, 256, 300,312, 440, 456, 512};
    bool result;
    int index = binarySearch(a,10, 0, &result );
    if (result)
    {
        printf("Required Number Present at %d position",index );
    }
    else
    {
        printf("Target not found");
    }
}

Sunday, March 15, 2015

Sequential Search using Array

In day to today programming we face lot of situations where we need to find something in the stored data. Generally the data is organized as arrays or in any form grouped together. If we are adding data to the already existing group we generally tend to add new data at the end of the group.
This leads to unsorted data. Searching unsorted data is time consuming. We have to go one element by element to find the desired data. consider basic scenario where we have 10 numbers stored in an array and that is unsorted. If we want to find if the desired number is present in that array or not then we have to read each element and we have to compare that with the desired one. If we put all the above in form of algorithm:


read the element from array
compare the element with the desired one
if both are matching stop the search we have desired one in array
else continue till we get the desired one or we reach end of array.

int getIndex(int *data, int length, int num)
{
    int i;
    for ( i = 0; i < length; i++)
    {
        if ( data[i] == num )
        {
            return i;
        }
    }
    return length+1;
}

and the main function to use the algorithm is
int main ()
{
    int a[10] = {1,2,56,34,21,67,22,99,88,0};
    int index = getIndex(a,10,9);
    if (index < 10)
    {
        printf ("The desired element is at position %d",index+1);
    }
    else
    {
        printf ("There is no such element in Array");
    }
}
in the function getIndex we are returning the index of the element if the desired number is present in array. If the desired number is not present in array we are returning length+1 so that the code in main function knows that there is no number which is matching our requirement.

Thursday, February 5, 2015

GCD of two number using C language

The gcd of two numbers is the largest number which divides the tow numbers with out leaving any reminder. gcd often known as greatest common factor (GCF), the highest common factor (HCF), and the greatest common measure (GCM).
In this post I will explain the calculation of GCD of tow numbers with Euclidean algorithm. This algorithm is recursive. So we can use recursion in any programming language which supports recursion to calculate GCD with Euclidean algorithm.
According to the algorithm the GCD of the two numbers will not change if the larger number is replaced with the difference of the small number and large number.
In each step of recursion we have to replace the large number with the difference of the small number and large number.
The implementation of the Euclidean algorithm for the problem is as simple as below

int calculateGCD (int num1 , int num2)
{
    if ( num2 == 0 )
    {
        return num1;
    }
    else if ( num1== 0 )
    {
        return num2;
    }
    return calculateGCD ( num2 , num1 % num2 );
}

in this algorithm we are returning the number if that is zero as a pre check. If both the numbers passed to the algorithm are non zeros then we have call the function itself till any one of the number becomes. in lase step when one of the number becomes zero we will return the number which is not zero to the previous step.

Sunday, November 16, 2014

Create and write text to the word document table using Apache POI in Java

In previous posts I explained how we can use Apache POI to read the text from word documents. It is the time to dwell into the writing of word documents using Java. You may get doubt  why to write word documents from Java(we can directly use word to write). But in so  many scenarios we directly work with data bases and some times we have to take the reports from database for further processing.

The database nothing more than tables in an organised and inter linked manner for easy retrieval of data. We can store that data into xls or we can use word tables to store for further use.

In this post I will explain how to write the tables in word document, how to create new rows, cells and putting data in the cells.

We are writing means we need one output stream to write to the disk. Obviously FileOutputStream comes handy. we will create object for FileOutputStream. Do not forget to catch the exceptions otherwise wisely throw them JVM is there to take care. But is is not good always to throw the exceptions.

FileOutputStream fos = new FileOutputStream("")

The next step is to create object for the word document. This is pretty straight forward just create object of type XWPFDocument.

XWPFDocument doc = new XWPFDocument()

All the thing(data) what we are going to write into above object will be part of our final word document which will be available after the finishing of our program(Java).

The next thing we have to do is to create table in word document to write the data into the cell. There are three steps we have to do sequentially to write the data to the table are creating the table in the XWPFDocument object, creating  row in that table and creating cell in the row to put the text.

XWPFTable table = doc.createTable()
XWPFTableRow row = table.getRow(0)

You may wonder how we can get the row with out creating it. One thing I want to make sure is that the table which we created will have default row. Just we are sing it as the table header row where we will keep all our columns headings. Now we are headed toward creating the cell in the row but not the first one as I said the default first row already has one for us.

The next step is creating one more cell if we want this looks like

XWPFTableCell cell1 = row.createCell()

if we want to set the text we can use

cell1.setText("")

After that based on our demand we can create as many rows as we need just be creating the row in the XWPFDocument object. One thing we have to be clear is we have to create the cells in the very first row only after that there is no need. Because the cells will be create automatically for us in the newly created rows of the table.

We have to get those cells and need to put the text.

The code snippet which will get you going will be

fos = new FileOutputStream("D:/POI/tableTest.docx");
            doc = new XWPFDocument();
            XWPFTable table = doc.createTable();
            XWPFTableRow row = table.getRow(0);
            row.getCell(0).setText("Name");
            XWPFTableCell cell1 = row.createCell();
            cell1.setText("Age");
            XWPFTableCell cell2 = row.createCell();
            cell2.setText("UID");
            for (int rows = 0; rows < 2 ; rows++ )
            {
                row = table.createRow();
                for (XWPFTableCell cell : row.getTableCells())
                {
                    cell.setText(" ");
                }
            }
            doc.write(fos);
            fos.close();

Do not forget to write the document by suing the line
            doc.write(fos)
The argument is just the object of FileOutPutStream which we have create earlier. The good way to end the logic is just by closing the all opened connections especially streams.


DC motor control with Pulse Width Modulation Part 1

DC Motor intro DC motor is a device which converts electrical energy into kinetic energy. It converts the DC power into movement. The typica...