|
| 1 | +#include <stdbool.h> |
1 | 2 | #include <stdio.h> |
2 | 3 | #include <stdlib.h> |
| 4 | +#include <string.h> |
3 | 5 |
|
4 | | -int josephus(int n, int k) |
| 6 | +bool linear_search(int *arr, int size, int target) |
5 | 7 | { |
6 | | - if (n == 1) |
7 | | - return 1; |
8 | | - else |
9 | | - return (josephus(n - 1, k) + k - 1) % n + 1; |
| 8 | + for (int i = 0; i < size; i++) |
| 9 | + if (arr[i] == target) |
| 10 | + return true; |
| 11 | + return false; |
10 | 12 | } |
11 | 13 |
|
12 | | -int main(int argc, char *argv[]) |
| 14 | +int *parse_array(char *input, int *size) |
13 | 15 | { |
14 | | - if (argc != 3) |
| 16 | + int *arr = NULL; |
| 17 | + *size = 0; |
| 18 | + char *token = strtok(input, ", "); |
| 19 | + while (token != NULL) |
15 | 20 | { |
16 | | - printf("Usage: please input the total number of people and number of " |
17 | | - "people to skip.\n"); |
18 | | - return 1; |
| 21 | + arr = realloc(arr, (*size + 1) * sizeof(int)); |
| 22 | + arr[*size] = atoi(token); |
| 23 | + (*size)++; |
| 24 | + token = strtok(NULL, ", "); |
19 | 25 | } |
| 26 | + return arr; |
| 27 | +} |
20 | 28 |
|
21 | | - char *endptr; |
22 | | - int n = strtol(argv[1], &endptr, 10); |
23 | | - if (*endptr != '\0' || n <= 0) |
| 29 | +int main(int argc, char *argv[]) |
| 30 | +{ |
| 31 | + if (argc != 3) |
24 | 32 | { |
25 | | - printf("Usage: please input the total number of people and number of " |
26 | | - "people to skip.\n"); |
| 33 | + printf("Usage: please provide a list of integers (\"1, 4, 5, 11, 12\") " |
| 34 | + "and the integer to find (\"11\")\n"); |
27 | 35 | return 1; |
28 | 36 | } |
29 | 37 |
|
30 | | - int k = strtol(argv[2], &endptr, 10); |
31 | | - if (*endptr != '\0' || k <= 0) |
| 38 | + int size; |
| 39 | + int *arr = parse_array(argv[1], &size); |
| 40 | + int target = atoi(argv[2]); |
| 41 | + |
| 42 | + if (size == 0) |
32 | 43 | { |
33 | | - printf("Usage: please input the total number of people and number of " |
34 | | - "people to skip.\n"); |
| 44 | + printf("Usage: please provide a list of integers (\"1, 4, 5, 11, 12\") " |
| 45 | + "and the integer to find (\"11\")\n"); |
| 46 | + free(arr); |
35 | 47 | return 1; |
36 | 48 | } |
37 | 49 |
|
38 | | - int result = josephus(n, k); |
39 | | - printf("%d\n", result); |
| 50 | + bool result = linear_search(arr, size, target); |
| 51 | + printf("%s\n", result ? "true" : "false"); |
40 | 52 |
|
| 53 | + free(arr); |
41 | 54 | return 0; |
42 | 55 | } |
0 commit comments