#include #include #include #include #include #include #include #include "ImageFmtc.h" #define SQR(x) ((x)*(x)) #define NELEM(a) ((int)(sizeof (a) / sizeof (*(a)))) struct Node { int idx; double coord_x; double coord_y; }; void do_error(const char *fmat, ...); int main(int argc, char **argv) { char parfname[200], tspfname[200], tourfname[200]; FILE *parfp, *tspfp; int num_nodes; if (argc != 4) do_error("usage: randtsp \n" "usage: randtsp "); num_nodes = atoi(argv[2]); if (num_nodes <= 1) do_error("I can't do a tour of '%d' nodes!", num_nodes); sprintf(parfname, "%s.par", argv[1]); sprintf(tspfname, "%s.tsp", argv[1]); sprintf(tourfname, "%s.tour", argv[1]); if ((parfp = fopen(parfname, "w")) == NULL) do_error("Can't open parfile '%s'!", parfname); if ((tspfp = fopen(tspfname, "w")) == NULL) do_error("Can't open tspfile '%s'!", tspfname); fprintf(parfp, "COMMENT : Autogenerated by randtsp\n"); fprintf(parfp, "PROBLEM_FILE = %s\n", tspfname); fprintf(parfp, "TOUR_FILE = %s\n", tourfname); fprintf(tspfp, "COMMENT : Autogenerated by randtsp\n"); fprintf(tspfp, "NAME: %s\n", argv[1]); fprintf(tspfp, "TYPE: TSP\n"); fprintf(tspfp, "DIMENSION: %d\n", num_nodes); fprintf(tspfp, "EDGE_WEIGHT_TYPE: EUC_2D\n"); fprintf(tspfp, "NODE_COORD_SECTION\n"); srand((unsigned)time(0)); if (isdigit(argv[3][0])) { double coord_range = strtod(argv[3], NULL); int i; if (coord_range <= 0.0) do_error("Coord range must be > 0.0"); for (i=0; i < num_nodes; ++i) { fprintf(tspfp, "%d %g %g\n", i+1, rand()*coord_range/RAND_MAX, rand()*coord_range/RAND_MAX); } } else { char *image_name = argv[3]; unsigned char *image; int w, h; int i, j; double total_gray; double new_point_thresh; if (ReadGenGray(image_name, &image, &w, &h)) do_error("Couldn't read image '%s'!", image_name); #if 0 total_gray = 0; for (i=0; i < w*h; ++i) total_gray += image[i]; new_point_thresh = total_gray/num_nodes; printf("num_nodes=%d\n", num_nodes); printf("total_gray=%g npt=%g\n", total_gray, new_point_thresh); total_gray = 0; num_nodes = 0; for (j=0; j < h; ++j) { for (i=0; i < w; ++i) { int new_nn; total_gray += image[j*w+i]; new_nn = total_gray/new_point_thresh; while (num_nodes < new_nn) { fprintf(tspfp, "%d %g %g\n", ++num_nodes, 10.*((rand()*1.0/RAND_MAX)+i), 10.*((rand()*1.0/RAND_MAX)+j)); } } } #else { const double GAMMA = num_nodes; num_nodes = 0; for (j=0; j < h; ++j) { for (i=0; i < w; ++i) { int gij = GAMMA*(1. - image[j*w+i]/256.); for (; gij > 0; --gij) { fprintf(tspfp, "%d %g %g\n", ++num_nodes, 10.*((rand()*1.0/RAND_MAX)+i), 10.*((rand()*1.0/RAND_MAX)+j)); } } } fprintf(parfp, "ASCENT_CANDIDATES = 10\n"); fprintf(parfp, "RUNS = 2\n"); fprintf(parfp, "OPTIMUM = 0\n"); } #endif } fprintf(parfp, "EOF\n"); fprintf(tspfp, "EOF\n"); fclose(tspfp); fclose(parfp); return 0; } void do_error(const char *fmat, ...) { va_list ap; va_start(ap, fmat); vprintf(fmat, ap); putchar('\n'); va_end(ap); exit(EXIT_FAILURE); }