简体   繁体   English

我如何解决这个算法?

[英]How do I go about solving this algorithm?

I've been struggling with this question for a while now and have no idea how to go about it.我一直在努力解决这个问题一段时间,不知道如何 go 关于它。 The aim is to create unique device names.目的是创建唯一的设备名称。 If a device already exists with a similar name, return an integer incremented by 1 for each occurrence.如果已存在具有相似名称的设备,则返回 integer,每次出现时加 1。

Input: ['lamp', 'lamp', 'tv', 'lamp']输入:['灯','灯','电视','灯']

Expected Output: ['lamp', 'lamp1', 'tv', 'lamp2']预期 Output:['lamp','lamp1','tv','lamp2']

How should I go about this?我应该如何 go 关于这个?

You could create an object keyed by the original string, and with corresponding value a counter that starts at zero.您可以创建一个以原始字符串为键的 object,并使用相应的值创建一个从零开始的计数器。 Then perform a map of the original data by adding that counter (if it is non-zero) and at the same time incrementing that counter:然后通过添加该计数器(如果它非零)并同时增加该计数器来执行原始数据的 map:

 let data = ['lamp', 'lamp', 'tv', 'lamp']; let counters = Object.fromEntries(data.map(str => [str, 0])); let result = data.map(str => str + (counters[str]++ || "")); console.log(result);

function myAlg(list){
    // You must create a memory in order to have the following index.
    var memo = {};
    // Let's create another result variable
    var newList = [];
    // Iterate the elements (there are only 2 casuistries)
    for(var elem of list){
        if(typeof memo[elem] === 'undefined'){
            memo[elem] = 0;
            newList.push(elem);
        } else {
            memo[elem]++;
            newList.push(elem+memo[elem]);
        }
    }
        return newList;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM