2016-09-30 3 views
3

나는 아기를 만들고 싶어하는 부모님의 배열을 가지고 있고, 빈 배열 (그 중 고정 된 길이가되어야 함)이 채워지 길 기다리고 있습니다.어떻게 아이들을 적절하게 분배합니까?

나는 아빠가 얼마나 잘 생겼는지에 따라 아기 - 어린이 -를 골고루 배부해야합니다. 그러나 나는 돌연변이가 된 아이가 더럽고 더 아름답다는 것을 알기 위해 모두를 필요로한다. (parents.length <= children.length)

부모 배열은 핸섬으로 정렬되어 있으므로 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); 
    } 
... 

지금이 부모의 자신의 percantage에 배포 상대를 제공합니다. 그러나 마루가 생기면 0이되는 경우가 있습니다. 어린이 배열의 길이가 20 인 경우 자손이 매우 넓게 나타납니다.

... 
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의 동일한 원리로 작성되어 있지만 :이 대항 생각

한 가지 방법은 iteritively, 이런 식으로 뭔가를이 foreloop을 실행하는 것입니다.

이 질문을 작성하는 동안 필자가 생각한 방법이며, 어떻게 작성합니까?

편집 : 마지막 예는 childrenToBeCreated이 아닌 백분율을 사용하는 것이고, 나는 혼란 스럽다고 생각합니다. 이 질문에 변호사에게 문의해야합니다,하지만 난 문제의 기술적 측면에 당신을 도울 수 있다고 생각의 법적 의미에 대해서는

+12

'어떻게 아이들을 적절하게 배포합니까? '이것은 프로그래밍보다는 법적인 질문처럼 들립니다. 조금 도덕적으로 모호한 것 같습니다. –

+3

나는이 질문과 @SamAxe에 대한 의견을 upvote해야만했다. 전제는 신 테러리즘입니다. Lol '나는 아기가 필요해.' LOL 부모 배열은 잘 다듬어 져 있습니다. 그래서'parents [0] = me' –

+5

이 모든 질문은 몰래 인신 매매 광 고라는 것입니다. –

답변

0

) 카미노 (알파 경기장)에있는 공장에 대한

청사진 :

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)); 

면책 조항 :이 기능은 아니다 외국 명령하에 생산 된 복제물에 의해 수행 된 모든 행위에 대해 책임을진다.

나는 대부분의 코드가 자신을 설명해야하고, 쉽게 코드베이스에 이식/적용되어야한다고 생각한다. algo의 동작/배포를 조작 할 수 있도록 몇 가지 후크 및 구성을 추가했습니다.

+0

멋진 솔루션, 정말 세련됨 –

+0

javascript/console.log()에서 "% i"유형을 대체 할 수 있습니까? 또는 일부 람다 함수를 사용함을 알았을 때 ES6 기능입니다. –

+0

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

관련 문제