Popular Posts

Friday, June 1, 2012

Radius of sphere inscibed in tetrahedron

Given the lengths of the edges of a tetrahedron calculate the radius of a sphere inscribed in that tetrahedron (i.e. a sphere tangent to all the faces).
Input

An integer t, 1<=t<=30, denoting the number of test cases, followed by t lines, each containing 6 integers describing the lengths of the edges of a tetrahedron separated by single spaces. The edges are not longer than 1000 and for the tetrahedron WXYZ, the order of the edges is: WX, WY, WZ, XY, XZ, YZ.
Output

t lines, each consisting of a real number given with four digits decimal precision equal to the radius of a sphere inscribed in the given tetrahedron.
Example

Input:
2
1 1 1 1 1 1
1000 999 998 5 5 6

Output:
0.2041
1.4189

Refer this blog for formula : http://saketsaurabh.in/blog/2009/11/radius-of-a-sphere-inscribed-in-a-general-tetrahedron/
#include<stdio.h>
#include<math.h>
double area(double p,double q,double r)
{
double s=0,area1;
s=(p+q+r)/2;
area1=sqrt(s*(s-p)*(s-q)*(s-r));
return area1;
}
int main()
{
double a,b,c,d,e,f,x,y,A,B,C,D,E,F;
int t;
double v,s,r;
scanf("%d",&t);
while(t--)
{
s=0;
scanf("%lf%lf%lf%lf%lf%lf",&F,&B,&D,&C,&E,&A);
a=A*A;
b=B*B;
c=C*C;
d=D*D;
e=E*E;
f=F*F;
x=(a*c*d)+(b*c*d)+(a*b*e)+(b*c*e)+(b*d*e)+(c*d*e)+(a*b*f)+(a*c*f)+(a*d*f)+(c*d*f)+(a*e*f)+(b*e*f);
y=(a*b*d)+(a*c*e)+(b*c*f)+(d*e*f)+(c*c*d)+(c*d*d)+(b*b*e)+(b*e*e)+(a*a*f)+(a*f*f);
v=sqrt(x-y)/12;
s=area(B,C,F)+area(D,E,F)+area(B,A,D)+area(A,E,C);
r=(v*3)/s;
printf("%.4lf\n",r);
}
return 0;
}

Thursday, May 31, 2012

The Sports Stadium

The bustling town of Siruseri has just one sports stadium. There are a number of schools, colleges, sports associations, etc. that use this stadium as the venue for their sports events.
Anyone interested in using the stadium has to apply to the Manager of the stadium indicating both the starting date (a positive integer S) and the length of the sporting event in days (a positive integer D) they plan to organise. Since these requests could overlap it may not be possible to satisfy everyone.
It is the job of the Manager to decide who gets to use the stadium and who does not. The Manager, being a genial man, would like to keep as many organisations happy as possible and hence would like to allocate the stadium so that maximum number of events are held.
Suppose, for example, the Manager receives the following 4 requests:
Event No.Start DateLength
125
297
3156
493
He would allot the stadium to events 1, 4 and 3. Event 1 begins on day 2 and ends on day 6, event 4 begins on day 9 and ends on day 11 and event 3 begins on day 15 and ends on day 20. You can verify that it is not possible to schedule all the 4 events (since events 2 and 3 overlap and only one of them can get to use the stadium).
Your task is to help the manager find the best possible allotment (i.e., the maximum number of events that can use the stadium).
Input format
The first line of the input will contain a single integer N (N 100000) indicating the number of events for which the Manager has received a request. Lines 2,3,...,N+1 describe the requirements of the N events. Line i+1 contains two integer Si and Di indicating the starting date and the duration of event i. You may assume that 1 Si 1000000 and 1 Di 1000.
Output format
Your output must consist of a single line containing a single integer M, indicating the maximum possible number of events that can use the stadium.
Example:
Sample input:
4
2 5
9 7
15 6
9 3
Sample output:
3


import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.Comparator;

