Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
94 changes: 94 additions & 0 deletions src/rewrite2/tracker.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
#include "tracker.h"

#include <stdint.h>
#include <stdio.h>

struct Vector*
filterReliablePoints(struct Vector* points, uint8_t minSignal)
{
struct Vector* reliable;
size_t i;
size_t n;
Comment on lines +9 to +11
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ой, а это зачем, ещё и не инициализированное?


reliable = newVector();
if (!reliable)
return NULL;

if (!points)
return reliable;

n = size(points);

for (i = 0; i < n; ++i) {
NavPoint* point = (NavPoint*)at(points, i);

if (!point)
continue;

if (point->signal >= minSignal) {
if (pushBack(reliable, point) != 0) {
deleteVector(reliable);
return NULL;
}
}
}

return reliable;
}

void
analyzeReliablePoints(struct Vector* reliablePoints)
{
size_t n;
size_t i;
size_t count;
double sumSignal;
uint8_t maxSignal;
size_t maxId;
int hasMax;
Comment on lines +42 to +48
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Здесь такой же вопрос. Особенно много вопросов, зачем выносить i наверх


if (!reliablePoints) {
printf("No reliable points to analyze.\n");
return;
}

n = size(reliablePoints);

if (n == 0) {
printf("No reliable points to analyze.\n");
return;
}

count = 0;
sumSignal = 0.0;
maxSignal = 0;
maxId = 0;
hasMax = 0;
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Почему не bool?


for (i = 0; i < n; ++i) {
NavPoint* point = (NavPoint*)at(reliablePoints, i);

if (!point)
continue;

++count;
sumSignal += (double)point->signal;

if (!hasMax || point->signal > maxSignal) {
hasMax = 1;
maxSignal = point->signal;
maxId = point->id;
}
}

if (count == 0) {
printf("No reliable points to analyze.\n");
return;
}
Comment on lines +84 to +87
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Такое правда может случиться?


printf("Reliable points: %zu\n", count);
printf("Average signal: %.2f\n", sumSignal / (double)count);
printf("Max signal id: %zu\n", maxId);
}


31 changes: 31 additions & 0 deletions src/rewrite2/tracker.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
#pragma once

#include <stdint.h>
#include <stddef.h>

#include "vector.h"

// Структура, описывающая одну навигационную точку
typedef struct {
// Уникальный идентификатор точки
size_t id;
// Широта
double latitude;
// Долгота
double longitude;
// Уровень сигнала (от 0 до 255).
// Чем меньше сигнал, тем выше вероятность ошибки.
uint8_t signal;
} NavPoint;

// Фильтрует "надёжные" точки: signal >= minSignal.
// Возвращает указатель на НОВЫЙ динамический массив Vector*.
// Исходный массив не изменяется.
// В случае ошибки выделения памяти возвращает NULL.
struct Vector* filterReliablePoints(struct Vector* points, uint8_t minSignal);

// Анализирует отфильтрованные точки и печатает статистику в консоль.
// Если массив пуст или NULL, печатает "No reliable points to analyze."
void analyzeReliablePoints(struct Vector* reliablePoints);


98 changes: 98 additions & 0 deletions src/rewrite2/vector.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
#include "vector.h"
#include <stdlib.h>

struct Vector {
void** data;
size_t size;
size_t capacity;
};

int reserve(struct Vector* vector, size_t new_capacity)
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Вообще странный выбор кода возврата, если бывает bool.

{
void** new_data;
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Не по кодстайлу


if (new_capacity <= vector->capacity)
return 0;

new_data = realloc(vector->data, new_capacity * sizeof(void*));
if (!new_data)
return -1;
Comment on lines +18 to +19
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Коды возврата стоит описывать в хедере


vector->data = new_data;
vector->capacity = new_capacity;
return 0;
}

struct Vector* newVector(void)
{
struct Vector* vector = malloc(sizeof(struct Vector));

if (!vector)
return NULL;

vector->data = NULL;
vector->size = 0;
vector->capacity = 0;
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ну, честно говоря, начальный capacity лучше делать не 0.


return vector;
}

void deleteVector(struct Vector* vector)
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Не очень понимаю, что пользователь должен делать со своими данными. Чистить сам? Это нужно было описать.

{
if (!vector)
return;

free(vector->data);
free(vector);
}

int pushBack(struct Vector* vector, void* value)
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Опять же здесь бы лучше подошел bool.

{
size_t new_capacity;

if (!vector)
return -1;

if (vector->size == vector->capacity) {
new_capacity = vector->capacity ? vector->capacity * 2 : 4;
if (reserve(vector, new_capacity) != 0)
return -1;
}

vector->data[vector->size++] = value;
return 0;
}

void* get(struct Vector* vector, size_t index)
{
return vector->data[index];
}

void* at(struct Vector* vector, size_t index)
{
if (!vector)
return NULL;

if (index >= vector->size)
return NULL;

return vector->data[index];
}
Comment on lines +66 to +80
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Интересно зачем get, если она не используется?


size_t size(struct Vector* vector)
{
if (!vector)
return 0;

return vector->size;
}

size_t capacity(struct Vector* vector)
{
if (!vector)
return 0;

return vector->capacity;
}


27 changes: 27 additions & 0 deletions src/rewrite2/vector.h
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Самая главная проблема --- нет описания стратегии владения. Я не понимаю, что должен делать пользователь, чтобы у него не текла память

Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
#pragma once
#include <stddef.h>

struct Vector;

// Создает пустой вектор
struct Vector* newVector(void);

// Удаляет структуру вектора и очищает память
void deleteVector(struct Vector* vector);

// Добавляет элемент в конец вектора (возвращает 0 если ок)
int pushBack(struct Vector* vector, void* value);

// Берет элемент по индексу
void* get(struct Vector* vector, size_t index);

// Возвращает элемент с указанным индексом или NULL если выходит за границы
void* at(struct Vector* vector, size_t index);

// Текущее количество элементов в списке
size_t size(struct Vector* vector);

// Количество элементов, которые помещаются без распределения
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Не знаю, что такое распределение, но ладно

size_t capacity(struct Vector* vector);