2016-12-17 47 views
0

我需要创建随机数字,这些数字将在没有重复的情况下通过数组运行。如何创建没有重复项的随机数列表?

的问题是重复和我不能像java.util.Randomjava.util.ArrayList使用任何utils的的除了Scanner输入(教师指令)。

我使用了一个函数random,我的老师写信给我们,函数newNum(int num)是我所需要的 - 随机数。

package exercise; 

import java.util.Scanner; 

public class Bingo { 

    static int size = 10; 
    static int num; 
    static int[] arr = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; 
    private static Scanner sc; 

    public static void main(String[] args) { 

     System.out.print("Press Enter to start: "); 
     sc = new Scanner(System.in); 
     sc.nextLine(); 
     System.out.println(""); 

     // int[] arr = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; 
     // int[] tempArray = arr; 

     int num = random(); 
     // int num = sc.nextInt(); 

     // System.out.println(num); 

     while (size > 0) { 
      System.out.println(num); 
      size--; 
      newArray(num); 
      num = random(); 
      newNum(num); 
      // System.out.println(num); 
     } 

    } 

    public static int random() { 

     int max = 10; 
     double r = Math.random(); 
     int num = (int) (r * max + 1); 

     return num; 
    } 

    public static int newNum(int num) { 

     // Here should go the code for the function for getting only new 
     // random number without duplications 

     return num; 
    } 

    public static int newArray(int num) { 

     int[] tempArray = arr; 

     arr = new int[size]; 

     int x = num - 1; 
     for (int i = 0; i < x; i++) { 
      if (i < size) { 
       arr[i] = tempArray[i]; 
      } 
     } 
     for (int i = num; i < size; i++) { 
      if (i < size) { 
       int y = i - 1; 
       arr[y] = tempArray[i]; 
      } else { 
       int a = size - 1; 
       arr[a] = tempArray[size]; 
      } 
     } 
     return num; 
    } 

} 
+5

欢迎来到堆栈溢出。由于这是一个学校项目,你应该自己做,以确保你正在学习。关于在这里提出问题还有一些指导:http://stackoverflow.com/help/how-to-ask - 所以如果你确实想提问,你可以用一种方式来帮助人们提供帮助。我会给你一个关于作业的提示:跟踪你使用的数字,并且每次生成一个新号码时检查该列表 – Mikkel

+0

感谢提示,但我需要将它发送给我的老师直到明天,所以我需要更多的解释或为我自己后面快速解释的答案。 –

+5

伊戈尔,学校项目的重点是要表明你可以自己做点什么,并且了解你需要什么来完成作业。我可以为你写代码,但那不对,会不会? – Mikkel

回答

0

首先,你写道你不能使用shuffle,但这并不意味着你被禁止实施它。事实并非如此。

如果你想这样做,使用费雪耶茨洗牌,在维基百科中找到:https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle

(顺便说一下,因为你要去上学了,如果你找到了这样一个维基百科的文章 - 或任何其他文章 - 很有意思,你可能会建议你的老师拿着一篇文章,很容易获得额外的好评)

当然,这假设你有一个向量来洗牌,这对于大型向量来说是低效的“零至十亿之内的随机数”)。在这种情况下,你可能会想要去的:

要0..M

1. Initialize an empty list of already used random numbers which is ordered, called "numbers" 
2. for i = 0..n-1 
     2a: r = random(0..m-i) (uniform distribution) 
     2b: for every entry in numbers 
      if entry <= r, r++ 
     2c: sort r into numbers (maybe by using a single bubblesort step) 

这和以前的转移从向量的大小复杂生成的数字量内找到N个随机数。

说明:在每次迭代中,我们都希望找到一个未使用的数字。我们找到第rth个未使用的数字(迭代中有一个0..m-i的未使用数字)。现在我们只需要找出哪个数字是第一个未使用的数字。这是由内部迭代完成的。由于这个例子,我们需要对数字进行排序:当前状态:数字= {5,1},r = 4。r < 5 - >什么都不做。 r> = 1 - > r ++。结束r = 5,得到了一个双重入口。

如果不需要对结果列表进行排序,只需使用两个列表即可。