62,634
社区成员




public static void doAnagram(int newSize)
{
if(newSize == 1) //if innermost,go no further
{
displayWord();//打印出目前字母数组的单词
return;
}
for (int j=0; j<newSize; j++) //for each position
{
doAnagram(newSize - 1); //anagram remaining
rotate(newSize); //rotate word
}
}
import java.io.*;
class AnagramApp1
{
static int size;
static int count;
static char[] arrChar = new char[100];
public static void main(String[] args) throws IOException
{
System.out.print("Enter a word:");
String input = getString();
size = input.length();
count = 0;
for (int j=0; j<size; j++)
{
arrChar[j] = input.charAt(j);
}
doAnagram(size);
}
public static void doAnagram(int newSize)
{
if(newSize == 1) //if innermost,go no further
{
displayWord(newSize); //最后一层,输出的是全部字符的可能组合
return;
}
for (int j=0; j<newSize; j++) //for each position
{
doAnagram(newSize - 1); //anagram remaining
displayWord(newSize); //我加的显示语句,用于显示所有长度小于原单词长度的单词
rotate(newSize); //rotate word
}
}
public static void rotate(int newSize)
{
int j;
int position = size - newSize;
char temp = arrChar[position]; //save first letter
for (j=position+1; j<size; j++) //shift others left
{
arrChar[j-1] = arrChar[j];
}
arrChar[j-1] = temp; //put first on right
}
public static void displayWord(int newSize) //经过改造的显示方法,要接收一个参数以判断当前的递归层数
{
if(count < 99)
System.out.print(" ");
if(count < 9)
System.out.print(" ");
if(size-newSize+1 <= 2) //加入的判断,2就表示长度小于等于2的单词打印出来
{
System.out.print(++count + " ");
for(int j=0;j < size-newSize+1; j++)
{
System.out.print(arrChar[j]);
}
}
System.out.print(" ");
System.out.flush();
if(count%6 == 0)
System.out.println("");
}
public static String getString() throws IOException
{
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
String s = br.readLine();
return s;
}
} //end class AnagramApp
public class test
{
public static void main(String[] args)
{
//允许组成的字符串的最大长度
int maxLen = 3;
//组成字符串的字符
char[] chars = "abcd1234".toCharArray();
//char[] chars = "012".toCharArray();
//0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz
//这就是对应的目标进制
int radix = chars.length;
//下面开始枚举各种组合
String s = "";
long i = 0;
do
{
System.out.println((i+1) +"\t"+ number2String(i++, radix, chars));
}
while(i<count(radix,maxLen) && i<3000);//计算所有符合要求的排列,当排列多于3000个时只算前3000个
}
/**
* 为这个任务修正过的进制转换方法,转换出来的结果不能当成真正的数字使用
* @param num 待转换的数字
* @param radix 进制。注意与 chars 保持匹配!
* @param chars 表现数字用的字符。注意与 radix 保持匹配!
* @return
*/
public static String number2String(long num, int radix, char[] chars)
{
int cIndex = (int) (num % radix);
String s = String.valueOf(chars[cIndex]);
if (num >= radix)
{
s = number2String(((num - cIndex) / radix) - 1, radix, chars) + s;
}
return s;
}
/**
* 接收传入的标准字符chars长度和要求的文件名最大长度maxLen,返回总的组合数目.
* @param m 标准字符chars长度
* @param n 文件名最大长度maxLen
* @return
*/
public static long count(int m,int n)
{
long result=0;
for(int i=1;i<=n;i++)
result+=Math.pow(m,i);
return result;
}
}