Created
August 18, 2012 10:14
-
-
Save jsianes/3385855 to your computer and use it in GitHub Desktop.
Spotify 'lottery' test program solved
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.Scanner; | |
import java.io.BufferedInputStream; | |
public class Lottery { | |
public static double LotteryProbability (String lottery) { | |
int m=0,n=0,t=0,p=0,requiredForWin=0; | |
double result=0.0; | |
String[] number = lottery.split(" "); | |
m=Integer.parseInt(number[0]); | |
n=Integer.parseInt(number[1]); | |
t=Integer.parseInt(number[2]); | |
p=Integer.parseInt(number[3]); | |
requiredForWin=(int)Math.ceil((double)p/t); | |
if (requiredForWin>n) { return result; } | |
for (int i=requiredForWin;i<(Math.min(n,p)+1);i++) { | |
result+=probability(i,p,n,m); | |
} | |
return result; | |
} | |
private static double probability (int x, int p, int n, int m) { | |
double result=0.0,y=0.0; | |
y=combination(m,n); | |
if (y==0.0) { return result; } else { | |
result=combination(p, x)*combination(m-p, n-x)/y; | |
} | |
return result; | |
} | |
private static double combination(int n, int m) { | |
double result=1.0; | |
if ((m<0)||(m>n)) { return 0.0; } | |
if (m>(n-m)) { m=(n-m); } | |
for (int i=0;i<m;i++) { | |
result=result*(n-(m-(i+1))); | |
result=result/(i+1); | |
} | |
return result; | |
} | |
public static boolean validEntry (String line) { | |
int val1=0,val2=0,val3=0,val4=0; | |
boolean result=true; | |
String[] number = line.split(" "); | |
if (number.length==4) { | |
String n_line= new String (line.replaceAll("[0-9]+", "")); | |
if (n_line.length()!=3) { result=false; } else { | |
val1=Integer.parseInt(number[0]); | |
val2=Integer.parseInt(number[1]); | |
val3=Integer.parseInt(number[2]); | |
val4=Integer.parseInt(number[3]); | |
if ((val1<1)||(val2<1)||(val3<1)||(val4<1)) { result=false; } | |
if ((val1>1000)||(val2>val1)||(val3>100)||(val4>val1)) { result=false; } | |
} | |
} else { | |
result=false; | |
} | |
return result; | |
} | |
public static void main(String[] args) { | |
try { | |
double result=0.0; | |
Scanner sca = new Scanner(new BufferedInputStream(System.in)); | |
String line = sca.nextLine(); | |
if (validEntry(line)) { result=LotteryProbability(line); } | |
System.out.printf("%.10f\n", result); | |
} catch (Exception e) { | |
System.err.println("Error: " + e.getMessage()); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment