-
Notifications
You must be signed in to change notification settings - Fork 0
/
random_list.c
51 lines (40 loc) · 1.03 KB
/
random_list.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
#include <stdlib.h>
static int rand_in_range(int min, int max) {
return rand() % (max - min) + min;
}
// swaps first k numbers
static void shuffle(int *arr, int length, int k) {
for (int i = 0; i < k; i++) {
int to_swap_with = rand_in_range(i, length);
// swap
int temp = arr[i];
arr[i] = arr[to_swap_with];
arr[to_swap_with] = temp;
}
}
static int *amelia_sort(int *arr, int length, int k) {
int *ones_and_zeroes = calloc(length, sizeof(int));
for (int i = 0; i < k; i++) {
ones_and_zeroes[arr[i]] = 1;
}
int *sorted = malloc(sizeof(int) * length);
int count = 0;
for (int i = 0; i < length; i++) {
if (ones_and_zeroes[i] == 1) {
sorted[count] = i;
count++;
}
}
free(ones_and_zeroes);
return sorted;
}
int *random_increasing_ints(int max, int k) {
int *full_list = malloc(sizeof(int) * max);
for (int i = 0; i < max; i++) {
full_list[i] = i;
}
shuffle(full_list, max, k);
int *sorted = amelia_sort(full_list, max, k);
free(full_list);
return sorted;
}