public class Main {
public static void main(String[] args) {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
int i, n = 0;
try {
n = Integer.parseInt(reader.readLine());
int[][] inputArray = new int[n][2];

for (i = 0; i < n; i++) {
String[] temp = reader.readLine().split(" ");
inputArray[i][0] = Integer.parseInt(temp[0]);
inputArray[i][1] = inputArray[i][0] + Integer.parseInt(temp[1]);
}

Arrays.sort(inputArray, new comp());
int prevEndDate = inputArray[0][1];
int maxEvents = 1;
for (i = 1; i < n; i++) {
if (inputArray[i][0] > prevEndDate) {
maxEvents++;
prevEndDate = inputArray[i][1];
}
}
System.out.println(maxEvents);
} catch (Exception e) {
System.out.print(e);
}
}
}

class comp implements Comparator {
int s1[] = new int[2];
int s2[] = new int[2];

public int compare(Object a1, Object a2) {
s1 = (int[]) a1;
s2 = (int[]) a2;

if (s1[1] < s2[1])
return -1;
else if (s1[1] > s2[1])
return 1;
else if (s1[0] < s2[0])
return -1;
else if (s1[0] > s2[0])
return 1;
else
return 0;
}
}
Refer : http://www.codechef.com/problems/STADIUM#

Tuesday, May 29, 2012

Maximum size name chopping

In the hidden country of Lapatrecta, an age old custom was followed to ensure that no outsider ever entered their country undetected. The security measure, though simple, was an effective one. Every person born in Lapatrecta had the initials of all his forefathers included in front of his name. Every once in a while, certain families became very famous and the initials of their ancestors were dropped from the names of all their descendants. Thus, there existed a nice homogeneity in the names of the people of Lapatrecta.
Now, a royal ball was organized at the behest of the Queen of Lapatrecta and all citizens were cordially invited to the event. The ball was being held to chop off the initials of the ancestors of the most distinguished family of the country. The Queen set the following 2 criteria for determining the most distinguished family from amongst the invitees:
1. The family must have more than 1 member living.
2. The length of the ancestor list of the family must be as long as possible.
For example:
For 3 people:

APJQ Ravi

APJRS Rahul

PJQ Bharat

Refer : http://www.codechef.com/problems/INSOMA4
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class NameChopping {

public static void main(String[] args) {

BufferedReader reader = new BufferedReader(new InputStreamReader(
System.in));
try {
int inputSize = Integer.parseInt(reader.readLine());
List<String> names = new ArrayList<String>();
for (int i = 0; i < inputSize; i++) {
names.add(reader.readLine());
}
// sort the string
Collections.sort(names);
getMaxSizeOfAncestors(names, inputSize);
} catch (Exception e) {
e.printStackTrace();
}

}

static void getMaxSizeOfAncestors(List<String> pNames, int collectionSize) {
int maxCount = 0;

// Check the starting letters of the names.If any two names have the
// same starting alphabets, then increase the count of maximum size.
for (int i = 1; i < collectionSize; i++) {
int tracker = 0;// temp variable
while (tracker < pNames.get(i - 1).length()
&& tracker < pNames.get(i).length()
&& pNames.get(i).charAt(tracker) == pNames.get(i - 1)
.charAt(tracker)) {
tracker++;
}

if (tracker > maxCount)
maxCount = tracker;
}
System.out.println(maxCount);
}

}

Monday, May 28, 2012

Sub array which forms the given sum

Given an unsorted array of nonnegative integers, find a continous subarray which adds to a given number.

 private static void checkSumExists(int[] a, int pRequiredSum) {
int length = a.length;
int currentSum = a[0];
int startIndex = 0;

for (int i = 1; i < length; i++) {
while (currentSum > pRequiredSum && startIndex<i-1) {
currentSum = currentSum - a[startIndex];
startIndex++;
}

if (currentSum == pRequiredSum) {
System.out.println("SubArray with startIndex : " + startIndex
+ " and endIndex : " + (i - 1)
+ " makes the given sum :" + pRequiredSum);
return ;
}

currentSum = currentSum + a[i];
}

System.out
.println("Sub array which makes the required sum doesn't exist : "
+ pRequiredSum);
}
Refer : http://www.geeksforgeeks.org/archives/19267

