我正在尝试将15位二进制序列编码为{0,1,2 ... 7}中的一个排列。例如,任何15位随机序列(如'001010101000101')将被编码为置换值之一,例如'12345670'。我使用的是HashMap,其中键表示15位序列,值代表40320个排列值之一。 Set存储15位序列。我写了下面的代码似乎工作,但最后“writeString.append”没有返回任何值,并变为null。有什么好的补救措施吗?
package wordnet;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
import java.util.Set;
import javax.print.DocFlavor.STRING;
public class CopyCharacters {
public static void main(String[] args) throws IOException {
String theString = "";
File file = new File("C:\\Users\\Vinay\\WordNet\\test");
Scanner scanner = new Scanner(file);
theString = scanner.nextLine();
while (scanner.hasNextLine()) {
theString = theString + "\n" + scanner.nextLine();
}
theString =theString.replaceAll("\\s+","");
List<Integer> b = new ArrayList<Integer>();
String a= "01234567";
Set<String> permutations= crunchifyPermutation(a);
Iterator<String> code = permutations.iterator();
//System.out.println(permutations);
Map<String, String> mapping = new HashMap<String, String>();
File file1 = new File("C:\\Users\\Vinay\\WordNet\\output.txt");
// if file doesnt exists, then create it
if (!file1.exists()) {
file1.createNewFile();
}
FileWriter fw = new FileWriter(file1.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
StringBuffer writeString =new StringBuffer();
for(int i=0,j=15;j<theString.length();i=i+15,j=j+15){
String value = theString.substring(j,i);
if(mapping.get(value)==null){
mapping.put(value, code.next());
//code.remove();
}
writeString.append(mapping.get(value));
}
System.out.println(writeString.toString());
//bw.write((writeString.toString()));
bw.close();
}
public static Set<String> crunchifyPermutation(String str) {
Set<String> crunchifyResult = new HashSet<String>();
if (str == null) {
return null;
} else if (str.length() == 0) {
crunchifyResult.add("");
return crunchifyResult;
}
char firstChar = str.charAt(0);
String rem = str.substring(1);
Set<String> words = crunchifyPermutation(rem);
for (String newString : words) {
for (int i = 0; i <= newString.length(); i++) {
crunchifyResult.add(crunchifyCharAdd(newString, firstChar, i));
}
}
return crunchifyResult;
}
public static String crunchifyCharAdd(String str, char c, int j) {
String first = str.substring(0, j);
String last = str.substring(j);
return first + c + last;
}
}
答案 0 :(得分:0)
for
循环似乎提前终止。使用
for (int i = 0, j = 15; i < theString.length(); i = i + 15, j = j + 15) {
为我带来了预期的结果数量。