【发布时间】:2015-12-15 22:37:29
【问题描述】:
所以我正在创建一个程序,它应该使用线性同余生成器来创建一个数字序列。我想将输出相互比较以检查是否有重复,然后让程序停止。但是,使用我当前的代码,我最终在第一个生成的数字“55672”之后停止了代码,我在 excel 中构建了一个生成器,显示了所有输出,并且没有重复。我究竟做错了什么?这甚至是一种比较它们的可能方法吗,因为我基本上最终会问是否 x[i]=x[i] 因为它循环了所有数字,包括 i 变量,因此最终返回 true。
tl;dr 我如何让它检查重复?
public class Pseudotilfaeldigetal {
public static int[] x = new int[1000];
public static int modulus = 86408;
public static int a = 43205;
public static int c = 12345;
public static int seed;
public static Scanner tastatur = new Scanner(System.in); // her navngives vores scanner til tastatur
public static void main(String[] args) {
algoritme(modulus, seed, a, c);
}
public static void algoritme(int modulus, int seed, int a, int c) {
System.out.println("Select your seed ");
x[0] = tastatur.nextInt(); //reads the next input, and uses as seed
for (int i = 1; i < x.length; i++) { //Main for loop that generates numbers
x[i] = (a * x[i - 1] + c) % modulus; //the number generation using LCG method
System.out.println(x[i]); // Prints the newly generated value
for (int j = 1; j < x.length; j++) { // cycles through all int in x[] array to check
if (x[i] == x[j]) { //if current number is already in array
System.out.println("Value has been repeated"); //Prints value already used
return; // program ends.
}
}
}
}}
【问题讨论】:
-
为什么你的循环从 1 而不是 0 开始?
-
您的目标是什么?您是否尝试确定生成器的周期长度?