Saturday, May 26, 2012

Switching between implemenations of an interface at runtime in java

Do you remember that class that you would love put an "if" before each method? Or, that in witch you would love to catch all exceptions in a unique stretch of code? Some way to change the application flow without any change in existing class? If you are thinking in aspects, you're wrong! There is a way to make the same thing without add any class, api, framework, special compiler or virtual machine. It's pure and basic Java. In this step I would like to present the Proxy class at Reflection API that comes together with Java since version 1.3. 

The Proxy is a special class that allows intercept a set of methods identified by an interface. You can, for example, intercept all methods of a class to check if an attribute is not null or to catch possible exceptions in methods. E.g.: Let's say that the class below is present in our commercial systems: 

public class Sum {
public Integer value1;
public Integer value2;
 
public Sum(Integer val1, Integer val2) {
value1 = val1;
value2 = val2;
}
 
public Integer sum() {
return new Integer(value1.intValue() + value2.intValue());
}
 
}


This class will run? It'll find the correct result? Well, being optimistical, yes, it will do. But, if a null value was passed as a parameter to the constructor, the method sum() will throw a pretty NullPointerException. Who is catching that? Anyone. Who will be using the class never will remember (and wouldn't have) that the method sum() can launch a exception. What we can do for solve? We can use reflection to help the user. Here we go. 

First, we need an interface with the method to intercept. In our case, the sum(). 

public interface ISum {
public Integer sum();
}


After, we have to create a class that will handle the method call. This class will try to run the true method sum() in Sum class, if it fails, the NullPointerException must be catched and a zero value must return. The handle must implement the InvocationHandler interface and obviously implements the public Object invoke(Object proxy, Method method, Object[] args) method. This method will be called when the user invoke the method sum() in a Proxy class. The "try catch" will evict the NullPointerException. See above: 

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
 
public class Handler implements InvocationHandler {
 
public Sum trueSum;
 
public Handler(Sum sum) {
this.trueSum = sum;
}
 
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
try {
return method.invoke(trueSum, args);
} catch ( Exception e ) {
return new Integer(0);
}
}
}


And now, to be beautiful, we must implement a Sum factory. An object that will create the true Sum and the proxy class. Anyone can create a Sum class without this factory class. You can block this action with a private or protected constructor. 

import java.lang.reflect.Proxy;
 
public class SumFactory {
public ISum createSum(Integer val1, Integer val2) {
Sum sum = new Sum(val1, val2);
Handler handler = new Handler(sum);
Class[] interfacesArray = new Class[] {ISum.class};
 
return (ISum) Proxy.newProxyInstance(Sum.class.getClassLoader(), interfacesArray, handler);
}
}


As you can see, this class creates a Sum instance with the params to sum() and a handler to intercept the calls in a Proxy class. The var sum is passed into a Handler constructor to be the responsable to right result. The method newProxyInstance creates the Proxy class that will change the application flow, repassing responsibilities to handler. The var interfacesArray is an array of interfaces that have the methods to handler intercept. 

To finish, it's necessary declare Sum class implementing the ISum interface. If you don't do this the Proxy class will throw an Exception like:"Exception in thread "main" java.lang.IllegalArgumentException: object is not an instance of declaring class" on constructor. 

After, all this work, you can test with a simple class, like: 
public class Test {
public static void main(String[] args) {
ISum s = new SumFactory().createSum(null, new Integer(2));
System.out.println("Returns (null+2): "+s.sum());

s = new SumFactory().createSum(new Integer(3), new Integer(2));
System.out.println("Returns (3+2): "+s.sum());
}
}


Easy? Yes, the proxy class calls the handler that invokes que true sum() method and catch possible exceptions. 

Make a fair coin from a biased coin

Let the function_A return 0 with probability 40% and 1 with probability 60%. Generate afunction_B with probabilities 50-50 using only function_A only.

if you have a biased coin that comes up heads with probability p, and if you flip the coin twice, then:

The probability that it comes up heads twice is p2
The probability that it comes up heads first and tails second is p(1-p)
The probability that it comes up tails first ands heads second is (1-p)p
The probability that it comes up tails twice is (1-p)2
Now, suppose that you repeatedly flip two coins until they come up with different values. If this happens, what's the probability that the first coin came up heads? Well, if we apply Bayes' law, we get that

P(first coin is heads | both coins are different) = P(both coins are different | first coin is heads) P(first coin is heads) / P(both coins are different)

The probability that the first coin is heads is p, since any coin toss comes up heads with probability p. The probability that both coins are different given that the first coin is heads is the probability that the second coin came up tails, which is (1 - p). Finally, the probability that both coins are different is 2p(1-p), since if you look at the probability table above there are two ways this can happen, each of which has probability p(1-p). Simplifying, we get that

P(first coin is heads | both coins are different) = p (1-p) / (2p(1-p)) = 1 / 2.

But that's the probability that the first coin comes up tails if the coins are different? Well, that's the same as the probability that the first coin didn't come up heads when both coins are different, which is 1 - 1/2 = 1/2.

In other words, if you keep flipping two coins until they come up with different values, then take the value of the first coin you flipped, you end up making a fair coin from a biased coin!

In C, this might look like this:

bool FairCoinFromBiasedCoin() {
    bool coin1, coin2;
    do {
        coin1 = function_A();
        coin2 = function_A();
    } while (coin1 == coin2);

    return coin1;
}
The probability that it terminates on each iteration is 2p(1 - p). On expectation, this means that we need 1/(2p(1-p)) iterations before this loop will terminate. For p = 40%, this is 1/(2 x 0.4 x 0.6) = 1/0.48 ~= 2.083 iterations. Each iteration flips two coins, so we need, on expectation, about 4.16 coin flips to get a fair flip.

Installing graphic drivers for windows7

First download ATI Graphics Driver , it will install in  C:\swsetup\sp50231\Packages\Drivers\Display\W7_INF 
Right click your card in device manager, choose update driver software -> Browse -> Let me pick -> Have disk -> Browse -> Choose:  C:\swsetup\sp50231\Packages\Drivers\Display\W7_INF click next and ignore the warning. after its updated restart your pc and you'll have ati mobility radeon hd 5470 again 

Installing apache tomcat with SSL configuration

There are some common situations where you might do this:
This page describes how to configure mod_proxy. We describe two options:

Simple configuration

Set the context path

Set your Confluence application path (the part after hostname and port) correctly. Say you want Confluence available at http://www.example.com/confluence/, and you currently have it running at http://localhost:8090/. The first step is to get Confluence available at http://localhost:8090/confluence/.
To do this in Tomcat (bundled with Confluence), edit conf/server.xml, locate the "Context" definition:
<Context path="" docBase="../confluence" debug="0" reloadable="true">
and change it to:
<Context path="/confluence" docBase="../confluence" debug="0" reloadable="true">
Then restart Confluence, and ensure you can access it at http://localhost:8090/confluence/

Configure mod_proxy

Now enable mod_proxy in Apache, and proxy requests to the application server by adding the example below to your Apache httpd.conf (note: the files may be different on your system; the JIRA docs describe the process for Ubuntu/Debian layout):
# Put this after the other LoadModule directives
LoadModule proxy_module /usr/lib/apache2/modules/mod_proxy.so
LoadModule proxy_http_module /usr/lib/apache2/modules/mod_proxy_http.so
# Put this in the main section of your configuration (or desired virtual host, if using Apache virtual hosts)
ProxyRequests Off
ProxyPreserveHost On
<Proxy *>
    Order deny,allow
    Allow from all
</Proxy>
ProxyPass /confluence http://localhost:8090/confluence
ProxyPassReverse /confluence http://localhost:8090/confluence
<Location /confluence>
    Order allow,deny
    Allow from all
</Location>
 Note to Windows Users

Set the URL for redirection

