Sunday, August 9, 2015

Equation

Cost = $$c = c_1 x + c_2y$$ where \(c_1\) is cost of travelling on water and \(c_2\) is cost of travelling on land. As per the given condition, $$c_1 = \frac{c_2}{2}$$ Hence the equation becomes: $$c = \frac{cx}{2} + cy$$
$$ => c = c(x/2 + y)$$
Also, as per the given figure, the relation between \(x\) and \(y\) can be represented as follows: $$y^2 = (a-x)^2 + d^2$$
$$=> y = \sqrt{(a-x)^2 + d^2}                               \cdots 1 $$                                                  
The objective is to minimize the cost function c. So $$ \frac{d}{dx}c[\frac{x}{2}+ \sqrt{(a-x)^2 + d^2}] = 0$$ Solving the above differential equation: $$\frac{1}{2} - \frac{2(a - x)}{2\sqrt{(a-x)^2 + d^2}} = 0$$ $$=> \frac{1}{2} = \frac{(a - x)}{\sqrt{(a-x)^2 + d^2}} $$ Squaring both sides, we get: $$=> \frac{1}{4} = \frac{(a - x)^2}{(a-x)^2 + d^2} $$ $$=> 4(a-x)^2 = (a-x)^2 + d^2$$ $$ => 3(a-x)^2 = d^2$$$$ => x = a - \frac{d}{\sqrt{3}}$$ From equation 1 above, $$y = \frac{2}{\sqrt3}d$$

Saturday, August 8, 2015

Robot's move

Problem : Robot's move
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 an obstacle after distance D from initial position in forward direction. This forward and backward movement is performed repeatedly by the Robot.

Your task is to calculate amount of time taken before the Robot hits the obstacle.

Input Format:
First line contains total number of test cases, denoted by N
Next N lines, contain a tuple containing 4 values delimited by space
F B T D, 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. D denotes distance from Robot's starting position and the obstacle in forward direction

Output Format:

For each test case print time taken by the Robot to hit the obstacle

Constraints:
First move will always in forward direction
1 <= N <= 100
backward displacement < forward displacement i.e. (B < F)
forward displacement (F) > 0
backward displacement (B) > 0
time (T) > 0
distance (D) > 0
All input values must be positive integers only

Sample Input and Output

SNo.InputOutput
1
2
5 4 8 10
8 2 3 15

400
69

Solution:
Find the distance to the point just before the last forward cycle starts. Find the time taken to reach this point. Beyond this point just add the time taken to take the forward steps.

C++ Program:
#include <iostream>
using namespace std;

int main(void) 
{
 int F,B,T,D;
 int N;
 cin>>N;
 while(N--)
 {
  cin>>F>>B>>T>>D;
  int forward = F-B; //The distance moved by robot in one forward and backward cycle
  int timeInOneCycle = (F+B)*T; //The time taken by robot to complete one forward and backward cycle
  int secondLastDistance = D-F; //The distance that the robot has to move before it can hit the obstacle
  int timeToSecondLastDistance = 0;
  int quotient = secondLastDistance/forward; //The number of forward and backward cycles needed to reach the secondLastDistance
  int remainder = secondLastDistance%forward;
  timeToSecondLastDistance = timeInOneCycle*quotient; //The time taken to reach the secondLastDistance
  int currentDistance = quotient*forward; //The distance covered by robot after completing quotient number of cycles
  int remainingTime = 0;
  int remainingDistance = D-currentDistance; //The distance remaining from the secondLastDistance point
  if(secondLastDistance <= 0) //If the total distance needed to be covered is less than or equal to the distance F covered by robot in forward direction
  {
   timeToSecondLastDistance = D*T;
  }
  else if(remainingDistance <= F) //If the remaining distance needed to be covered is less than or equal to the distance F covered by robot in forward direction
  {
   remainingTime = remainingDistance*T;
  }
  else //If the quotient calculated above is less than the number of cycles needed to reach the secondLastDistance point
  {
   currentDistance = currentDistance + forward;
   remainingTime = remainingTime + timeInOneCycle;
   remainingDistance = remainingDistance - forward;
   remainingTime = remainingTime + remainingDistance*T;
  }
  cout<<timeToSecondLastDistance + remainingTime<<endl;
 }
 return 0;
}

Sunday, July 26, 2015

Income Tax Calculation in India 2014-15

A good website describing the calculation with example is as follows: Learn-how-to-calculate-your-income-tax

An example calculation with an annual income of Rs 12,00,000.00 (where the income spans over all the three tax slabs), is shown below:

Slab
Income Slab (Rs.)
Income Tax Rate
Income Tax
Income Tax Amount
0
0 to 2,50,000
NIL
0
0
I
2,50,001-5,00,000
10%
10% of 2,50,000
25,000
II
5,00,001-10,00,000
20%
20% of 5,00,000
10,00,00
III
10,00,001 and above
30%
30% of (12,00,000 – 10,00,000)
= 30% of 2,00,000
60,000
Total Income Tax Amount
1,85,000
 
 Explanation:
If your income falls in Slab I, tax will be deducted on the amount that exceeds Rs. 2,50,001/- . Similarly, tax for Slab II and Slab III will be calculated for the amount that exceeds Rs. 5,00,001/- and Rs. 10,00,001/- respectively.

If the income lies above Slab III, then the tax in Slab I is calculated as 10% of (5,00,000 - 2,50,000) and tax in Slab II is calculated as 20% of (10,00,000 - 5,00,000). And the tax Slab III is calculated as 30% of (Annual Income - 10,00,000).

Wednesday, July 22, 2015

How to set the debug console buffer limit in Eclipse

  1. Click on Window -> Preferences
  2. In type filter text box, search for "Console"
  3. Select Console under Run/Debug
  4. For setting a limit, check the "Limit Console Output" check-box, and set the character limit in "Console buffer size (characters)" text box.
  5. For setting the Console buffer size to unlimited, uncheck the "Limit Console Output" check-box.

Wednesday, July 1, 2015

Java code to read and write objects in AWS S3


import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.Date;
import org.apache.log4j.Logger;
import amazon.odin.awsauth.OdinAWSCredentialsProvider;
import com.amazonaws.HttpMethod;
import com.amazonaws.auth.AWSCredentials;
import com.amazonaws.auth.AWSCredentialsProvider;
import com.amazonaws.services.s3.model.GeneratePresignedUrlRequest;
import com.amazonaws.services.s3.model.S3Object;

public class S3Utils {
 public static final String MATERIAL_SET = "<material_set_name>";
 public static final String BUCKET = "<bucket_name>";
 public static final Integer S3_URL_VALIDITY_PERIOD_MILLISEC = 1000*60*60; // S3 url should be valid for 1 hour.
 private static final Logger logger = Logger.getLogger(S3Utils.class);
 private static final String folder = "<folder_name>";
 
 public static String writeToS3(File file, String folder) {
  com.amazonaws.services.s3.AmazonS3 s3Client = new com.amazonaws.services.s3.AmazonS3Client(
    getAWSCredentials());
  String key = file.getName();
  System.out.println("Going to write to key " + folder + key + " in S3");
  s3Client.putObject(BUCKET, folder + key, file);
  
  //This generates a URL that can be used to download the uploaded file.
  Date expiration = new Date();
  long msec = expiration.getTime();
  msec += S3_URL_VALIDITY_PERIOD_MILLISEC;
  expiration.setTime(msec);
  GeneratePresignedUrlRequest generatePresignedUrlRequest = new GeneratePresignedUrlRequest(BUCKET, folder + key);
  generatePresignedUrlRequest.setMethod(HttpMethod.GET);
  generatePresignedUrlRequest.setExpiration(expiration);
  URL s = s3Client.generatePresignedUrl(generatePresignedUrlRequest);
  if(s == null) {
   System.out.println("Url returned was null");
   return null;
  }
  System.out.println("S3 Url: " + s.toString());
  return s.toString();
 }
 
 public static String readFromS3(String folder, String key) {
  StringBuilder sb = new StringBuilder();
  com.amazonaws.services.s3.AmazonS3 s3Client = new com.amazonaws.services.s3.AmazonS3Client(
    getAWSCredentials());
  
  S3Object s3object = s3Client.getObject(BUCKET, folder + key);
  InputStream is = s3object.getObjectContent();
  BufferedReader br = new BufferedReader(new InputStreamReader(is));
  
  String line;
  try {
   while((line = br.readLine()) != null) {
    System.out.println(line);
    sb.append(line);
   }
  } catch (IOException e) {
   e.printStackTrace();
  }
  return sb.toString();
 }
 
 private static AWSCredentials getAWSCredentials() {
  AWSCredentialsProvider credentialsProvider = new OdinAWSCredentialsProvider(MATERIAL_SET);
     AWSCredentials credentials = credentialsProvider.getCredentials();
        return credentials;
    }
}

Sunday, June 28, 2015

Spiral Order Traversal of Two Dimensional Matrix - 1

Problem:

Given a two dimensional array, print the elements in spiral order starting at the top left corner.

Example:

Output:

1 2 3 4 8 12 16 15 14 13 9 5 6 7 11 10

Java Program:

public class SpiralOutToIn {
 public static void main(String[] args) {
  int [][] A = {{1,2,3,4},{5,6,7,8},{9,10,11,12},{13,14,15,16}}; //m x n, m=n, m and n even 
  //int [][] A = {{1,2,3},{5,6,7},{9,10,11}}; //m x n, m=n, m and n odd
  //int [][] A = {{1,2,3,4},{5,6,7,8},{9,10,11,12}}; //m x n, m < n, m odd and n even
  //int [][] A = {{1,2,3,4,17},{5,6,7,8,18},{9,10,11,12,19},{13,14,15,16,20}}; //m x n, m < n, m even and n odd
  //int [][] A = {{1,2,3},{5,6,7},{9,10,11},{13,14,15}}; //m x n, m > n, m even and n odd
  //int [][] A = {{1,2,3,19},{5,6,7,20},{9,10,11,21},{13,14,15,22},{16,17,18,23}}; //m x n, m > n, m odd and n even
  //Boundary Value Test Cases
  //int [][] A = {{}};
  //int [][] A = {{1}};

  int layer = 0;
  //Go till half the length of the array.
  int maxLayer = A.length % 2 == 0 ? A.length/2 - 1 : A.length/2;
  while(layer <= maxLayer) {
   int i=layer;
   int j=layer;
   //Left to Right
   for(j=layer; j<=A[i].length-1-layer;j++) {
    System.out.print(A[i][j] + " ");
   }
   j = A[i].length - 1 -layer;
   //Top to Down
   for(i=layer + 1; i <= A.length - 1 - layer; i++) {
    System.out.print(A[i][j] + " ");
   }
   i = A.length - 1 - layer;
   //Right to Left
   for(j=A[i].length - 2 - layer; j >= layer; j--) {
    System.out.print(A[i][j] + " ");
   }
   j = layer;
   //Down to Top
   for(i=A.length - 2 - layer; i>=layer + 1; i--) {
    System.out.print(A[i][j] + " ");
   }
   layer++;
  }
 }
}

Sunday, April 5, 2015

Robot Steps

.Problem:
A robot can take 2, 3 or 5 steps at a time. Given the difference (total number of steps) between source and destination, find the number of ways the robot can reach from source to destination.

Sample Input:
1
2
3
4
5
6
7
8
9

Sample Output:
0
1 
1
1
3
2
5
6
8

Solution:
The solution to these problems can be generalized in the following manner:
If a robot can take a, b, c, ... steps to move from one position to another, then the total number of ways to traverse a particular number of steps n is:
A[n] = A[n-a] + A[n-b] + A[n-c] + ...

So in this case, the recurrence formula is:
A[n] = A[n-2] + A[n-3] + A[n-5]