我正在努力实现滑动窗口以解决以下问题。
我正在编写一个程序,该程序应询问文件的位置(具有PI的数字)和要通过用户的Scanner类解析的位数。
问题: 一家公司正在评估它是否可以通过解析小数位后的PI数来分配电话号码。假设每个电话号码有5位数。因此,第一个电话号码的小数点后面的前5位数字,从第二个位置开始的5个数字形成第二个电话号码(它遵循滑动窗口模式,您可以一次滑动一个数字)。
以下是我到目前为止的尝试。
如何实施滑动窗口?
非常感谢任何建议。
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStreamReader;
import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;
public class Problem3 {
public static void main(String[] args) throws Exception {
FileInputStream inputstream = null;
BufferedReader reader = null;
Set<String> set = new HashSet<String>();
@SuppressWarnings("resource")
Scanner input = new Scanner(System.in);
try {
System.out.println("Give the location of the file (example: C:\\Users\\Onur\\workspace\\ProgAssign3\\src\\pi.txt):");
String fileloc = input.nextLine();
inputstream = new FileInputStream(fileloc);
reader = new BufferedReader(new InputStreamReader(inputstream));
String stringinput;
System.out.println("Number of digits of PI to parse: ");
int parsenum = input.nextInt() + 2;
String[] stringarray = new String[parsenum];
while((stringinput = reader.readLine()) != null) {
stringinput = stringinput.substring(2, parsenum);
for(int i = 0; i < stringinput.length(); i++) {
stringarray = stringinput.split("");
}
}
for(int i = 0; i < 5; i++){
set.add(stringarray[i]);
}
System.out.println(set);
}
catch (FileNotFoundException exception) {
System.err.println("File not found, please try again");
main(null);
}
catch (Exception e) {
System.err.println("Invalid input entered");
}
finally {
reader.close();
}
}
}
答案 0 :(得分:2)
处理&#34;滑动窗口的一种方法&#34;将使用stretch,并寻求当前的偏移量。
唯一性可由RandomAccessFile处理。
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.HashSet;
import java.util.Set;
public class NumberGeneratorPI {
private static final int N = 100_000;
private static final String PI = "pi.txt"; // 1415...
private static final byte[] buf = new byte[5];
public static void main(String[] args) throws IOException {
Set<String> numbers = new HashSet<>();
RandomAccessFile digits = new RandomAccessFile(new File(PI), "r");
for (int i = 0; i < N; i++) {
digits.seek(i);
digits.read(buf);
if (!numbers.add(new String(buf)))
System.out.println("Duplicate!");
}
// Do something with numbers
}
}
答案 1 :(得分:0)
不知道你面临的问题是什么。在伪代码中它应该看起来像这样:
ask for file name;
open inputStream for file;
read 5 characters from inputStream;
phoneNumber = concatenation of 5 character
print phoneNumber;
put phoneNumber in a set;
while (there are more data in inputStream) {
c = read 1 char from inputStream;
phoneNumber = substring of phoneNumber from 2nd to end, plus c;
print phoneNumber;
if (phoneNumber exists in set) {
print it is repeated;
} else {
add phoneNumber to set;
}
}