Explore Rewrite from C to C++: void run\_kmeans(twtown\\ routes, int lenSub, twtown\* sub,… Save Share Download ▾ ReportJump to turn (6) 1 Rewrite from C to C++: void run\kmeans(twtown\\ routes, int lenSub, twtown\ sub, 2 Rewrite from C to C++: void cvrptw(struct twoResults (\algfunc)(twtown\, int, ha 3 Rewrite from C to C++: #include "parameters.h" #pragma once #ifndef LOGISTIC\H # 4 Rewrite from C to C++ and change struct on class: #include "parameters.h" #pragm 5 Rewrite from C to C++ where town is class #include #include #include "logistic.h 6 Reqwrite from C to C++: #pragma once #define errortwtown maketwtown(errortown, - Rewrite from C to C++:
void run_kmeans(twtown** routes, int lenSub, twtown* sub, double** distance_matrix, double** cluster_centers, int* cluster_assignments, int maxCapacity, twtown town0, int* cnt, const int count_vehicle)
{
initialize_cluster_centers(count_vehicle, sub, cluster_centers);
int* cluster_sizes = calloc(count_vehicle, sizeof(int));
double** cluster_sum = calloc(count_vehicle, sizeof(double *));
for (int i = 0; i < count_vehicle; i++)
{
cluster_sum[i] = calloc((DIMENSIONS), sizeof(double));
}
double** tmp_centers = calloc(count_vehicle, sizeof(double *));
for (int i = 0; i < count_vehicle; i++)
{
tmp_centers[i] = calloc((DIMENSIONS), sizeof(double));
}
int* cap = calloc(count_vehicle, sizeof(int));
Show full message · 79 lines Copy first prompt Copy first response
Details
Model Unknown
Provider unknown
Model provenance As recorded by source dataset
Turns 6 (12 messages)
Language Not recorded
Added to archive Nov 26, 2026
ID 01m8bdx9ra9nf8m2xekfj5a7s4Source & license Imported from ShareGPT 90K (shared ChatGPT conversations) (source ). Imported records earn no Research Points.
Upstream record: HTML_cleaned_raw_dataset/sg_90k_part2_html_cleaned.json:35467
anon8231489123/ShareGPT_Vicuna_unfiltered, revision 192ab2185289094fc556ec8ce5ce1e8e587154ca
License: Apache-2.0 (as published by the uploader; same files as RyokoAI/ShareGPT52K, CC0)
Dataset releases Not yet included in a published release.
Turns (6) 1 Rewrite from C to C++: void run\kmeans(twtown\\ routes, int lenSub, twtown\ sub, for (int i = 0; i < MAX_ITERATIONS; i++)
{
for (int j = 0; j < lenSub-1; j++)
{
for (int k = 0; k < count_vehicle; k++)
{
distance_matrix[j][k] = euclidean_distance(sub[j], cluster_centers[k]);
}
}
update_cluster_assignments(sub, lenSub-1, distance_matrix, cluster_assignments, maxCapacity, count_vehicle, cap);
for(int t = 0; t < count_vehicle; t++)
{
cap[t] = 0;
}
int stop = update_cluster_centers(lenSub-1, sub, cluster_assignments, cluster_centers, cnt, count_vehicle, cluster_sizes, cluster_sum, tmp_centers);
for (int t=0; t < count_vehicle; t++)
{
cluster_sizes[t] = 0;
}
for (int t = 0; t < count_vehicle; t++)
{
for(int k = 0; k < DIMENSIONS; k++)
{
cluster_sum[t][k] = 0;
}
}
for (int t = 0; t < count_vehicle; t++)
{
for(int k = 0; k < DIMENSIONS; k++)
{
tmp_centers[t][k] = 0;
}
}
if(stop)
{
break;
}
}
for(int i = 0; i < count_vehicle; i++)
{
cnt[i] = 0;
}
for (int j = 0; j < lenSub-1; j++)
{
routes[cluster_assignments[j]][cnt[cluster_assignments[j]]] = sub[j];
cnt[cluster_assignments[j]]++;
}
for(int i = 0; i < count_vehicle; i++)
{
routes[i][cnt[i]] = town0;
cnt[i]++;
}
Here's the C++ version of the code:
scss Copy code
void run_kmeans(twtown** routes, int lenSub, twtown* sub, double** distance_matrix, double** cluster_centers, int* cluster_assignments, int maxCapacity, twtown town0, int* cnt, const int count_vehicle)
{
initialize_cluster_centers(count_vehicle, sub, cluster_centers);
int* cluster_sizes = new int[count_vehicle]();
double** cluster_sum = new double*[count_vehicle];
for (int i = 0; i < count_vehicle; i++)
{
cluster_sum[i] = new double[DIMENSIONS]();
}
double** tmp_centers = new double*[count_vehicle];
for (int i = 0; i < count_vehicle; i++)
{
tmp_centers[i] = new double[DIMENSIONS]();
}
int* cap = new int[count_vehicle]();
for (int i = 0; i < MAX_ITERATIONS; i++)
{
for (int j = 0; j < lenSub-1; j++)
{
for (int k = 0; k < count_vehicle; k++)
{
distance_matrix[j][k] = euclidean_distance(sub[j], cluster_centers[k]);
}
}
update_cluster_assignments(sub, lenSub-1, distance_matrix, cluster_assignments, maxCapacity, count_vehicle, cap);
for(int t = 0; t < count_vehicle; t++)
{
cap[t] = 0;
}
int stop = update_cluster_centers(lenSub-1, sub, cluster_assignments, cluster_centers, cnt, count_vehicle, cluster_sizes, cluster_sum, tmp_centers);
for (int t=0; t < count_vehicle; t++)
{
cluster_sizes[t] = 0;
}
for (int t = 0; t < count_vehicle; t++)
{
for(int k = 0; k < DIMENSIONS; k++)
{
cluster_sum[t][k] = 0;
}
}
for (int t = 0; t < count_vehicle; t++)
{
for(int k = 0; k < DIMENSIONS; k++)
{
tmp_centers[t][k] = 0;
}
}
if(stop)
{
break;
}
}
for(int i = 0; i < count_vehicle; i++)
{
cnt[i] = 0;
}
for (int j = 0; j < lenSub-1; j++)
{
routes[cluster_assignments[j]][cnt[cluster_assignments[j]]] = sub[j];
cnt[cluster_assignments[j]]++;
}
for(int i = 0; i < count_vehicle; i++)
{
routes[i][cnt[i]] = town0;
cnt[i]++;
}
delete[] cluster_sizes;
for (int i = 0; i < count_vehicle; i++)
{
delete[] cluster_sum[i];
}
delete[] cluster_sum;
for (int i = 0; i < count_vehicle; i++)
{
delete[] tmp_centers[i];
}
delete[] tmp_centers;
delete[] cap;
}
Rewrite from C to C++:
void cvrptw(struct twoResults (*algfunc)(twtown*, int, halfmatrix*, double*, const double, double, double, int), halfmatrix *m, twtown *towns, int countTowns, double maxCapacity, double T, double t_end, int shuffle_param, int count_vehicles, char *fileout)
{
FILE *out = fopen(fileout, "w");
FILE *res_distance = fopen("current_result/res_distance.txt", "w");
if(res_distance == NULL) {exit(-1);}
if(out == NULL) {exit(-1);}
twtown town0 = getTwTownByName(0, countTowns, towns);
double startTime = town0.mTimeStart;
double endTime = town0.mTimeEnd;
for(int c = 0; c < countTowns; c++)
{
if((town0.mTimeStart < town0.mTimeEnd && town0.mTimeStart > towns[c].mTimeEnd && towns[c].mTimeEnd > towns[c].mTimeStart) ||
(town0.mTimeEnd < towns[c].mTimeStart && town0.mTimeStart > towns[c].mTimeEnd && towns[c].mTimeStart > towns[c].mTimeEnd && town0.mTimeEnd > town0.mTimeStart))
{
towns[c].t = zerotown;
}
else if((town0.mTimeStart > towns[c].mTimeStart && town0.mTimeStart < towns[c].mTimeEnd && town0.mTimeEnd > towns[c].mTimeEnd) ||
(towns[c].mTimeStart < town0.mTimeStart && towns[c].mTimeEnd < town0.mTimeEnd && town0.mTimeStart > town0.mTimeEnd))
{
towns[c].mTimeStart = town0.mTimeStart;
}
else if(towns[c].mTimeEnd > towns[c].mTimeStart && towns[c].mTimeStart < town0.mTimeStart && towns[c].mTimeEnd > town0.mTimeEnd)
{
towns[c].mTimeStart = town0.mTimeStart;
towns[c].mTimeEnd = town0.mTimeEnd;
}
else if((town0.mTimeEnd > towns[c].mTimeStart && town0.mTimeStart < towns[c].mTimeEnd && town0.mTimeEnd < town0.mTimeStart) ||
(town0.mTimeStart < towns[c].mTimeStart && town0.mTimeEnd > towns[c].mTimeEnd && towns[c].mTimeEnd < towns[c].mTimeStart && town0.mTimeEnd < town0.mTimeStart) ||
(town0.mTimeStart < towns[c].mTimeEnd && towns[c].mTimeStart > town0.mTimeEnd && towns[c].mTimeStart > towns[c].mTimeEnd) ||
(town0.mTimeStart < towns[c].mTimeEnd && towns[c].mTimeStart < town0.mTimeEnd && towns[c].mTimeStart > towns[c].mTimeEnd) ||
(town0.mTimeStart > towns[c].mTimeEnd && town0.mTimeEnd > towns[c].mTimeStart && towns[c].mTimeStart > towns[c].mTimeEnd) ||
(towns[c].mTimeEnd > towns[c].mTimeStart && town0.mTimeEnd > towns[c].mTimeEnd && town0.mTimeStart > town0.mTimeEnd) ||
(towns[c].mTimeEnd > towns[c].mTimeStart && towns[c].mTimeStart > town0.mTimeStart && towns[c].mTimeEnd > town0.mTimeEnd))
{
continue;
}
if(towns[c].mTimeService > towns[c].mTimeEnd - towns[c].mTimeStart)
{
towns[c].t = zerotown;
}
if(towns[c].t.weight > maxCapacity || (towns[c].mTimeStart - towns[c].mTimeEnd) == 0)
{
towns[c].t = zerotown;
}
if(c != 0 && towns[c].mTimeEnd < getByTown(m, 0, c) + towns[c].mTimeService)
{
towns[c].t = zerotown;
}
if(c != 0 && ((getByTown(m, 0, c) < towns[c].mTimeStart && towns[c].mTimeStart + towns[c].mTimeService + getByTown(m, 0, c) > town0.mTimeEnd) || (getByTown(m, 0, c) >= towns[c].mTimeStart && towns[c].mTimeService + 2 * getByTown(m, 0, c) > town0.mTimeEnd)))
{
towns[c].t = zerotown;
}
if(town0.mTimeStart - town0.mTimeEnd == 0)
{
printf("Impossible to optimize tour");
exit(-1);
}
}
twtown *sub = (twtown*) malloc((countTowns-1) * sizeof(twtown));
int w = 0;
twtown t;
// считаем количество плохих городов
int errorCounter = 0;
for(int i = 1; i < countTowns; i++)
{
t = getTwTownByName(i, countTowns, towns);
Show full message · 420 lines The code can be rewritten to C++ in the following way:
c Copy code
void cvrptw(std::function<twoResults(twtown*, int, halfmatrix*, double*, const double, double, double, int)> algfunc, halfmatrix *m, twtown *towns, int countTowns, double maxCapacity, double T, double t_end, int shuffle_param, int count_vehicles, char *file
Rewrite from C to C++:
#include "parameters.h"
#pragma once
#ifndef LOGISTIC_H
#define LOGISTIC_H
#define errortown maketown(-1, -1, -1, -1)
#define zerotown maketown(-3, 0, 0, 3000)
typedef struct town {
int name;
double x, y;
int weight;
} town;
town maketown(int name, double x, double y, int weight);
#endif
#include "parameters.h"
#pragma once
#ifndef LOGISTIC_H
#define LOGISTIC_H
#define errortown maketown(-1, -1, -1, -1)
#define zerotown maketown(-3, 0, 0, 3000)
struct Town {
int name;
double x, y;
int weight;
Town(int name, double x, double y, int weight);
};
Town maketown(int name, double x, double y, int weight);
#endif
Rewrite from C to C++ and change struct on class:
#include "parameters.h"
#pragma once
#ifndef LOGISTIC_H
#define LOGISTIC_H
#define errortown maketown(-1, -1, -1, -1)
#define zerotown maketown(-3, 0, 0, 3000)
typedef struct town {
int name;
double x, y;
int weight;
} town;
town maketown(int name, double x, double y, int weight);
#endif
Here's the rewritten code in C++ with the town struct changed to a Town class:
cpp Copy code
#include "parameters.h"
#pragma once
#ifndef LOGISTIC_H
#define LOGISTIC_H
#define errortown maketown(-1, -1, -1, -1)
#define zerotown maketown(-3, 0, 0, 3000)
class Town {
public:
int name;
double x, y;
int weight;
Town(int n, double x_, double y_, int w) : name(n), x(x_), y(y_), weight(w) {}
};
Town maketown(int name, double x, double y, int weight);
#endif
Note that the constructor for the Town class has been added to initialize its member variables, and the typedef has been removed since it's not necessary with the class. The maketown function has not been changed, so it can be left as is.
Rewrite from C to C++ where town is class
#include
#include
#include "logistic.h"
town maketown(int name, double x, double y, int weight)
{
town t;
t.name = name;
t.x = x;
t.y = y;
t.weight = weight;
return t;
}
Here's the rewritten code in C++ where town is a class:
cpp Copy code
#include <iostream>
#include "logistic.h"
#pragma once
#define errortown town(-1, -1, -1, -1)
#define zerotown town(-3, 0, 0, 3000)
class town {
public:
int name;
double x, y;
int weight;
town(int name, double x, double y, int weight) {
this->name = name;
this->x = x;
this->y = y;
this->weight = weight;
}
};
town maketown(int name, double x, double y, int weight)
{
town t(name, x, y, weight);
return t;
}
Note that we define the class town with public member variables name, x, y, and weight. We also define a constructor that initializes these member variables, and a maketown function that creates a new town object and returns it. The #define statements for errortown and zerotown are also updated to use the town class constructor.
Reqwrite from C to C++:
#pragma once
#define errortwtown maketwtown(errortown, -1, -1, -1)
#define MIN(a, b) ((a < b) ? (a) : (b))
In C++, you can use the #ifndef header guard to prevent multiple inclusions of a header file. Here's the rewritten code:
cpp Copy code
#ifndef PARAMETERS_H
#define PARAMETERS_H
#define errortwtown maketwtown(errortown, -1, -1, -1)
#define MIN(a, b) ((a < b) ? (a) : (b))
#endif
Note that #pragma once is not needed when using header guards. The macro MIN can be defined like this, using C++'s std::min function:
cpp Copy code
#define MIN(a, b) std::min(a, b)
Or, you can use a template function:
cpp Copy code
template<typename T>
T MIN(T a, T b) {
return (a < b) ? a : b;
}
In the C++ version, dynamic memory allocation is done using new instead of calloc(). Also, after the usage, the memory is freed using delete[] operator.
if(t.t.name == -1)
{
errorCounter++;
printf("Error town: %d\n", i);
continue;
}
sub[w] = t;
w++;
}
int newCountTowns = w;
printf("%d\n", newCountTowns);
sub = realloc(sub, newCountTowns * sizeof(twtown));
double td;
double distanceInTourBest = -1.0, distanceInTourNew = 0.0;
double runtime = clock();
double full_time = 0;
signal(SIGINT, sigfunc);
if(shuffle_param == 0)
{
FILE *start_tour = fopen("current_result/start_tour.txt", "w");
doShuffleTw(newCountTowns, sub);
for(int h = 0; h < newCountTowns; h++){
fprintf(start_tour, "%d ", sub[h].t.name);
}
fclose(start_tour);
}
else if(shuffle_param == 1)
{
FILE *start_tour = fopen("current_result/start_tour.txt", "r");
int name;
twtown *sub_alg = (twtown*) malloc((newCountTowns) * sizeof(twtown));
for(int h = 0; h < newCountTowns; h++){
fscanf(start_tour, "%d ", &name);
for(int s = 0; s < newCountTowns; s++){
if(name == sub[s].t.name){
sub_alg[h] = sub[s];
break;
}
}
}
fclose(start_tour);
for(int h = 0; h < newCountTowns; h++){
sub[h] = sub_alg[h];
}
}
double** distance_matrix = calloc(newCountTowns, sizeof(double *));
for (int i=0; i < newCountTowns; i++)
{
distance_matrix[i] = calloc(count_vehicles, sizeof(double));
}
int* cluster_assignments = calloc(newCountTowns, sizeof(int));
double** cluster_centers = calloc(count_vehicles, sizeof(double *));
for (int i=0; i < count_vehicles; i++)
{
cluster_centers[i] = calloc(DIMENSIONS, sizeof(double));
}
twtown** routes = calloc(count_vehicles, sizeof(twtown *));
for (int i=0; i < count_vehicles; i++)
{
routes[i] = calloc((newCountTowns+1), sizeof(twtown));
}
twtown** best_route = calloc(count_vehicles, sizeof(twtown *));
for (int i=0; i < count_vehicles; i++)
{
best_route[i] = calloc((newCountTowns+1), sizeof(twtown));
}
int* cnt = calloc(count_vehicles, sizeof(int));
int* best_cnt = calloc(count_vehicles, sizeof(int));
double BestInitalDistance = INT_MAX;
int BestCountClusters = 0;
for(int f = 1; f < count_vehicles; f++)
{
run_kmeans(routes, newCountTowns+1, sub, distance_matrix, cluster_centers, cluster_assignments, maxCapacity, town0, cnt, f);
bool* clusters_flags = calloc(f, sizeof(bool));
bool** not_return = calloc(f, sizeof(bool *));
for (int i=0; i < f; i++)
{
not_return[i] = calloc(countTowns, sizeof(bool));
}
int err_towns = 0;
for(int i = 0; i < f; i++)
{
if(clusters_flags[i] == 1)
{
continue;
}
while(td == -1)
{
if(clusters_flags[i] == 1)
{
break;
}
tr = subtourdistanceTw(routes[i], cnt[i], m, startTime, endTime);
td = tr.localtimer;
if(td == -1)
{
startTime = town0.mTimeStart;
if(cnt[i] == 1 && routes[i][cnt[i] - 1].t.name == 0)
{
break;
}
cnt[i]--;
not_return[i][routes[i][cnt[i]].t.name] = 1;
int min_distance = INT_MAX;
int closest_cluster = 0;
for(int j = 0; j < f; j++)
{
int dist = euclidean_distance(routes[i][cnt[i]], cluster_centers[j]);
if (dist < min_distance && not_return[j][routes[i][cnt[i]].t.name] == 0)
{
min_distance = dist;
closest_cluster = j;
}
}
if(min_distance == INT_MAX)
{
err_towns++;
}
else
{
routes[closest_cluster][cnt[closest_cluster]] = routes[i][cnt[i]];
cnt[closest_cluster]++;
clusters_flags[closest_cluster] = 0;
if(closest_cluster < i)
{
i = closest_cluster;
}
}
for(int i = 0; i < f; i++)
{
startTime = town0.mTimeStart;
tr = subtourdistanceTw(routes[i], cnt[i], m, startTime, endTime);
distanceInTourNew += tr.only_distance;
}
if(distanceInTourNew * 13 + (errorCounter + err_towns) * 10 < BestInitalDistance)
{
BestInitalDistance = distanceInTourNew * 13 + (errorCounter + err_towns) * 10;
BestCountClusters = f;
for (int i = 0; i < f; i++)
{
best_route[i] = routes[i];
best_cnt[i] = cnt[i];
}
}
distanceInTourNew = 0;
}
for(int i = 0; i < BestCountClusters; i++)
{
write_cvrptw_subtour(res_distance, best_route[i], best_cnt[i]);
}
fprintf(out, "%lf\t%lf\n", (BestInitalDistance), 0.0);
while(!stop)
{
clock_t start = clock();
startTime = town0.mTimeStart;
td = -1;
distanceInTourNew = 0;
tr.localtimer = 0;
tr.only_distance = 0;
int err_towns = 0;
doShuffleTw(newCountTowns, sub);
run_kmeans(routes, newCountTowns+1, sub, distance_matrix, cluster_centers, cluster_assignments, maxCapacity, town0, cnt, BestCountClusters);
bool* clusters_flags = calloc(BestCountClusters, sizeof(bool));
bool** not_return = calloc(BestCountClusters, sizeof(bool *));
for (int i=0; i < BestCountClusters; i++)
{
not_return[i] = calloc(countTowns, sizeof(bool));
}
for(int i = 0; i < BestCountClusters; i++)
{
if(clusters_flags[i] == 1)
{
continue;
}
while(td == -1)
{
if(clusters_flags[i] == 1)
{
break;
}
startTime = town0.mTimeStart;
if(cnt[i] > 2)
{
tr = algfunc(routes[i], cnt[i], m, &startTime, endTime, T, t_end, countTowns);
}
else
{
tr = subtourdistanceTw(routes[i], cnt[i], m, startTime, endTime);
}
td = tr.localtimer;
if(td == -1)
{
if(cnt[i] == 1 && routes[i][cnt[i] - 1].t.name == 0)
{
break;
}
cnt[i]--;
not_return[i][routes[i][cnt[i]].t.name] = 1;
int min_distance = INT_MAX;
int closest_cluster = 0;
for(int j = 0; j < BestCountClusters; j++)
{
int dist = euclidean_distance(routes[i][cnt[i]], cluster_centers[j]);
if (dist < min_distance && not_return[j][routes[i][cnt[i]].t.name] == 0)
{
min_distance = dist;
closest_cluster = j;
}
}
if(min_distance == INT_MAX)
{
err_towns++;
}
else
{
routes[closest_cluster][cnt[closest_cluster]] = routes[i][cnt[i]];
cnt[closest_cluster]++;
clusters_flags[closest_cluster] = 0;
if(closest_cluster < i)
{
i = closest_cluster;
}
}
for(int i = 0; i < BestCountClusters; i++)
{
startTime = town0.mTimeStart;
tr = subtourdistanceTw(routes[i], cnt[i], m, startTime, endTime);
distanceInTourNew += tr.only_distance;
write_cvrptw_subtour(res_distance, routes[i], cnt[i]);
}
if(distanceInTourBest == -1.0)
{
fprintf(out, "%lf\t%lf\n", (distanceInTourNew * 13 + (errorCounter + err_towns) * 10), (clock() - runtime) / CLOCKS_PER_SEC);
distanceInTourBest = distanceInTourNew * 13 + (errorCounter + err_towns) * 10;
}
if(distanceInTourNew * 13 + (errorCounter + err_towns) * 10 < distanceInTourBest)
{
distanceInTourBest = distanceInTourNew * 13 + (errorCounter + err_towns) * 10;
write_cvrptw_end_tour(res_distance, distanceInTourBest);
fprintf(out, "%lf\t%lf\n", (distanceInTourNew * 13 + (errorCounter + err_towns) * 10), (clock() - runtime) / CLOCKS_PER_SEC);
}
else
{
write_cvrptw_end_tour(res_distance, -1);
}
clock_t end = clock();
double seconds = (double)(end - start) / CLOCKS_PER_SEC;
full_time += seconds;
// 100 секунд - 50 городов
// 200 секунд - 100 городов
if(full_time > 20)
{
stop = 1;
}
}
/* данный параметр очень важно заново обнулять, так как он глобальный и при решении следующих задач
будет сразу вызывать Ctrl+C*/
stop = 0;
double final_time = (clock() - runtime) / CLOCKS_PER_SEC;
fprintf(out, "%lf\t%lf\n", (distanceInTourBest), final_time);
printf("2Opt:%d 3Opt:%d KOpt:%d\n", two_opt, three_opt, k_opt);
two_opt = 0;
three_opt = 0;
k_opt = 0;
printf("\nОкончательное время оптимизации: %lf \nОкончательная длина маршрута: %lf \n", final_time, (distanceInTourBest));
fputc('\n', out);
printf("Количество, использованных транспортных средств: %d\n", BestCountClusters);
for (int i=0; i < newCountTowns; i++)
{
free(distance_matrix[i]);
}
free(distance_matrix);
for (int i=0; i < BestCountClusters; i++)
{
free(cluster_centers[i]);
}
free(cluster_centers);
free(cluster_assignments);
for (int i=0; i < BestCountClusters; i++)
{
free(routes[i]);
}
free(routes);
free(cnt);
free(sub);
free(towns);
fclose(out);
fclose(res_distance);
finalizehalfmatrix(m);
}