1 package icecream;
2 
3 public class PolymerTrimmer {
4 
parse(String arg, String a, String b)5 	public static boolean parse(String arg, String a, String b){
6 		if(a.equalsIgnoreCase("minPolymer")){
7 			minPolymer=Integer.parseInt(b);
8 		}else if(a.equalsIgnoreCase("minFraction")){
9 			float f=Float.parseFloat(b);
10 			setMinFraction(f);
11 		}else if(a.equalsIgnoreCase("polyerror")){
12 			float f=Float.parseFloat(b);
13 			setMinFraction(1-f);
14 		}else{
15 			return false;
16 		}
17 		return true;
18 	}
19 
testLeft(byte[] bases, char symbol)20 	public static int testLeft(byte[] bases, char symbol){return testLeft(bases, (byte)symbol);}
21 
testLeft(byte[] bases, byte symbol)22 	public static int testLeft(byte[] bases, byte symbol){
23 		float score=0;
24 		float max=0;
25 		int maxPos=-1;
26 		for(int i=0; i<bases.length && score>=minScore; i++){
27 			byte b=bases[i];
28 			if(b==symbol){
29 				score++;
30 				if(score>max){
31 					max=score;
32 					maxPos=i;
33 				}
34 			}else{
35 				score-=penalty;
36 			}
37 		}
38 		int trim=maxPos+1;
39 		return (trim<minPolymer ? 0 : trim);
40 	}
41 
testRight(byte[] bases, char symbol)42 	public static int testRight(byte[] bases, char symbol){return testRight(bases, (byte)symbol);}
43 
testRight(byte[] bases, byte symbol)44 	public static int testRight(byte[] bases, byte symbol){
45 		float score=0;
46 		float max=0;
47 		int maxPos=bases.length;
48 		for(int i=bases.length-1; i>=0 && score>=minScore; i--){
49 			byte b=bases[i];
50 			if(b==symbol){
51 				score++;
52 				if(score>max){
53 					max=score;
54 					maxPos=i;
55 				}
56 			}else{
57 				score-=penalty;
58 			}
59 		}
60 		int trim=bases.length-maxPos;
61 		return (trim<minPolymer ? 0 : trim);
62 	}
63 
setMinFraction(float f)64 	public static void setMinFraction(float f){
65 		assert(f>=0 && f<=1) : f;
66 		minFraction=f;
67 		penalty=(f>=1 ? 99 : ((1f/(1-minFraction))-1));
68 		minScore=(f>=1 ? 0 : -4*penalty);
69 	}
70 
71 	static int minPolymer=5;
72 	private static float minFraction=0.8f;
73 	private static float penalty=(1f/(1-minFraction))-1;
74 	private static float minScore=-4*penalty;
75 
76 }
77