Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7963535
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 4, 20262026-06-04T05:37:43+00:00 2026-06-04T05:37:43+00:00

I’m trying to play with some code..keep getting an compile error RND not declared

  • 0

I’m trying to play with some code..keep getting an compile error RND not declared in scope I found a part of the code that defined it if it ran on linux and if defined it on windows thus ignoring Mac users(no biggie, I would ignore them too!). I removed that part of the code and defined it using the linux settings(since I figured my Mac is more closer to linux than windows), but then I get the same error but for seed. The odd thing is those seed errors are at the same spot at the RND error was. So my question is what the heck is RND/Seed? My searches found them specific to VB but not sure if its useful since I’m using C++.

Here’s an offensive code snipped(viewers discretion is advised):

mi = (int)(round(RND*(dimc-1)));

Any tips/suggestions would be great. I’m just starting to learn about c++ so I maybe missing something very simple.

Here’s the entire code(stole it from here http://cg.iit.bme.hu/~zsolnai/gfx/genetic/ ):

// a fast genetic algorithm for the 0-1 knapsack problem
// by karoly zsolnai - keeroy@cs.bme.hu
// test case: 1000 items, 50 knapsack size
//
// compilation by: g++ genetic.cpp -O3 -ffast-math -fopenmp
#include <math.h>
#include <time.h>
#include <algorithm>
#include <vector>
#include <fstream>
#include <limits.h>


#define RND ((double)rand_r(&seed)/RAND_MAX) // reentrant uniform rnd



using namespace std;

struct chromo {
    chromo(int dimc) { items = new bool[dimc]; }
    ~chromo() { items = NULL; }
    void mutate(const int dimc, const int count) {
        int mi;
        for(int i=0;i<count;i++) {
            mi = (int)(round(RND*(dimc-1)));
            items[mi] = !items[mi];
        }
    }
    bool* items;
    int f;
};

int fitness(bool*& x, const int dimc, const vector<int>& v, const vector<int>& w, const int limit) {
    int fit = 0, wsum = 0;
    for(int i=0;i<dimc;i++) {
        wsum += x[i]*w[i];
        fit += x[i]*v[i];
    }
    if(wsum>limit) fit -= 7*(wsum-limit); // penalty for invalid solutions
    return fit;
}

void crossover1p(const chromo& c1, const chromo& c2, const chromo& c3, const int dimc, const int cp) {
    for(int i=0;i<dimc;i++) {
        if(i<cp) { c3.items[i] = c1.items[i]; }
        else { c3.items[i] = c2.items[i]; }
    }
}

void crossover1p_b(const chromo &c1, const chromo &c2, const chromo &c3, int dimc, int cp) {
    for(int i=0;i<dimc;i++) {
        if(i>=cp) { c3.items[i] = c1.items[i]; }
        else { c3.items[i] = c2.items[i]; }
    }
}

void crossoverrand(const chromo &c1, const chromo &c2, const chromo &c3, const int dimc) {
    for(int i=0;i<dimc;i++) {
        if(round(RND)) { c3.items[i] = c1.items[i]; }
        else { c3.items[i] = c2.items[i]; }
    }
}

void crossoverarit(const chromo &c1, const chromo &c2, const chromo &c3, int dimc) {
    for(int i=0;i<dimc;i++) {
        c3.items[i] = (c1.items[i]^c2.items[i]);
    }
}

bool cfit(const chromo &c1,const chromo &c2) { return c1.f > c2.f; }
bool cmpfun(const std::pair<int,double> &r1, const std::pair<int,double> &r2) { return r1.second > r2.second; }

int coin(const double crp) { // a cointoss
    if(RND<crp) return 1; // crossover
    else return 0; // mutation
}

// initializes the chromosomes with the results of a greedy algorithm
void initpopg(bool**& c, const std::vector<int> &w, const std::vector<int> &v, const int dimw, const int limit, const int pop) {
    std::vector<std::pair<int,double> > rvals(dimw);
    std::vector<int> index(dimw,0);
    for(int i=0;i<dimw;i++) {
        rvals.push_back(std::pair<int,double>(std::make_pair(i,(double)v[i]/(double)w[i])));
    }
    std::sort(rvals.begin(),rvals.end(),cmpfun);
    int currentw = 0, k;
    for(int i=0;i<dimw;i++) {
        k = rvals[i].first;
        if(currentw + w[k] <= limit) { // greedy fill
            currentw += w[k];
            index[k] = 1;
        }
    }
    for(int i=0;i<pop;i++) {
        for(int j=0;j<dimw;j++) {
            c[i][j] = index[j];
        }
    }
}

int main() {
    printf("\n");
    srand(time(NULL));
    vector<int> w, v; // items weights and values
    int info=0;
    FILE *f = fopen("1000_weights.txt","r");
    FILE *f2 = fopen("1000_values.txt","r");
    while(!feof(f) || !feof(f2) ) {
        fscanf(f," %d ",&info);
        w.push_back(info);
        info=0;
        fscanf(f2," %d ",&info);
        v.push_back(info);
    } // omitted fclose(f1) and fclose(f2) on purpose
    const int limit = 50; // knapsack weight limit
    const int pop = 250; // chromosome population size
    const int gens = INT_MAX; // maximum number of generations
    const int disc = (int)(ceil(pop*0.8)); // chromosomes discarded via elitism
    const int dimw = w.size();
    int best = 0, ind = 0, ind2 = 0; // a few helpers for the main()
    int parc = 0; // parent index for crossover
    double avg = 0, crp = 0.35; // crossover probability
    vector<chromo> ch(pop,chromo(dimw));
    bool **c = new bool*[pop];
    for(int i=0;i<pop;i++) c[i] = new bool[dimw];
    clock_t start = clock();
    printf("Initializing population with a greedy algorithm...");
    initpopg(c,w,v,dimw,limit,pop);
    printf("done!");
    for(int i=0;i<pop;i++) {
        ch[i].items = c[i];
        ch[i].f = fitness(ch[i].items, dimw ,v, w, limit);
    }
    printf("\n\n");

    for(int p=0;p<gens;p++) {
        std::sort(ch.begin(), ch.end(), cfit);
        #pragma omp parallel for shared(ch)
        for(int i=0;i<pop;i++) {
            if(i>pop-disc) { // elitism - only processes the discarded chromosomes
                if(coin(crp)==1) { // crossover section
                    ind = parc+round(10*RND); // choosing parents for crossover
                    ind2 = parc+1+round(10*RND);
                    // choose a crossover strategy here
                    crossover1p(ch[ind%pop],ch[ind2%pop],ch[i],dimw,round(RND*(dimw-1)));
//                  crossoverrand(ch[ind],ch[ind2],ch[i],dimw);
//                  crossoverarit(ch[0],ch[1],ch[i],dimw);
                    ch[i].f = fitness(ch[i].items, dimw ,v, w, limit);
                    parc += 1;
                }
                else { // mutation section
                    ch[i].mutate(dimw,1);
                    ch[i].f = fitness(ch[i].items, dimw ,v, w, limit);
                }
            }
            avg += ch[i].f;
            if(ch[i].f>best) best=ch[i].f;
        }
        parc = 0;
        if(p%5==0) {
            printf("\n#%d\t",p);
            printf("best fitness: %d \t",best);
            printf("avg fitness: %f",avg/pop);
            if(best == 675) goto end; // psst...don't tell anyone
        }
        best = avg = 0;
    }

end:
    printf("\n\n");
    clock_t end = clock();
    double t = (double)(end-start)/CLOCKS_PER_SEC;
    printf("\nCompletion time: %fs.\n",t);
    return 0;
}
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-04T05:37:44+00:00Added an answer on June 4, 2026 at 5:37 am

    The problem is you’ve inexpertly cut apart the code you’ve got:

    #if defined(__linux) || defined(__linux__)
            unsigned int seed = time(NULL);
            #define RND ((double)rand_r(&seed)/RAND_MAX) // reentrant uniform rnd
    #endif
    
    #if defined(WIN32) || defined(_WIN32) || defined(__WIN32__)
            #define RND ((double)rand()/RAND_MAX) // uniform rnd
    #endif
    

    This defines the seed variable based on the current time for Linux systems; perhaps the Windows systems do not need a seed?

    In any event, if you include both lines from the if defined (__linux) ... branch, instead of only one line, it should work without trouble on your OS X system.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I am trying to understand how to use SyndicationItem to display feed which is
Basically, what I'm trying to create is a page of div tags, each has
link Im having trouble converting the html entites into html characters, (&# 8217;) i
I have just tried to save a simple *.rtf file with some websites and
For some reason, after submitting a string like this Jack’s Spindle from a text
I have a string like this: La Torre Eiffel paragonata all&#8217;Everest What PHP function
I am trying to render a haml file in a javascript response like so:
I have this code to decode numeric html entities to the UTF8 equivalent character.
I want use html5's new tag to play a wav file (currently only supported
I'm parsing an RSS feed that has an &#8217; in it. SimpleXML turns this

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.