Hack Forums
[C] Fun C Challenge(Pointers, Random Integers, Arrays) - Printable Version

+- Hack Forums (https://hackforums.net)
+-- Forum: Tech (https://hackforums.net/forumdisplay.php?fid=444)
+--- Forum: Coding (https://hackforums.net/forumdisplay.php?fid=151)
+---- Forum: Software Development (https://hackforums.net/forumdisplay.php?fid=118)
+---- Thread: [C] Fun C Challenge(Pointers, Random Integers, Arrays) (/showthread.php?tid=6194070)



Fun C Challenge(Pointers, Random Integers, Arrays) - EmacsSucksButILikeIt - Feb 17, 2022

Fun C Challenge(Pointers, Random Integers, Arrays)..

Here's a fun and standard C problem. Can you shuffle an array of integers via an array of int pointers?

I.E.

Say you have an array of integers:
Code
#define ARR_SIZE 10

int arr[ARR_SIZE] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};

and an array of int pointers:
Code
#define ARR_SIZE 10

int *arr_ptrs[ARR_SIZE] = {NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL};

Now can you use the addresses of the elements in arr to populate arr_ptrs such that each address in arr is present in arr_ptrs only once and is shuffled.

Here's something to get you started:
Code
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

#define ARR_SIZE 10

void shuffle(int arr[], int *arr_ptr[], size_t size) {
  //Do your C magic here
}

int main(int argc, char **argv) {
  size_t i = 0;
  int arr[ARR_SIZE] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
  int *arr_ptrs[ARR_SIZE] = {NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL};

  shuffle(arr, arr_ptrs, ARR_SIZE);

  for (; i < ARR_SIZE; i++) {
    arr_ptrs[i] ?
      fprintf(stdout, "(%ld): %d\n", i, *arr_ptrs[i]) :
      fprintf(stdout, "(%ld): NULL value\n", i);
  }
  return 0;
}

Here is some examples of what the output of printing arr_ptrs would look like.
Code
(0): 8
(1): 7
(2): 2
(3): 3
(4): 10
(5): 1
(6): 9
(7): 4
(8): 5
(9): 6
Code
(0): 1
(1): 3
(2): 8
(3): 7
(4): 4
(5): 10
(6): 2
(7): 6
(8): 5
(9): 9

Notice that each number from arr is represented and the output is shuffled.


RE: Fun C Challenge(Pointers, Random Integers, Arrays) - unazed - Jun 4, 2022

a simple xorshift prng on the indices should be fine