Home Upgrade Search Memberlist Extras Hacker Tools Award Goals Help Wiki Contact

C 

Fun C Challenge(Pointers, Random Integers, Arrays)

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.
a simple xorshift prng on the indices should be fine


Possibly Related Threads...
Thread / Author Replies Views Last Post
[.NET] by pzychonautJun 8, 2023 05:03 PM 5 174 Jun 8, 2023 05:03 PM
Last Post: padrino
[C] by spl0itpid1Jun 3, 2022 04:17 AM 10 350 Jun 3, 2022 04:17 AM
Last Post: Mr Roboto
[Java] by PsychoJul 3, 2021 11:15 PM 24 1,975 Jul 3, 2021 11:15 PM
Last Post: Lookdadon