view src/sample/merge/PermEnum.java @ 57:f055e65c7e3c

*** empty log message ***
author pin
date Tue, 24 Jul 2007 17:40:07 +0900
parents
children
line wrap: on
line source

package sample.merge;

import java.util.Enumeration;

public class PermEnum implements Enumeration {
	private int N;
	private int c[], k;
	private Object[] objs;
	
	public PermEnum(Object[] items){
		N = items.length;
		c = new int [N+1];
		for(int i = 0; i<=N; i++) c[i] = i;
		objs = items;
		k = 1;
	}
	
	public boolean hasMoreElements(){
		return (k < N);
	}
	
	public Object nextElement(){
		int i = 0;
		if((k & 1) != 0) i = c[k];
		
		Object tmp = objs[k];
		objs[k] = objs[i];
		objs[i] = tmp;
		
		k = 1;
		while(c[k] == 0) c[k] = k++;
		c[k]--;
		return objs;
	}
	
	public static void main(String[] args){
		String[] strs = {"1", "2", "3", "4"};
		//String[] strs = {"a"};
		System.out.println("N="+strs.length);
		Enumeration e = new PermEnum(strs);
		int count = 0;
		while(e.hasMoreElements()) {
			String[] a = (String[])e.nextElement();
			System.out.print("{" + a[0]);
			for(int i = 1; i<a.length; i++) System.out.print(", "+a[i]);
			System.out.println("}");
			count++;
		}
	System.out.
	println("count="+count);
	}
}