-1

I'm trying to generate random numbers without any duplicate, like from 1 to 5 I want it to be 2 3 1 5 4 not 2 2 2 1 5. I've tried it but something went wrong and the code didn't work properly.

#include <stdlib.h>
#include <time.h>

int random(int minN, int maxN){
    return minN + rand() % (maxN + 1 - minN);
}
 
int main(){
    int max,min;
    printf("nhap max ");
    scanf("%d", &max);

    printf("nhap min ");
    scanf("%d", &min);
    srand((int)time(0));
    for (int i = 0; i < max; i++)
    {
        int arr[100];
        arr[i] = random(min,max);
        if(i!=0){
            for(int j=i-1; j>=0;j-1){
                if (arr[i]==arr[j])
                    continue;
            }
        }
        printf("%d ",arr[i]);
    }
}
mch
  • 9,424
  • 2
  • 28
  • 42
  • 1
    That doesn't sound random to me. You probably want the numbers from 1 to 5 in a random order, which is something quite different. – dandan78 May 04 '21 at 07:36
  • 1
    Welcome to SO. The nature of random numbers is that they can repeat. What you want instead is a given set of numbers in random order. You might put all numbers in an array and create random index to pick one number from that array and remove afterwards. – Gerhardh May 04 '21 at 07:36
  • Does your compiler issue some warning about "expression without any side effect"? for your loop: `; j-1}`. Running your program in a debugger should reveal that endless loop within seconds. – Gerhardh May 04 '21 at 07:43
  • 2
    Besides the previous comments, "and the code didn't work properly." is not a very useful statement. What does or does not happen incorrectly? Please read [How To ask](https://stackoverflow.com/help/how-to-ask) and provide sample input, expected output and real output. – Gerhardh May 04 '21 at 07:47
  • 2
    You want to shuffle the array `{ 1, 2, 3, 4, 5 }` instead. Try [Fisher-Yates shuffle](https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle). – pmg May 04 '21 at 08:16
  • You are probably looking for this: https://stackoverflow.com/questions/42321370/fisher-yates-shuffling-algorithm-in-c – Jabberwocky May 04 '21 at 08:17
  • thank everyone, I'm still new with all of this so my question may be silly but thank you all for your help. – Ggeniee May 04 '21 at 13:48

1 Answers1

-4

While generating random number instead of random(min,max); you can use below:

int random_int(int min, int max) { return min + rand() % (max+1 - min);}
  • How does this address the "no duplicates" part of the question? And how is this different from the code in the question? That only uses slightly different names. – Gerhardh May 04 '21 at 07:40