Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- typedef struct {
- size_t size;
- size_t count;
- int *input_array;
- } input_t;
- input_t * initialize_input_struct();
- int traverse_list(input_t *input, int current_pos);
- void add_character(input_t *input, int input_data);
- void read_input(input_t *input);
- void parse_input(input_t *input);
- int main() {
- input_t *input = initialize_input_struct();
- read_input(input);
- parse_input(input);
- return 0;
- }
- void parse_input(input_t *input) {
- // Keep track of the sum
- int sum = 0;
- // Keep track of the highest index
- int highest_index = input->count -1;
- // The increment is equal to the size of the list divided by two
- int increment = input->count / 2;
- // Keep track of the next index
- int next_index;
- // Loop through all the items
- for (int i = 0; i < input->count; ++i) {
- // Keep track of the current index
- int current_value = input->input_array[i];
- // If we can safely increment the index and proceed, do so
- if(i + increment <= highest_index) {
- next_index = i + increment;
- } else {
- // Check the number of steps you can safely take
- int valid_steps = highest_index - increment;
- // Proceed the number of steps and subtract them from the total distance to go
- int remaining_steps = increment - valid_steps;
- // Start from 0 and move forward the remaining number of steps
- next_index = remaining_steps - 1; // Subtract one to start from index 0
- }
- int next_value = input->input_array[next_index];
- // Check if the value in the current index is equal to the value in the next index
- if(current_value == next_value) {
- sum += current_value;
- printf("%i is equal to %i, sum: %i\n", current_value, next_value, sum);
- }
- }
- }
- void read_input(input_t *input) {
- FILE* f = fopen("input2.txt", "r");
- if(f) {
- while(!feof(f)) {
- char buffer;
- fscanf(f, "%c", &buffer);
- add_character(input, buffer - '0');
- }
- } else {
- printf("Failed to open file stream\n");
- }
- input->count -= 1; // When the list is complete, there is one unused space, remove this one
- }
- // Create an initial list with 10 elements
- input_t * initialize_input_struct() {
- input_t *input = malloc(sizeof(input_t));
- input->size = 10;
- input->count = 0;
- input->input_array = malloc(sizeof(int) * input->size);
- return input;
- }
- // Add characters to the list 1 by 1
- void add_character(input_t *input, int input_data) {
- if(input->size == input->count) {
- input->size += 10;
- input->input_array = realloc(input->input_array, sizeof(int) * input->size);
- }
- input->input_array[input->count] = input_data;
- input->count++;
- }
Advertisement
Add Comment
Please, Sign In to add comment