Advertisement
STANAANDREY

rand shuffle

Dec 22nd, 2022
679
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 0.73 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <time.h>
  4. #define NMAX 10
  5. int arr[NMAX];
  6.  
  7. void swapInts(int *a, int *b) {
  8.   int aux = *a;
  9.   *a = *b;
  10.   *b = aux;
  11. }
  12.  
  13. int randInRange(int low, int high) {
  14.   return rand() % (high - low + 1) + low;
  15. }
  16.  
  17. void randShuffle(int arr[], int low, int high) {
  18.   for (int i = low; i <= high; i++) {
  19.     int j = randInRange(low, high);
  20.     swapInts(arr + i, arr + j);
  21.   }
  22. }
  23.  
  24. void printArray(int arr[], int n) {
  25.   for (int i = 0; i < n; i++) {
  26.     printf("%d ", arr[i]);
  27.   }
  28.   puts("");//*/
  29. }
  30.  
  31. int main(void) {
  32.   srand(time(NULL));
  33.   for (int i = 0; i < NMAX; i++) {
  34.     arr[i] = i + 1;
  35.   }
  36.   printArray(arr, NMAX);
  37.   randShuffle(arr, 4, 8);
  38.   printArray(arr, NMAX);
  39.   return 0;
  40. }
  41.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement