最好的方法来产生零件编号与范围选项



我有一个零件号,完成后看起来像这样:TCW-K1-A4-B21AA

唯一的常量是TCW-部分,其他的都指定了部件号的选项。我的最终目标是能够在csv文件中的每个配置中具有所有可能的部件号。我的编程技能有限,所以我尝试用javascript解决我的问题,使用下面的代码:

var tcwArray = [['TCW-'], 
['K', 'J', 'T', 'R', 'S', 'E'], 
['1-', '2-', '3-', '4-', '5-', '6-', '7-', '8-'], 
['A', 'B'], 
['1-', '2-', '3-', '4-', '5-', '6-', '7-', '8-', '9-'], 
['A', 'B', 'C', 'D'], 
['0', '1', '2', '3'], 
['0', '1', '2'], 
['1', 'A', 'B', 'C', 'D', 'E'], 
['A', 'B']];
function allPossibleCases(arr) {
    if (arr.length === 0) {
        return [];
    }
    else if (arr.length === 1){
        return arr[0];
    }
    else {
        var result = [];
        var allCasesOfRest = allPossibleCases(arr.slice(1)); //recur with the rest of array
        for (var c in allCasesOfRest) {
            for (var i = 0; i < arr[0].length; i++) {
                result.push(arr[0][i] + allCasesOfRest[c]);
            }
        }
        return result;
    }
}
var r=allPossibleCases(tcwArray);

这对我不起作用,很可能是由于内存限制。我的问题是,有没有一种更好的语言能让我学得更快?

只有当数字完全时才可以追加结果(或者像Justin提到的那样存储在文件中)

var results = [];
function allPossibleCases(arr, number) {
    if (arr.length === 0) {
        return result.push(number);
    }
    else {
        var first = arr[0];
        var rest = arr.slice(1);
        for (var i = 0; i < first.length; i++) {
            allPossibleCases(rest, number + first[i]);
        }
    }
}

其他语言而言,Python相对容易入门。下面是在Python中的实现:

all_descriptors = [
    ['TCW-'],
['K', 'J', 'T', 'R', 'S', 'E'],
['1-', '2-', '3-', '4-', '5-', '6-', '7-', '8-'],
['A', 'B'],
['1-', '2-', '3-', '4-', '5-', '6-', '7-', '8-', '9-'],
['A', 'B', 'C', 'D'],
['0', '1', '2', '3'],
['0', '1', '2'],
['1', 'A', 'B', 'C', 'D', 'E'],
['A', 'B']
]
all_part_numbers = []
# Recursive part number generator, all possible permutations for given list of descriptor lists
#   descriptors - the list of lists of descriptors
#   part_number - the part number string which has descriptors added to it with each recursion
def generate_permutations(descriptors, part_number):
    if len(descriptors) == 1:  # this is the farthest right descriptor
        for char_descriptor in descriptors[0]:
            # finish up, add last character descriptor to part number
            all_part_numbers.append(part_number + char_descriptor)
    else:
        for char_descriptor in descriptors[0]:
            # call this function recursively with the descriptor fields to the right of current field
            #     and append current descriptor to end of part_number
            generate_permutations(descriptors[1:], part_number + char_descriptor)
generate_permutations(all_descriptors, "")
outfile = open("part_numbers.csv", 'w')
for part_number in all_part_numbers[0:-1]:
    print("{},".format(part_number), file=outfile, end="")
# separate printing of last element so there is no comma at the end
print("{}".format(all_part_numbers[-1]), file=outfile, end="")

为了节省内存,可以跳过将部分数字附加到all_part_numbers后,直接打印到文件中。但是,您必须找到一种方法来避免最后一部分数字上的尾随逗号。也许这并不重要。

最新更新