2016-10-12 2 views
2

지난 주 나는 내가하고있는 간단한 프로그램에 약간의 문제가 있었고 여기 누군가가 나를 도왔습니다. 이제 다른 문제가 생겼습니다. 가중치 확률과 값을 사용하여 배열의 항목 찾기

var findItem = function(desiredItem) { 
 
    var items = [ 
 
     { item: "rusty nail", probability: 0.25 }, 
 
     { item: "stone", probability: 0.23 }, 
 
     { item: "banana", probability: 0.20 }, 
 
     { item: "leaf", probability: 0.17 }, 
 
     { item: "mushroom", probability: 0.10 }, 
 
     { item: "diamond", probability: 0.05 } 
 
    ]; 
 
    var possible = items.some(({item, probability}) => 
 
      item === desiredItem && probability > 0); 
 
    if (!possible) { 
 
     console.log('There is no chance you\'ll ever find a ' + desiredItem); 
 
     return; 
 
    } 
 
    var sum = items.reduce((sum, {item, probability}) => sum+probability, 0); 
 
    while (true) { 
 
     var value = Math.random() * sum; 
 
     var lootedItem = items.find( 
 
       ({item, probability}) => (value -= probability) <= 0).item; 
 
     if (lootedItem === 'diamond') break; 
 
     console.log("Dang! A " + lootedItem + " was found..."); 
 
    } 
 
    console.log("Lucky! A " + desiredItem + " was found!"); 
 
} 
 

 
findItem('diamond');
지금 나는 items 배열에 category라는 또 다른 값을 추가하여이를 확장하고 싶습니다 나는 현재이 코드가 있습니다. 카테고리의 값을 2, 5 또는 10으로 지정합니다. 따라서 diamond 항목이 category: 10에 속하고 findItem이 실행될 때 동일한 카테고리에 속한 항목 만 찾을 수 있다고 가정 해 봅시다. 나는 지금 이틀 동안 노력하고 있지만 내 머리를 감당할 수없는 것 같습니다. 어쩌면 누군가 나를 올바른 방향으로 밀어 넣을 수 있습니까? 사전에 감사

당신은 그 코드에이 업데이트를 사용할 수
+0

검색을 주어진 카테고리로 제한하려면 ['filter'] (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter)를 사용 하시겠습니까? –

+0

"Dang!"메시지는 해당 카테고리에서만 발생할 수 있으며 다른 모든 항목은 완전히 무시되어야한다는 *을 발견 할 수 있습니까? – trincot

+0

고마워요, 제가 살펴볼 것입니다! –

답변

3

:

// Pass the item list and the desired category as arguments: 
 
var findItem = function(items, category, desiredItem) { 
 
    // apply filter to items, so only those of the given category remain: 
 
    items = items.filter(item => item.category == category); 
 
    // rest of code remains the same: 
 
    var possible = items.some(({item, probability}) => 
 
      item === desiredItem && probability > 0); 
 
    if (!possible) { 
 
     console.log('There is no chance you\'ll ever find a ' + desiredItem); 
 
     return; 
 
    } 
 
    var sum = items.reduce((sum, {item, probability}) => sum+probability, 0); 
 
    var t = 10; 
 
    while (true) { 
 
     var value = Math.random() * sum; 
 
     var lootedItem = items.find( 
 
       ({item, probability}) => (value -= probability) <= 0).item; 
 
     if (lootedItem === desiredItem) break; // fixed this condition! 
 
     console.log("Dang! A " + lootedItem + " was found..."); 
 
     t--; if (t <= 0) throw "loop"; 
 
    } 
 
    console.log("Lucky! A " + desiredItem + " was found!"); 
 
} 
 

 
// Define items here with their category 
 
var items = [ 
 
    { item: "rusty nail", probability: 0.25, category: 2 }, 
 
    { item: "stone",  probability: 0.23, category: 2 }, 
 
    { item: "banana",  probability: 0.20, category: 2 }, 
 
    { item: "leaf",  probability: 0.17, category: 5 }, 
 
    { item: "mushroom", probability: 0.10, category: 5 }, 
 
    { item: "diamond", probability: 0.05, category: 10 } 
 
]; 
 

 
// Call function with extra arguments: 
 
findItem(items, 5, 'mushroom'); 
 

 
console.log('second run:'); 
 
// This will obviously give a hit immediately, as there is only one possible item: 
 
findItem(items, 10, 'diamond');

변경 사항은 다음과 같습니다 함수에

  • 패스 이상의 인수 : 항목 목록과 원하는 범주
  • fu의 첫 번째 작업으로 항목 목록에 필터 적용 nt
  • lootedItem 테스트와 관련된 문제 수정 - "다이아몬드"가 하드 코딩되어 있습니다.
  • 함수 외부에서 항목 목록을 정의하고 각 요소에 범주 값을 추가하십시오.
  • 함수의 호출을 수정하여 추가 인수를 전달합니다.
+0

많은 분들께 감사 드리며 모든 것이 무엇을했는지 설명해 주셔서 감사합니다. 나는 지금 코딩에 대해 조금 더 알고있는 것처럼 느껴진다. –

1

원하십니까?

var items = [ { item: "rusty nail", probability: 0.25, category: 10 } 
 
      , { item: "stone",  probability: 0.23, category: 5 } 
 
      , { item: "banana",  probability: 0.20, category: 2 } 
 
      , { item: "leaf",  probability: 0.17, category: 5 } 
 
      , { item: "mushroom", probability: 0.10, category: 2 } 
 
      , { item: "diamond", probability: 0.05, category: 10 } 
 
      ]; 
 

 
findItem("diamond", items); 
 

 
function findItem(needle, haystack) { 
 
    var item = haystack.find(thing => thing.item === needle && 
 
             thing.probability > 0); 
 

 
    if (item) { 
 
     var category = item.category; 
 
     var items = haystack.filter(thing => thing.category === category); 
 
     var sum = items.reduce((sum, thing) => sum + thing.probability, 0); 
 

 
     var value = sum * Math.random(); 
 
     var loot = items.find(thing => (value -= thing.probability) <= 0).item; 
 

 
     while (loot !== needle) { 
 
      value = sum * Math.random(); 
 
      console.log("Dang! A " + loot + " was found..."); 
 
      loot = items.find(thing => (value -= thing.probability) <= 0).item; 
 
     } 
 

 
     return console.log("Lucky! A " + needle + " was found!"); 
 
    } 
 

 
    console.log("There's no chance that you'll ever find a " + needle); 
 
}

코드에서 유일한 큰 차이는 내가 검색을 제한하는 filter을 사용한다는 것입니다.

+0

그 점을 지적 해 주셔서 감사합니다! :) –