Grasshopper

algorithmic modeling for Rhino

Hello everyone!

Lets say I have this data:

List:

  1. ListOfPoints = a
  2. ListOfPoints = b
  3. ListOfPoints = c
  4. ListOfPoints = d

Now what I'm trying to do is: swap two points in every list (a,b,c,d), but my approach is not working.

Here is my code:

List<List<Point3d>> currentGeneration = handoverPopulation.ToList();

foreach (List<Point3d> generation in currentGeneration)

{

  Random r = new Random();

  int index1;

  int index2;

  index1 = r.Next(0, generation.Count);

  index2 = r.Next(0, generation.Count);

  if (index1 != index2)

  {

    Point3d cache = generation[index1];

    generation[index1] = generation[index2];

    generation[index2] = cache;

  }

}

Why does it not work? The list before and after swapping are still the same (see Picture below). I tried it with a for Loop and put <Random> out of the Loop, however no difference.

Thanks for your help,

Tülin

Views: 1707

Replies to This Discussion

I can't see anything intrinsically wrong with the code, and since I can't replicate the problem I can't comment further. Perhaps lists are getting copied somehow? What type is handoverPopulation? How are you assigning outputs?

As a general rule though I'd recommend re-using a Random object as often as possible and construct it with a specific seed. If you don't use seeds then you won't be able to repeat a specific run, and if you construct new random instances quickly then they may end up using the same seed because if you don't supply one, the system clock will be used instead.

Oh I see now. You're not duplicating the lists of points so your two references are to the same list in memory. Ie. the swapping works just fine, BOTH outputs are swapped.

I'm unable to parse the intent of this code, can you elaborate what it is supposed to do:

int n = population[column].Count;
while (n > 0)
{
  byte[] box = new byte[1];
  do provider.GetBytes(box);
  while (!(box[0] < n * (255 / n)));
  int k = (box[0] % n);
  n--;
  Point3d value = individual[k];
  individual[k] = individual[n];
  individual[n] = value;
}

Is that just an attempt to randomize the individual?

Ok, then I guessed right. The code I posted shows how to randomize the order of an array, basically using the Array.Sort method and an key array of random bytes.

I attached a modified version which (amongst other changes) contains a DuplicatePopulation() method. You need to use this if you want to modify individuals in one generation without affecting individuals in other generations.

Attachments:

RSS

About

Translate

Search

Photos

  • Add Photos
  • View All

© 2024   Created by Scott Davidson.   Powered by

Badges  |  Report an Issue  |  Terms of Service