我正在使用 javascript 并試圖找出一種演算法,根據程式中的現有字串將增量數字附加到字串中。
輸入:
['Untitled Form', 'Untitled Form - 1', 'Untitled Form - 5', 'Untitled Form - 3', 'Untitled Form - 4', "Untitled Form"];
因此,假設用戶想要向此串列添加另一個字串,并且他們已選擇“無標題表單”作為要添加的字串。因此,給定輸入和現有串列,演算法將在串列中搜索以檢查是否缺少任何遞增數字,例如在上面的代碼中缺少“無標題表格 - 2”,它應該回傳“無標題表格 - 2”作為要添加的新字串。
輸出:
['Untitled Form', 'Untitled Form - 1', 'Untitled Form - 5', 'Untitled Form - 3', 'Untitled Form - 4', "Untitled Form - 2"];
它與在 Windows 資源管理器中不斷添加新檔案夾的功能相同(“新檔案夾 (1)”、“新檔案夾 (2)”等等)
我有這個問題的解決方案,但我認為它不是很有效,演算法還會檢查最高數字并在其后添加增量數字“無題表格 - 6”。
uj5u.com熱心網友回復:
您可以通過提取現有indexes并對其進行排序來實作,然后將每個索引與下一個進行比較,如果差異大于1,則您可以意識到該位置缺少索引。像這樣:
let list = ['Untitled Form', 'Untitled Form - 1', 'Untitled Form - 5', 'Untitled Form - 3', 'Untitled Form - 4'];
const findNextIndex = (arr)=> {
const sortedArr = arr.map(item => Number(item.split('-')[1] || 0)).sort((a,b)=> a-b);
if(!sortedArr.includes(0)) return 0;
let index = sortedArr[sortedArr.length-1] 1; //maximum value
for(let i =0; i< sortedArr.length; i ){
if(sortedArr[i 1] - sortedArr[i] > 1){
index = sortedArr[i] 1;
break;
}
}
return index;
}
const nextIndex = findNextIndex(list);
list = [...list, `Untitled Form${nextIndex ? ` - ${nextIndex}` : ''}`]
console.log(list)
uj5u.com熱心網友回復:
這應該作業
- 對陣列進行排序,使其變為
[
[0] => 'Untitled Form',
[1] => 'Untitled Form - 1',
[2] => 'Untitled Form - 2',
....
]
回圈,找到 indexInTitle 與陣列索引不匹配的索引。
如果找到,則回傳該索引否則增量索引,
const listMissing2 = ['Untitled Form', 'Untitled Form - 1', 'Untitled Form - 5', 'Untitled Form - 3', 'Untitled Form - 4'];
const listNotMissing = ['Untitled Form', 'Untitled Form - 1', 'Untitled Form - 5', 'Untitled Form - 3', 'Untitled Form - 4', 'Untitled Form - 2'];
const findMissingOrIncrementIndex = list => {
const sortedList = list.sort();
const missingIndex = sortedList.findIndex((title, index) => {
const [, indexInTitle] = title.split(' - ');
return index > 0 && Number(indexInTitle) !== index;
});
return (missingIndex > -1) ? missingIndex : list.length;
}
console.log(findMissingOrIncrementIndex(listMissing2));
console.log(findMissingOrIncrementIndex(listNotMissing));
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/397926.html
標籤:javascript 数组 反应 有角的 排序
上一篇:計算自定義游標之間的正確間隙
