【问题标题】:Most efficient way to pick unique strings from weighted categories从加权类别中选择唯一字符串的最有效方法
【发布时间】:2018-07-04 12:06:59
【问题描述】:

设置:

  • n 个类别
  • 每个类别都有一个权重(表示该类别重要性的人工数字)
  • 每个字符串都是全局唯一的

示例:

  • 类别:a、b、c
  • 字符串:
    • a_001、a_002、a_003
    • b_001、b_002、b_003
    • c_001、c_002、c_003
  • 重量:
    • 一:1
    • b: 2
    • c: 1

任务:

获取一个唯一字符串数组,1个来自a类,2个来自b类,1个来自c类。从一个类别中挑选的字符串数量不必与 weightedNumber 完全一致。在挑选琴弦时,应该只考虑重量(尽管强烈)。但是,如果不可能,那也不是世界末日。但是,选择的字符串总数必须正确。

问题:

  • 权重可以是 10,但该类别中只有 3 个唯一字符串(在这种情况下,应根据权重填充其他类别的字符串)
  • 我正在使用 Firestore,因此我一次只能选择一个随机字符串,并且无法访问给定类别中的字符串数量

我的尝试:

function pickStrings(numberOfStrings, arrCategories) {
  // Calculates the weight of each category
  // Sets initial weight and stringsleft to weightTotal and numberOfStrings
  // Iterates over the categories:
  //    selectedStrings.push(...pickStringsFromCategory(calculatedNumberBasedOnWeight, categoryId))
  // returns selectedStrings
}

function pickStringsFromCategory(numberOfStrings, categoryid) {
  // Create a map of picked strings
  // Randomly pick a string from that category
  // Checks if the string was picked already
  // Tries again (up to 10 times) if the string was already picked
}

但是,这感觉不对。尝试 10 次是一个人为的数字,如果只有 1 个字符串且 weightedNumber 为 10 的类别是最后一个,则选择的字符串数小于 numberOfStrings。

关于如何改进这个算法的任何想法?

【问题讨论】:

  • 请将数据放入数据结构中。 - 并添加一些示例。
  • 问题是,没有真正的数据结构。我可以使用的只有“getRandomStringFromCategory()”,它直接从数据库中提取一个随机字符串,仅此而已。

标签: javascript arrays performance


【解决方案1】:

这是一种可能的方法:

var arr = [
  ["a_001", "a_002", "a_003"],
  ["b_001", "b_002", "b_003"],
  ["c_001", "c_002", "c_003"]
];

var weights = [7, 2, 1];

var str = "";
weights.map((o, i) => {

  let curr = i;
  let p = 0;
  for (let j = 0; j < o; j++) {
    if (arr[curr][p]) {//this could be and ajax, function, whatever
      str += arr[curr][p] + " ";//this is an assumption
      p++;
    } else { //this happens when we didn't find a string into such category 
      curr = curr + 1; //we move one category
      p = 0;//firs element in the next category
      j--;//move back because we didn't finish
    }
  }

})

console.log(str);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-10-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-09-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多