Sunday, March 24, 2013

Distance between point and the line Part 2

After I published my first solution I got feedback that the same can be achieved calculating other way. So I tried implement another way:
public double distanceBetweenLineAndPoints(Point a, Point b, Point c){
    double dx = a.x - b.x;
    double dy = a.y - b.y;
    if(dy == 0){
        //we have vertical line
        return distanceBetweenPoints(new Point(c.x, a.y), c);
    }
    if(dx == 0){
        //we have horizontal line
        return distanceBetweenPoints(new Point(a.x, c.y), c);
    }
    double slope = dy / dx;
    //lets check - may be c point is on the line
    if(c.y - a.y == slope * (c.x - a.x)){
        //yes, it is
        return 0;
    }
    Point aa = new Point();
    Point bb = new Point();
    aa.x = c.x;
    aa.y = slope * (c.x - a.x)+ a.y;
    bb.x = (c.y - a.y)/slope + a.x;
    bb.y = c.y;

    return (distanceBetweenPoints(bb, c) / distanceBetweenPoints(aa, bb)) * 
   distanceBetweenPoints(aa, c);
}

Is it faster?

I did two tests:
1. I took solution 1 and 2 gave them the same data (line is not horizontal/vertical and point is not on the line) - solution 1 was 10-15% faster.
2. I add the same checking (the line is vertical/horizontal or point is on the line) to solution 1 and repeated test - both solution were performing almost identically.

Friday, March 22, 2013

Distance between point and the line


Hei, I got Challenge to my email and I thought - why not :)

Distance:
In 2D coordinate system we have three points A(x,y) B(x,y) C(x,y)
where x,y can be positive and negative integer numbers
If Points A and B define endless line, write function which returns the 
distance between point C and the line defined by point A, B
 
I havn't thought it will be so easy:

public class DistanceCalculator {
    public static double distanceBetweenPoints(Point p1, Point p2){
        int dx = p1.x - p2.x;
        int dy = p1.y - p2.y;
        return Math.sqrt(dx*dx + dy*dy);
    }
    public static double distanceBetweenLineAndPoints(Point a, Point b, Point c){
        //lets find area of triangle
        double ab = distanceBetweenPoints(a, b);
        double bc = distanceBetweenPoints(b, c);
        double ca = distanceBetweenPoints(c, a);
        double p = (ab + bc + ca)/2;

        double area = Math.sqrt(p*(p-ab)*(p-bc)*(p-ca));

        return (area*2)/ab;
    }
}
public class Point {
    public int x;
    public int y;

    public Point (int x, int y){
        this.x = x;
        this.y = y;
    }
}
If you like it - there is also Part2.

Thursday, December 6, 2012

RXTXComm lirary NullPointerException at gnu.io.RXTXPort.setSerialPortParams(RXTXPort.java:178)

RXTXComm library is great, but if you want to use it from not signed applet - you could get NullPointerException exception like this:
java.lang.NullPointerException
     at gnu.io.RXTXPort.setSerialPortParams(RXTXPort.java:178)
     at JAppletExample$Captura$1.run(JAppletExample.java:79)
     at java.security.AccessController.doPrivileged(Native Method)
     at JAppletExample$Captura.connect(JAppletExample.java:62)
     at JAppletExample.actionPerformed(JAppletExample.java:45)
     at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
     at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)
     at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
     at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
     at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(Unknown Source)
     at java.awt.Component.processMouseEvent(Unknown Source)
     at javax.swing.JComponent.processMouseEvent(Unknown Source)
     at java.awt.Component.processEvent(Unknown Source)
     at java.awt.Container.processEvent(Unknown Source)
     at java.awt.Component.dispatchEventImpl(Unknown Source)
     at java.awt.Container.dispatchEventImpl(Unknown Source)
     at java.awt.Component.dispatchEvent(Unknown Source)
     at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
     at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
     at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
     at java.awt.Container.dispatchEventImpl(Unknown Source)
     at java.awt.Component.dispatchEvent(Unknown Source)
     at java.awt.EventQueue.dispatchEvent(Unknown Source)
     at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
     at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
     at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
     at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
     at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
     at java.awt.EventDispatchThread.run(Unknown Source)
    

To fix it - add this line to java.policy file:
permission "java.util.PropertyPermission" "gnu.io.log.mode", "read";

Tuesday, June 19, 2012

JQWicket date picker

JQWicket is JQeury wrapper for Wicket. To get started import maven dependency:
   <dependency> 
       <groupId>com.google.code.jqwicket</groupId> 
       <artifactId>jqwicket</artifactId> 
       <version>0.8</version> 
   </dependency>
Java code:
In you application init method add these lines. They will include JQeury javascript libs to your pages.
import com.google.code.jqwicket.JQComponentOnBeforeRenderListener;
import com.google.code.jqwicket.JQContributionConfig;

super.getComponentPreOnBeforeRenderListeners().add(
    new JQComponentOnBeforeRenderListener(
        new JQContributionConfig().withDefaultJQueryUi()));

Then in your page:
import com.google.code.jqwicket.ui.datetimepicker.DateTimePickerTextField;


public class DatePickerPage extends WebPage {
    Logger log = LoggerFactory.getLogger(DatePickerPage.class);
    Date date = new Date();

    public DatePickerPage() {
        Form form = new Form("form"){
            @Override
            protected void onSubmit() {
                log.info("return value:"+date);
            }
        };
        form.add(new DateTimePickerTextField<Date>("datetimepicker", new PropertyModel<Date>(this, "date")));
        form.add(new SubmitLink("submit"));
        add(form);
    }
//Add getter and setter for a date
}
And your HTML should look something like this:
!DOCTYPE html>
<html xmlns:wicket="http://wicket.apache.org">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
</head>
<body>
<form wicket:id="form">
    Date: <input type="text" wicket:id="datetimepicker"/>
    <a wicket:id="submit">Go</a>
</form>
</body>
</html> 

Result:


But I still like more another date picker, because out of the box this one:
1. It looks over sized;
2. You need to convert its value from String to Date manually.

Tuesday, June 12, 2012

Zebra Puzzle gets solved in Java

For one of job interview I was asked for Zebra Puzzle solution in Java.
Considering you have input file provided bellow you need to create output xml.
Input:
5
SAME;nationality;English;color;Red
SAME;nationality;Spaniard;pet;Dog
SAME;drink;Coffee;color;Green
SAME;drink;Tea;nationality;Ukrainian
TO_THE_LEFT_OF;color;Green;color;Ivory
SAME;smoke;Old gold;pet;Snails
SAME;smoke;Kools;color;Yellow
SAME;drink;Milk;position;3
SAME;nationality;Norwegian;position;1
NEXT_TO;pet;Fox;smoke;Chesterfields
NEXT_TO;smoke;Kools;pet;Horse
SAME;smoke;Lucky strike;drink;Orange juice
SAME;smoke;Parliaments;nationality;Japanese
NEXT_TO;nationality;Norwegian;color;Blue
SAME;drink;Water
SAME;pet;Zebra

Output:
<solutions>
  <solution>
    <house color="Yellow" drink="Water" nationality="Norwegian" pet="Fox" position="1" smoke="Kools"/>
    <house color="Blue" drink="Tea" nationality="Ukrainian" pet="Horse" position="2" smoke="Chesterfields"/>
    <house color="Red" drink="Milk" nationality="English" pet="Snails" position="3" smoke="Old gold"/>
    <house color="Ivory" drink="Orange juice" nationality="Spaniard" pet="Dog" position="4" smoke="Lucky strike"/>
    <house color="Green" drink="Coffee" nationality="Japanese" pet="Zebra" position="5" smoke="Parliaments"/>
  </solution>
</solutions>

You can download source code and JUnit tests here. Inside that zip you will also find xslt to render xml nice way.

Solution

So, we have to fill [5,6] array. The easiest way would be to check all possible combinations, but that will be slow because there are (5!)^6=2985984000000 combinations. To speedup we prefill array with data we already know is correct: we have all nationalities and additional attribute to them. That will leave us to fill array [5,4] i.e. (5!)^4=207360000. It is already 10000 times less combinations.
Next step is to start guessing values. But not randomly. Lets start from color because it has biggest amounts of clues and because of that some rules will fail immediately and we will not need to go deeper and fill other values. Then - go deeper and take another key with highest amount of clues.
The code provides solution in 90-1460 iterations.

Monday, June 11, 2012

Nice Action buttons meets Wicket

For my Block A Sender project I needed nice action buttons. I was lucky to find this post.  Here is how they look:
Google style buttons
To get them in Wicket is really simple:
  1. Grab CSS from this post. and add to your project
  2. Add some link in java:
     add(new BookmarkablePageLink("home_link", HomePage.class));
  3. And HTML
    <button class="action bluebtn" wicket:id="home_link">Home</button>
That's it :)

Friday, May 18, 2012

Wicket & Guice - how to start service on application start

I have Wicket web application and I am using Guice to inject services whatever I want. Some thing like here. Everything works great, but I needed to run some recovery routine on application startup. The only way I found is this:
public class WicketApplication extends WebApplication{
    @Override
 public void init()
 {
  super.init();

        GuiceModule guiceModule = new GuiceModule(usesDeploymentConfig());
        GuiceComponentInjector injector = new GuiceComponentInjector(this, guiceModule);
        getComponentInstantiationListeners().add(injector);
        
        //Here is interesting part
        GuiceInjectorHolder holder = Application.get().getMetaData(GuiceInjectorHolder.INJECTOR_KEY);
        holder.getInjector().getProvider(EmailSenderService.class).get().recover();
    }
}

Enjoy!