2016-09-30 3 views
3

У меня есть массив родителей, которых я хочу сделать младенцами, и пустой массив (которого я должен быть фиксированной длиной), ожидающий заполнения.Как вы правильно распространяете детей?

Мне нужны дети - дети - должны быть равномерно распределены на основе того, насколько красивый их папа; Однако, мне нужно все, чтобы получить клон упаковывают их мутировавший ребенок уродливее/beautifuller, то Theres еще один шанс ... (parents.length <= children.length)

Родитель массив отсортирован по handsomeness, так parents[0] = me;. Что я сделал до сих пор:

for (var p = parents.legth; parent--;) { 
    var myself = parents[p], 
     aRandomDaddy = parents[~~(Math.random()*parents.length)] 
     iDeserveMoreThan1Child = parents.length-p; 
     // if this is 0 they're last in the array and just get their 1 clone. Should be different, right? 

    makeABabyWith(myself); 
    if (iDeserveMoreThan1Child) { 
     makeABabyWith(aRandomDaddy); 
    } 
} 

То, что я сейчас пытаюсь сделать, это выяснить способ алгоритмически makeABabyWith(aRandomDaddy), children.length - parents.length раз, и принимать во внимание то, как красивый в папочки есть.

Я думал, что делать:

for(var c = parents.length, totalHandsomeness = 0; c--;) 
    totalHandsomeness+= parents[c].handsomeness; 
... 

    makeABabyWith(myself); 
    for (var handsomenessComparedToEveryoneElse 
     = ~~(myself.handsomeness * children.length/totalHandsomeness); 
     handsomenessComparedToEveryoneElse--;) { 
     makeABabyWith(aRandomDaddy); 
    } 
... 

Теперь это дает распределение относительно их подтверждения, родителей. Однако, когда настил происходит, вы иногда получаете 0. Итак, если массив детей имеет длину 20, вы можете варьироваться очень широко.

Один из способов я думал о борьбе с этим является iteritively запустить эту foreloop, что-то вроде этого:

... 
var childrenToBeCreated = children.length - parents.length; 
... 

    makeABabyWith(myself); 

    while (childrenToBeCreated) for (var handsomenessComparedToEveryoneElse 
     = ~~(myself.handsomeness * children.length/totalHandsomeness); 
     handsomenessComparedToEveryoneElse--;) { 
     if (childrenToBeCreated) { 
      makeABabyWith(aRandomDaddy); 
      childrenToBeCreated--; 
     } else break; 
    } 

//EDIT: realised this would run to the end in the first loop and break, instead of run through all and check for left overs. 
//EDIT OF THE EDIT: no it wouldn't... 
//ED...: Yes it would, the while loops inside the for loop. 
... 

console.log("is","this"+"a good way to do it?? would this even work"); 

Хотя это написано в JS ИТС том же принципе, на любом языке.

Является ли метод, который я придумал при достаточном написании этого вопроса, и как бы вы это сделали?

Редактировать: Последний пример должен был использовать Процент childrenToBeCreated не ptotal, я думаю, что я запутался.

+12

'Как вы правильно распространяете детей? Это звучит скорее как юридический вопрос, а не программный. Звучит немного морально сомнительно. –

+3

Мне пришлось подняться на этот вопрос, и ваш комментарий @SamAxe. Помещение является горьким. Лол: «Мне нужны дети». LOL Родительский массив сортируется по удобству, поэтому 'родители [0] = me' –

+5

Весь этот вопрос является тайно рекламой с торговлей людьми. –

ответ

0

Что касается правовых последствий этого вопроса, вы должны связаться с адвокатом, но я думаю, что я могу помочь вам с техническими аспектами проблемы;)

светокопий для заводов по Kamino (альфа стадион):

var int = v => 0|v; 

//creates mostly average and below values, and fewer high values 
var randomHandsomeness =() => int(Math.pow(Math.random(), 2) * 100) + 1; 

var breedClone = (parent) => ({ 
    id: int(Math.random() * 0x80000000).toString(36), //no time for names 
    handsomeness: int(.25 * parent.handsomeness + .75 * randomHandsomeness()), //a bit genetic heritage but mostly luck 
    parent: parent //just for the record 
}); 

var deriveBatch = (parents, numClonesToBreed, minChildrenPerParent, distribution) => { 
    console.log("starting batch of", numClonesToBreed); 

    if(typeof minChildrenPerParent === "function"){ 
     distribution = minChildrenPerParent; 
     minChildrenPerParent = 0; 
    } 

    if(typeof distribution !== "function"){ 
     distribution = (handsomeness) => handsomeness; 
    } 

    minChildrenPerParent = Math.max(int(minChildrenPerParent), 0); 

    //I'll add these back in the loop 
    numClonesToBreed -= parents.length * minChildrenPerParent; 
    if(numClonesToBreed < 0){ 
     throw new Error("increase batch size, insufficient capacities for these specs"); 
    } 

    //order doesn't matter, only handsomeness in relation to the total handsomeness 
    var totalHandsomeness = parents.reduce((acc, p) => acc + distribution(p.handsomeness), 0); 

    return parents.reduce((newBatch, parent) => { 
     //this computation doesn't only compute the relative handsomeness of the parent to the group, 
     //and the amount of children he's entitled to, but also balances the delta 
     //between the computed value and the rounded numChildren 
     //(partial clones are of no use and are therefore avoided). 
     //At the same time it's important to neither overproduce nor stay short of the goal. 
     var handsomeness = distribution(parent.handsomeness); 
     var numChildren = Math.round(handsomeness/totalHandsomeness * numClonesToBreed); 
     totalHandsomeness -= handsomeness; 
     numClonesToBreed -= numChildren; 

     //add the minimum amount of children per parent to the computed/distributed numChildren 
     numChildren += minChildrenPerParent; 
     console.log("handsomeness: %i, children: %i", parent.handsomeness, numChildren); 

     while(numChildren--) newBatch.push(breedClone(parent)); 
     return newBatch; 
    }, []); 
} 

Пусть производство начнется:

//prepare a first batch 
var parents = deriveBatch([{ 
    id: "Jango Fett", 
    handsomeness: 75, 
    parent: null //file corrupted 
}], 10); 

//breed new clones from the parent batch 
//create 30 clones 
//create at least 1 clone per parent 
//and a weighting function how the handsomeness impacts the amount of children 
//pow < 1: handsome people get more children, but not that much more 
//pow = 1: linear correlation of handsomeness to distribution 
//pow > 1: handsome people get significantly more children 
var children = deriveBatch(parents, 30, 1, handsomeness => Math.pow(handsomeness, 1.25)); 

Отказ от ответственности: Этот объект не является за любые действия, выполняемые произведенными клонами под любой иностранной командой.

Я думаю, что большая часть кода должна объяснить себя и должна быть легко перенесена/применена к вашей кодовой базе. Добавлено несколько крючков и конфигов, чтобы иметь возможность манипулировать поведением/распределением алго.

+0

Отличное решение, это действительно элегантно –

+0

Можете ли вы заменить тип «% i» в javascript/console.log()? Или это функция ES6, поскольку я заметил, что вы использовали некоторые лямбда-функции. –

+0

@Tobiq [MDN: Console Using_string_substitutions] (https://developer.mozilla.org/en-US/docs/Web/API/Console#Using_string_substitutions) – Thomas

 Смежные вопросы

  • Нет связанных вопросов^_^