Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- #include <time.h>
- #define MAX_DATA 100 // Maximum number of stored values (can be dynamic if needed)
- // Structure to store a value and its timestamp
- typedef struct {
- int value;
- time_t timestamp;
- } Data;
- // Global buffer to store data and the index of the next position in the buffer
- Data data_buffer[MAX_DATA];
- int buffer_index = 0;
- int data_count = 0;
- // Function to calculate sum of values in the last 10 seconds
- int calculate_sum() {
- time_t current_time = time(NULL);
- int sum = 0;
- // Iterate over the data buffer and sum values within the last 10 seconds
- for (int i = 0; i < data_count; i++) {
- if (difftime(current_time, data_buffer[i].timestamp) <= 10) {
- sum += data_buffer[i].value;
- }
- }
- return sum;
- }
- // Function to add new data to the buffer
- void add_data(int value) {
- time_t current_time = time(NULL);
- // Add new data to the buffer
- data_buffer[buffer_index].value = value;
- data_buffer[buffer_index].timestamp = current_time;
- // Update buffer index and count
- buffer_index = (buffer_index + 1) % MAX_DATA;
- if (data_count < MAX_DATA) {
- data_count++;
- }
- }
- // Function to discard old data and update the buffer
- void update_data() {
- time_t current_time = time(NULL);
- // Remove data older than 10 seconds
- int i = 0;
- while (i < data_count) {
- if (difftime(current_time, data_buffer[i].timestamp) > 10) {
- // Shift elements to remove the old data
- for (int j = i; j < data_count - 1; j++) {
- data_buffer[j] = data_buffer[j + 1];
- }
- data_count--;
- } else {
- i++;
- }
- }
- }
- int main() {
- // Seed the random number generator
- srand(time(NULL));
- // Simulate incoming data with random intervals and values
- while (1) {
- // Simulate random wait time between 1 to 3 seconds
- int wait_time = rand() % 3 + 1;
- sleep(wait_time);
- // Simulate random data value between 1 and 10
- int value = rand() % 10 + 1;
- printf("Received value: %d\n", value);
- // Update data and calculate sum
- add_data(value);
- update_data();
- int sum = calculate_sum();
- printf("Sum of values in the last 10 seconds: %d\n", sum);
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement