Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

This is my homework assignment:

Random r = new Random();
public int get100RandomNumber() {
    return 1 + r.nextInt(100);
}

You are given a pre-defined function named getrand100() (above) which returns an integer which is one random number from 1-100. You can call this function as many times as you want but beware that this function is quite resource intensive. You cannot use any other random generator. You cannot change the definition of getrand100().

Output: Print numbers 1-20 in random order. (Not 20 random numbers)

What I have tried..

public class MyClass {

    static Random r = new Random();
    static HashSet<Integer>;

    public static void main(String args[]) {
        myMethod();
        System.out.println(s);
    }    

    public static void myMethod() {
        boolean b = false;
        s = new HashSet<Integer>();
        int i = getRand100();
        if (i >= 20)
            i = i % 20;
        int j = 0;

        int k, l;
        while (s.size() <= 20) 
        {
            System.out.println("occurence no" + ++j);
            System.out.println("occurence value" + i);
            b = s.add(i);
            while (!b) {
                k = ++i;
                if(k<=20)
                    b = s.add(k);
                if(b==true)
                    break;
                if (!b) {
                    l = --i;
                    if(i>=1&&i<=20)
                        b = s.add(l);
                    if(b==true)
                        break;
                }
            }
        }
        System.out.println(s);
    }

    public static int getRand100()
    {
        return r.nextInt(100) + 1;
    }
}

Thanks for any help!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
236 views
Welcome To Ask or Share your Answers For Others

1 Answer

I believe you are asking how to use a random number generator to print out the numbers 1 to 20 in a random order. This is also known as a "random permutation". The Fischer-Yates shuffle is such an algorithm.

However, to implement the algorithm, you first of all need a random number generator that can pick one out of N items with equal probability where N ranges from 2 up to the size of the set to shuffle, while you only have one that can pick one out of 100 items with equal probability. That can easily be obtained by a combination of modulo arithmetic and "rerolling".


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...