随机数生成器到数组,没有重复的java

时间:2016-02-27 21:01:53

标签: java arrays random

所以我试图制作一个程序,产生一个包含20个随机数的数组,没有重复数(给最终用户)。这是我到目前为止的代码

   let myURL = NSURL(string: "http://localhost:8888/saveWorkout.php");
        let request = NSMutableURLRequest(URL:myURL!);
        request.HTTPMethod = "POST";



        let postString = "exercise=\(exercise)";

        request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding);

        let task = NSURLSession.sharedSession().dataTaskWithRequest(request){
            data, response, error in

            if error != nil {
                print("error=\(error)")
                return
            }

            do{

                let json = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.AllowFragments) as? NSDictionary

                if let parseJSON = json{
                    let resultValue = parseJSON["status"] as! String!;

                    print("result: \(resultValue)")

                    if(resultValue == "Success"){



                        print("worked")


                    }
                    else{

                        print("not worked")
                    }
                }

            }
            catch { print(error) }

        }


        task.resume();

所以你可以看到我已经尝试过使用Arrays.asList(list).contains(mynumber)但是我仍然在输出中收到重复内容 29 4 4 1 20 三十 20 23 三十 11 6 7 27 14 16 8 4 19 7 15

有什么建议吗?

4 个答案:

答案 0 :(得分:4)

使用HashSet跟踪您使用过的数字。

例如

int[] result = new int[20];

HashSet<Integer> used = new HashSet<Integer>();
for (int i = 0; i < 20; i++) {
    int add = (int)(Math.random() * 30); //this is the int we are adding
    while (used.contains(add)) { //while we have already used the number
        add = (int) (Math.random() * 30); //generate a new one because it's already used
    }
    //by this time, add will be unique
    used.add(add);
    result[i] = add;
}

这确保您没有重复项,并且比在ArrayList中搜索要快得多,ArrayList每次搜索数字时都会执行一些等于ArrayList大小的操作。当您检查是否包含数字时,HashSet仅执行1次操作。

答案 1 :(得分:1)

您的代码无效的原因是Arrays.asList(int[] list)返回的大小为ArrayList<int[]>,而不是ArrayList<Integer>。因此,当您致电contains时,它不会检查原始列表中的整数元素,并始终返回false

答案 2 :(得分:0)

我建议使用ArrayList,不要使用空if块。 这应该有用。

   import java.util.ArrayList;
    import java.util.List;
    import java.util.Random;

    public class Main {
            static List list = new ArrayList<>(20);
            public static void main(String args[])
            {
                Random rand = new Random();
                boolean generating=true;
                int counting=0;
                while(generating)
                {
                    int testNum= rand.nextInt(30)+1;
                    if (!list.contains(testNum))
                    {
                        list.add(testNum);
                        counting++;
                        System.out.println(testNum);
                    }
                    if(counting>=20)
                    {
                        generating=false;
                    }
                }
            }
}

答案 3 :(得分:0)

使用Collections.Shuffle

class Ideone{
    public static void main(String[] args) {
    Integer[] arr = new Integer[20];
    for (int i = 0; i < arr.length; i++) {
        arr[i] = i;
    }
    Collections.shuffle(Arrays.asList(arr));
    System.out.println(Arrays.toString(arr));

}}
相关问题