Skip to content

Instantly share code, notes, and snippets.

@zenozeng
Last active August 29, 2015 14:05
Show Gist options
  • Save zenozeng/bbe89868d12e3ee13e7b to your computer and use it in GitHub Desktop.
Save zenozeng/bbe89868d12e3ee13e7b to your computer and use it in GitHub Desktop.
javascript
// Sort by fitness
// JSON.stringify([[5, 3], [2, "string"], [4, 1]].sort())
// "[[2,"string"],[4,1],[5,3]]"
// `a` and `b` are sorted by `a.toString()` - `b.toString()`
// See also: http://www.ecma-international.org/ecma-262/5.1/#sec-15.4.4.11
// 所以是不靠谱的:
// ["190", (2000000000000000000000000).toString(), (1000000000000000000000000000000000000).toString()].sort()
// ["190", "1e+36", "2e+24"]
this.population = this.population.map(function(individual) {
return [self.fitness(individual), individual];
}).sort().map(function(elem) {
return elem[1];
});
[200000000000000000, 10000000000000000000000000000].sort();
// => [1e+28, 200000000000000000]
// 因为 es 标准规定这个必须要通过 toString() 来排序
// http://www.ecma-international.org/ecma-262/5.1/#sec-9.8.1
// http://www.ecma-international.org/ecma-262/5.1/#sec-15.4.4.11
[200000000000000000, 10000000000000000000000000000].sort(function(a, b) {return a - b;});
// => [200000000000000000, 1e+28]
@zenozeng
Copy link
Author

Use this:

    var fitness = this.population.map(function(individual, i) {
        return {index: i, fitness: self.fitness(individual)};
    }).sort(function(a, b) {
        return b.fitness - a.fitness;
    });

    var population = fitness.map(function(e, i) {
        return this.population[i];
    });

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment