0

I've some strange situation here and i thought that you may help me. I have an int array populated with numbers from 1 to 10. I want to generate random number from this array and save it to another int array. I used class Random to pick any number and since random throws 0 also i modify it like that ( so it throws numbers from 1 to 10 )

randNum = rand.nextInt(numbers.length-min+1)+min;   

Following code makes sure that if it generates same random number, it skips it. Program is actually working and i'm getting in another array randomly positioned numbers from 1 to 10. That's what i wanted. But sometimes i'm missing one number from 1 - 10 AND iam Getting ZERO instead. Why??

int[] numbers = {1,2,3,4,5,6,7,8,9,10};
int[] usednum = new int[10];
Random rand = new Random();
int randNum;
int min = 1;

for (int x = 0; x<numbers.length; x++) {        
  for (int i = 0; i<usednum.length; i++) { 
    randNum = rand.nextInt(numbers.length-min+1) + min;
    for (int f = 0; f<usednum.length; f++) {
      if (usednum[f] == randNum) {
        break;
      } else if (usednum[f] == 0) { 
        usednum[x] = randNum;   
      }
    }
  } 
}

for (int c = 0; c<usednum.length; c++) {
  System.out.println(usednum[c]);
}
2
  • 1
    I have run this and confirmed that there is an error. Commented Aug 31, 2012 at 14:16
  • What is the purpose of g? you assign it, but do not use it. Commented Aug 31, 2012 at 14:20

7 Answers 7

2

You're inner-most for loop only checks if the current random number is in the usednum[] array. And the for loop immediately outer of that only checks 10 times total. It gives up too quickly because it only tries 10 random numbers. If all 10 are already used, nothing will get stored in that slot of usednum[] (thus it will be 0), try adding a while loop around that and get rid of the extraneous outer-most for loop:

        for(int i = 0; i<usednum.length; i++) {
           while(usednum[i]==0) {
              randNum = rand.nextInt(numbers.length-min+1)+min;
              for(int f = 0; f<usednum.length; f++) {
                 if(usednum[f] == randNum) {
                    break;
                 } //if                                                                                                                                        
                 else if (usednum[f] == 0) {
                    usednum[i] = randNum;
                 }
              }
           }
        }

Also note that the assignment is for usednum[i] = randNum;.

This is essentially replacing the middle for loop (the one that goes from i=0 to 9) with the while loop.

Sign up to request clarification or add additional context in comments.

Comments

2

If your goal is simply to shuffle an array of numbers, try this instead:

Integer[] numbers = {1,2,3,4,5,6,7,8,9,10};
Collections.shuffle(Arrays.asList(numbers));

It will have the same effect. Unless you are completing a homework assignment that forces you to solve the issue in a more manual fashion, just make use of the standard Java libraries.

The shuffle method writes changes through to the underlying Integer array, thanks to the special type of List returned by Arrays.asList(...). Note you have to use an array of Integer not int (see Why does Collections.shuffle() fail for my array?).

2 Comments

Thank you for your answer. But as you said i must complete my homework in hard way, lol. It's stupid tho..
Well, it's difficult enough to have challenged you, which is a good thing! In the future, please mark such questions with the "homework" tag so that people answer your question in a more constructive manner.
0

You are generating used numbers through an entire pass, so it doesn't generate a zero is just fails to generate a value it should.

2 Comments

I think this makes some sense yes. And why exactly fails to generate a value?
It generates 10 values all of which have been used before. Try using randNum = 4; in your code it will give you 4 then 9 zeros
0

you have one for loop too much.

remove the loop with the i iterator and the program should do what you want.

Oh and remove the -min+1 from the random generator, -1+1=0

1 Comment

the -min+1 is probably there to be used in the future.
0

Your array usednum is consisted of zeros at the beginning. In some cases, your program doesn't change that initial value, but breaks before at the line:

if(usednum[f] == randNum)

and does that during all iterations with same value x. X increments and there goes your chance to change the zero value.

Comments

0

Edit - followed it and re-wrote it:

List<Integer> numbers = new LinkedList<Integer>(Arrays.asList(new Integer[]{ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }));
        int[] usednum = new int[10];
        Random rand = new Random();
        int n = numbers.size();
        for (int i = 0; i < n; i++) {
            int randNum = rand.nextInt(numbers.size());
            usednum[i]=numbers.get(randNum);
            numbers.remove(randNum);
        }
        for (int c:usednum) {
            System.out.println(c); 
        }

1 Comment

Edited - please review again - sorry about that
0

Actually, you are never using the content of the array numbers. Try changing the array to something like int[] numbers = { 10, 22, 23, 42, 53, 18, 7, 8, 93, 10 };. You will get similar output.

Jon Lin's answer describe why your code is not working but does not address this issue. I think you will want to change your code to something like:

    int[] numbers = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
    int[] usednum = new int[10];
    Random rand = new Random();

    int selectedCount = 0;

    while (selectedCount < numbers.length) {
        int randNum = numbers[rand.nextInt(numbers.length)];
        boolean contains = false;
        for (int x = 0; x < selectedCount; x++) {
            if (usednum[x] == randNum) {
                contains = true;
                break;
            }
        }

        if (!contains) {
            usednum[selectedCount] = randNum;
            selectedCount++;
        }
    }


    for (int c = 0; c < usednum.length; c++) {
        System.out.println(usednum[c]);
    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.