You will need to modify the server.xml file in your tomcat's conf directory and set the URL for redirection.
Locate this code segment
<Connector port="8090" maxHttpHeaderSize="8192"
               maxThreads="150" minSpareThreads="25" maxSpareThreads="75"
               enableLookups="false" redirectPort="8443" acceptCount="100"
               connectionTimeout="20000" disableUploadTimeout="true" />
And append the following segment:
<Connector port="8090" maxHttpHeaderSize="8192"
               maxThreads="150" minSpareThreads="25" maxSpareThreads="75"
               enableLookups="false" redirectPort="8443" acceptCount="100"
               connectionTimeout="20000" disableUploadTimeout="true"
               proxyName="www.example.com" proxyPort="80" />
Replace www.example.com with the URL you wish to be redirected to.
If this isn't working for you, try adding a scheme attribute to your Connector tag: scheme="https".

Set the Confluence Base URL

The last stage is to set the Base URL to the address you're using within the proxy. For example, if you're using http://www.example.com then set your Base URL to this.

Complex configuration

Complex configuration involves using the mod_proxy_html filter to modify the proxied content en-route. This is required if the Confluence path differs between Apache and the application server. For example:
Notice that the application path in the URL is different in each. On Apache, the path is /, and on the application server the path is /confluence.
For this configuration, you need to install the mod_proxy_html module, which is not included in the standard Apache distribution.
Alternative solutions are discussed below.
# Put this after the other LoadModule directives
LoadModule proxy_module modules/mod_proxy.so
LoadModule proxy_http_module modules/mod_proxy_http.so
LoadModule proxy_html_module modules/mod_proxy_html.so
<VirtualHost *>
    ServerName confluence.example.com
     
    # Put this in the main section of your configuration (or desired virtual host, if using Apache virtual hosts)
    ProxyRequests Off
    ProxyPreserveHost On
    <Proxy *>
        Order deny,allow
        Allow from all
    </Proxy>
     
     
    ProxyHTMLURLMap / /confluence/
     
    <Location />
        Order allow,deny
        Allow from all
    </Location>
</VirtualHost>
The ProxyHTMLURLMap configuration can become more complex if you have multiple applications running under this configuration. The mapping should also be placed in a Location block if the web server URL is a subdirectory and not on a virtual host. The Apache Week tutorial has more information how to do this.

Adding SSL

If you're running Apache in front of Tomcat, it's a good idea to terminate your SSL configuration at Apache, then forward the requests to Tomcat over HTTP. You can set up Apache to terminate the SSL connection and use the ProxyPass and ProxyPassReverse directives to pass the connection through to Tomcat (or the appropriate application server) which is running Confluence.
  1. Create a new SSL host by creating a virtual host on 443
  2. The standard http connection on apache could be used to redirect to https if you want or it could just be firewalled.
  3. Within the VirtualHost definition:
    1. define the SSL options (SSLEngin and SSLCertificateFile)
    2. define the ProxyPass and ProxyPassReverse directives to pass through to Tomcat.
Most of the relevant Apache Config:
Listen 443
NameVirtualHost *:443
<VirtualHost *:443>
    SSLEngine On
    SSLCertificateFile /etc/apache2/ssl/apache.pem
    ProxyPass / http://localhost:8090/
    ProxyPassReverse / http://localhost:8090/
</VirtualHost>
Apart from the Apache configuration there is a couple of things you will need to do before you get your server working:
  1. You will have to change your base URL to point o https addresses. See the documentation on configuring the server base URL.
  2. We need to set up the connector to use https. In your installation directory, edit the file server.xml and add this attributes to your connector:
proxyName="proxy.example.com" proxyPort="443" scheme="https"

More information

Alternatives

If Tomcat is your application server, you have two options:
  • use mod_jk to send the requests to Tomcat
  • use Tomcat's virtual hosts to make your Confluence application directory the same on the app server and the web server, removing the need for the URL mapping.
If your application server has an AJP connector, you can:
  • use mod_jk to send the requests to your application server.