Jonckheere-Terpstra

import java.io.IOException;

public class Jonckheere {
	int nGroup;
	int nRecord;
	int[] nRecPerGroup;
	double[][] data;
	//double[][] rank;
	double T;
	//double Tinv;
	double p;
	//double pinv;

	/**
	 * @param args
	 */
	public static void main(String[] args) throws IOException {
		// TODO 自動生成されたメソッド・スタブ
		int n=10;
		double[] d2=new double[n];
		for(int i=0;i<d2.length;i++){
			d2[i]=Math.random();
		}
		d2[3]=d2[6];
		d2[2]=d2[5];
		d2[4]=d2[5];
		double[] d={1,3,5,2,4,6,3};
		//int[][] sortorder = MiscUtil.bublSortSameVals(d2);
		
		double[][] d3={{1,4,6},{2,3,2,5},{1,6,2,3,4}};
		Jonckheere kw = new Jonckheere(d3);
		org.apache.commons.math.distribution.NormalDistributionImpl st = 
			new org.apache.commons.math.distribution.NormalDistributionImpl();
		try{
			kw.p=Math.min(1-st.cumulativeProbability(kw.T),st.cumulativeProbability(kw.T));
			//kw.pinv=Math.min(1-st.cumulativeProbability(kw.Tinv),st.cumulativeProbability(kw.Tinv));
			
		} catch (org.apache.commons.math.MathException ex) {
			
		}
		System.out.println("T=\t"+kw.T+"\n"+"p=\t"+kw.p);
		//System.out.println("Tinv=\t"+kw.Tinv+"\n"+"pinv=\t"+kw.pinv);


		
		
	}
	
	public Jonckheere(double[][] d){
		nGroup=d.length;
		nRecPerGroup=new int[nGroup];
		//rank=new double[nGroup][0];
		double sqNRecPerGroup=0;
		double sqNRecPerGr2=0;
		for(int i=0;i<d.length;i++){
			nRecord+=d[i].length;
			nRecPerGroup[i]=d[i].length;
			sqNRecPerGroup+=nRecPerGroup[i]*nRecPerGroup[i];
			sqNRecPerGr2+=nRecPerGroup[i]*nRecPerGroup[i]*(2*nRecPerGroup[i]+3);
			//rank[i]=new double[nRecPerGroup[i]];
		}
		double U=0;
		double Uinv=0;
		for(int i=0;i<d.length;i++){
			for(int j=i+1;j<d.length;j++){
				for(int k=0;k<d[i].length;k++){
					for(int l=0;l<d[j].length;l++){
						if(d[i][k]>d[j][l]){
							U++;
						}else if(d[i][k]==d[j][l]){
							U+=0.5;
							Uinv+=0.5;
						}else{
							Uinv++;
						}
					}
				}
			}
		}
		T=(U-((double)(nRecord*nRecord)-sqNRecPerGroup)/4)/Math.sqrt(
				((double)(nRecord*nRecord*(2*nRecord+3)-sqNRecPerGr2))/72);
		/*
		Tinv=(Uinv-((double)(nRecord*nRecord)-sqNRecPerGroup)/4)/Math.sqrt(
				((double)(nRecord*nRecord*(2*nRecord+3)-sqNRecPerGr2))/72);
		*/
		//int df = nGroup-1;
		
		//System.out.println("T=\t"+T);
	}
	

}