# 关于Comparable与compareTo,该如何处理

www.MyException.Cn  网友分享于：2013-01-30  浏览：28次

import java.math.BigInteger;
import java.util.Arrays;
public class Lottery
{
public String[] sortByOdds(String[] rules)
{
Ticket[] tickets=new Ticket[rules.length];
for(int i=0;i<rules.length;i++)
tickets[i]=new Ticket(rules[i]);
Arrays.sort(tickets);

String[] names=new String[rules.length];
for(int i=0;i<rules.length;i++)
names[i] = tickets[i].name;
return names;
}
private class Ticket implements Comparable
{
private String name;
private int choices,blanks;
private boolean sort,unique;
private BigInteger probability;
Ticket(String rule)
{
String[] token=rule.split(":");
this.name = token[0];
token = token[1].trim().split(" ");
this.choices = Integer.valueOf(token[0]);
this.blanks = Integer.valueOf(token[1]);
this.sort = token[2].equalsIgnoreCase("T");
this.unique = token[3].equals("T");

if (!sort && !unique)
probability = BigInteger.valueOf((long)Math.pow(choices, blanks));
else if (!sort && unique)
getBinomial(choices,blanks).multiply(getFactorial(blanks));
else if (sort && !unique)
getBinomial(choices+blanks-1,blanks);
else
getBinomial(choices,blanks);
}
public BigInteger getBinomial(int n,int m)
{
return getFactorial(n).divide(getFactorial(m).multiply(getFactorial(n-m)));
}
public BigInteger getFactorial(int n)
{
BigInteger factorial = BigInteger.ONE;
for (int i=1;i<=n;i++)
factorial.multiply(BigInteger.valueOf(n+1));
return factorial;
}
public int compareTo(Object O)
{
Ticket ticket =(Ticket)O;
if (this.probability.equals(ticket.probability))
return this.name.compareTo(ticket.name);
return this.probability.compareTo(ticket.probability);

}

}
}

------解决方案--------------------

------解决方案--------------------