DEV Community

Lalit Kumar
Lalit Kumar

Posted on

Mix arrangement in C (random order)

In this post I show you how to mix an arrangement in C , that is, randomize it or randomize it; whatever you call it. In this way at the end we will have the arrangement mixed, ordered randomly .

Table of contents:

  • Mix arrangement in C
  • Putting it all together

To achieve this we simply need to loop through the array and at each iteration:

  1. Get a random index that is in the range of alongitud -1
  2. Swap the item at the cycle index for the random index

Let's go there!

Mix Arrangement in C

I have explained the operation above. We start by defining the function that will give us a random number and feeding srand.

The function looks like this:

// maximum and minimum are inclusive
int  random_in_range ( int minimum, int max) {
    return minimum + rand () / (RAND_MAX / (maximum - minimum + 1 ) + 1 );
}
Enter fullscreen mode Exit fullscreen mode

We feed srand:
srand(getpid());
Then we define the array and calculate its length:

int array [] = { 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 };
int length =
        sizeof (array) / sizeof array [ 0 ];
Enter fullscreen mode Exit fullscreen mode

Wre print the original so that the difference is noticeable:

printf ( " Original fix: \ n " );
for ( int i = 0 ; i <length; i ++) printf ( " % d , " , array [i]);
Enter fullscreen mode Exit fullscreen mode

Now comes the part of the algorithm to make a random arrangement in C:

// Cycle from 0 to array length
for ( int i = 0 ; i <length; i ++) {
    int Random Index = random_in_range ( 0 , length - 1 );
    // Swap the current with an element of the random index
    temporary int = array [i];
    array [i] = array [RandomIndex];
    array [randomIndex] = temporary;
}
Enter fullscreen mode Exit fullscreen mode

We get a random index on line 3 . The security in the index iis then temporarily backed by temporal. Then, to the element that is in iwe put what is in the random index and to the random index we put the temporary one. Read more

Top comments (0)