gpt4 book ai didi

javascript - 从加权类别中选择唯一字符串的最有效方法

转载 作者:行者123 更新时间:2023-11-29 23:19:41 25 4
gpt4 key购买 nike

设置:

  • 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。从一个类别中选取的字符串的数量不必与加权数字完全一致。在挑选琴弦时,应该只考虑(虽然强烈)重量。但是,如果不可能,那也不是世界末日。但是,选择的字符串总数必须是正确的。

问题:

  • 权重可能是 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。

关于如何改进这个算法有什么想法吗?

最佳答案

这里有一个可能的方法:

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

关于javascript - 从加权类别中选择唯一字符串的最有效方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51173340/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com