gpt4 book ai didi

javascript - 代码挑战 : Rename filenames if duplicates are present

转载 作者:行者123 更新时间:2023-11-30 12:06:48 25 4
gpt4 key购买 nike

我正在应对我在网上找到的编码挑战。我有第一个测试用例通过但第二个失败。我正在尝试确定我失败的第二个测试用例是否是拼写错误。

问题是:

You are given an array of desired filenames in the order of their creation. Since two files cannot have equal names, the one which comes later will have an addition to its name in a form of (k), where k is the smallest positive integer such that the obtained name is not used yet.

Return an array of names that will be given to the files.

测试用例:

1 - 传球:

  • 输入:["doc", "doc", "image", "doc(1)", "doc"]
  • 输出:["doc", "doc(1)", "image", "doc(1)(1)", "doc(2)"]

2 - 失败:

  • 输入:["a(1)","a(6)","a","a","a","a","a","a","a","一个","一个","一个"]
  • 输出:["a(1)","a(6)","a","a(2)","a(3)","a(4)","a (5)","a(7)","a(8)","a(9)","a(10)","a(11)"]

这是我通过第一个规范的代码:

function fileNaming(names) {
var finalArr = [],
obj = {};
names.forEach(function(val){

if(obj[val] === undefined){
if(finalArr.indexOf(val) === -1){
finalArr.push(val);
obj[val] = 0;
} else {
obj[val] = 1;
finalArr.push(val + "(" + obj[val] + ")" );
}

} else {
finalArr.push( val + "(" + (++obj[val]) + ")");
}
});
return finalArr;
}

问题:

  • 在第二个测试规范中,为什么没有 "a(1)(1)" 就像有一个 "doc(1)(1)" 这是打字错误吗?
  • 如果有人对改进我的方法或替代方法提出建议,我将非常感谢您的反馈。

最佳答案

这是一个更简单的方法。这个想法是将原始名称和生成的名称都存储在哈希表中:

f = function(xs) {

var c = {}, t = (x, n) => x + "(" + n + ")";

return xs.map(function(x) {
var n = c[x] || 0;

c[x] = n + 1;

if(!n)
return x;

while(c[t(x, n)])
n++;

c[t(x, n)] = 1;
return t(x, n);
});

};


q = ["doc", "doc", "image", "doc(1)", "doc", "doc"];
document.write('<pre>'+JSON.stringify(f(q)));

q = ["a(1)","a(6)","a","a","a","a","a","a","a","a","a","a"]
document.write('<pre>'+JSON.stringify(f(q)));

关于javascript - 代码挑战 : Rename filenames if duplicates are present,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34971980/

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