Browse Source

Add option to specify percentage of changed values

or more accurately, the probability that each value in the neighbor
solution will be changed.

Note that I have found that giving lower values yields much better
results.

Signed-off-by: wmb <wmb@teknik.io>
tags/v0.1.0^0
wmb 1 month ago
parent
commit
cfe78cea0e
1 changed files with 17 additions and 6 deletions
  1. 17
    6
      main.c

+ 17
- 6
main.c View File

@@ -38,6 +38,7 @@ solution new_solution;

int n_clusters = 5;
int n_iterations = 1000;
long double percentage = 10.0;


int main(int argc, char *argv[])
@@ -50,7 +51,7 @@ int main(int argc, char *argv[])
SetConsoleOutputCP(CP_UTF8);
#endif /* _WIN32 */

while ((c = getopt(argc, argv, ":c:i:h")) != -1) {
while ((c = getopt(argc, argv, ":c:i:p:h")) != -1) {
int k;
switch (c) {
case 'c':
@@ -63,8 +64,19 @@ int main(int argc, char *argv[])
if (k > 0)
n_iterations = k;
break;
case 'p':
{
char *endp;
long double p = strtold(optarg, &endp);
if (p == 0.0 || *endp != '\0') {
fprintf(stderr, "%s: Invalid percentage: %s\n", argv[0], optarg);
exit(EXIT_FAILURE);
}
percentage = p;
}
break;
case 'h':
printf("Usage: %s [-c N_CLUSTERS] [-i N_ITERATIONS]", argv[0]);
printf("Usage: %s [-c N_CLUSTERS] [-i N_ITERATIONS] [-p PERCENTAGE]", argv[0]);
exit(EXIT_SUCCESS);
break;
default:
@@ -243,11 +255,10 @@ vector *centres_gravite(const solution s)

int solution_voisine(solution *dest, const solution src)
{
/* This function changes about 10% of the solution randomly */
/* This function changes about percentage% of the solution randomly */

size_t i;
const int a = 10000; /* b = 10% of a */
const int b = 1000;
const int cutoff = (int) ((long double) RAND_MAX / 100.0 * (long double) percentage);
bool valid;

if (!(*dest = calloc(N_VECTORS, sizeof(**dest))))
@@ -258,7 +269,7 @@ int solution_voisine(solution *dest, const solution src)
assert(n_clusters > 1);

for (i = 0; i < N_VECTORS; i++) {
if (rand() % a < b) {
if (rand() < cutoff) {
int new_cluster = rand() % (n_clusters - 1);
/* To avoid the case where the cluster isn't actually changed. */
new_cluster += (new_cluster >= src[i]);

Loading…
Cancel
Save