Hello Everyone;

I have been trouble with putting Random numbers in an array for an 2 hours
My problem is ,yes I know that how I can put Random numbers in an array but, for example
my array length is 6 and I generated 1 to 6 random number and first index I putted; hovewer the program should not be replace array[index] to array[index+1] Here my code is shown how can I fix ? Really I need help thank you for your interests.

public static int[] randomDizi(int size) {
        final int finalSize = size;

        // int randomNumber;
        int newArray[];
        newArray = new int[finalSize];



        for (int in = 0; in < finalSize; in++) {

            if ((in+1) < finalSize) {
                do {
                    newArray[in+1] = (int) (Math.random() * finalSize) + 1;
                    newArray[in] = (int) (Math.random() * finalSize) + 1;
                    if (newArray[in+1] != newArray[in]) {
                        break;
                    }

                } while (newArray[in+1] == newArray[in]);
            }
        }




        return newArray;

Recommended Answers

All 4 Replies

ouf really complicated for nothing
assuming you want values <= finalSize

int[] newArray = new int[finalSize];
Random ran = new Random();
for(int i = 0; i < newArray.length(); ++i)
   newArray[i] = ran.nextInt(finalSize) + 1;

Hi;

yes I want to use finalSize to compute random() method in Math class. Anyway

The real question is for example if my arrays' first index is 6 which generated by (int)Math.random() and which means that this 6 never replaced other array elements
Actually my question does not just belong Java problem it is math problem as same as
combination problem i.e. I've 6 digit number [a][c][d][e][f] and from 1 to 6 that I allowed the numbers. if [a] has taken 5; then [c][d][e][f] none of them should not use number 5 anymore and so our choices 1,2,3,4,6 and again again So it is the heart of this question. I would fix this problem it may help in real project algorithms in future I hope. Anyway thanks for interests. Now I try again :)

In that case use an ArrayList and randomly remove from it that will garanty unicity

ArrayList<Integer> al = new ArrayList<Integer>();
// for loto 6/36
for(int i = 1; i <= 36; ++i)
  al.add(i);
// retreive 6 unique number randomly
Random ran = new Random();
for(int i = 0; i < 6; ++i) {
  int val = ran.nextInt(al.size());
  int num = al.remove(val);   // unique random number  removed from arrayList
}

that's it ! Thank you really for your interest. I've also started to think using ArrayList because excepting special element is easier -in ArrayList, than in Array.
Again Thank you. My Arraylist knowloedge is not good but I've learned today. ;)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.